Solved

java: why do I get two values when selecting a table row?

Posted on 2012-03-17
4
272 Views
Last Modified: 2012-06-21
Hello Experts,

why do I get two values when selecting a row?
I get the following:
value selected: value 0
value selected: value 0
value selected: value 1
value selected: value 1
value selected: value 2
value selected: value 2
value selected: value 3
value selected: value 3

I want the return to be only one...

code below:
public class SplitPaneExample extends JFrame implements ActionListener {
	
	private static final long serialVersionUID = 1L;
	JMenu menu;
	JMenuItem menuOpen, menuSave, menuQuit;
	JMenuBar menuBar;
	
	JFileChooser fileChoose;
	File file;
	FileReader fileReader;
	BufferedReader bufferReader;
	StringBuffer stringBuffer;
	
	JTextArea bottomArea, topLeft, topRight;
	JScrollPane scrollPane;
	
	JSplitPane hSplit, vSplit;
	JPanel mainPanel, leftPanel, rightPanel;
	
	JTable myLeftTable;
	JScrollPane myLeftTableScrollPane;
	@SuppressWarnings("rawtypes")
	Vector<Vector> leftTableContainer, rightTableContainer, bottomTableContainer;
	Vector<String> leftTableValues, rightTableValues, leftTableColumnName;

	
	public SplitPaneExample(){
		createUserInterface();
	}

	private void createUserInterface() {		
		setFrame();
		setPanels();		
	}
	
	public void setFrame(){
		//set frame/window title, background color, dimensions...
		setTitle("test - top left and table listeners...");
		setBackground(Color.white);
		setPreferredSize(new Dimension(600, 500));
		setVisible(true);
	}
	
	public void setPanels(){
		//set text areas
		topLeft = new JTextArea();
		topLeft.setText("topLeft...");
		topLeft.setAlignmentX(CENTER_ALIGNMENT);
		
		topRight = new JTextArea();
		topRight.setText("topRight...");
		topRight.setAlignmentX(CENTER_ALIGNMENT);
		
		bottomArea = new JTextArea();
		bottomArea.setText("bottomArea...");
		bottomArea.setAlignmentX(CENTER_ALIGNMENT);
		
		//split panes		
		vSplit = new JSplitPane();
		vSplit.setOrientation(JSplitPane.VERTICAL_SPLIT);
		vSplit.setDividerSize(3);
		vSplit.setDividerLocation(200);
		
		hSplit = new JSplitPane();
		hSplit.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
		hSplit.setDividerSize(3);	
		hSplit.setDividerLocation(130);
		
		// add table to left component
		leftTableValues = new Vector<String>();
		leftTableValues.add("value 0");
		leftTableValues.add("value 1");
		leftTableValues.add("value 2");
		leftTableValues.add("value 3");
		
		hSplit.setLeftComponent(getLeftTable());
		hSplit.setRightComponent(topRight);
		
		vSplit.setLeftComponent(hSplit);
		vSplit.setRightComponent(bottomArea);
		
		//add vertical split: vSplit to content_pane
		Container content_pane = getContentPane();
		content_pane.add(vSplit, BorderLayout.CENTER);
	}
	
	public JScrollPane getLeftTable(){
		myLeftTable = new JTable(getLeftTableValues(), getColumnName());
		myLeftTable.setCellSelectionEnabled(true);
		
		ListSelectionModel cellSelectionModel = myLeftTable.getSelectionModel();
	    cellSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		cellSelectionModel
				.addListSelectionListener(new ListSelectionListener() {
					public void valueChanged(ListSelectionEvent e) {

						String valueSelected = null;
						int selectedRow = myLeftTable.getSelectedRow();
						valueSelected = leftTableValues.get(selectedRow);

						System.out.println("value selected: " + valueSelected);
					}
				});
	    
		myLeftTableScrollPane = new JScrollPane(myLeftTable);
		return myLeftTableScrollPane;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Vector<Vector> getLeftTableValues(){		
		if(leftTableContainer == null){
			
			leftTableContainer = new Vector<Vector>();
			
			//left table values
			Vector[] v = new Vector[leftTableValues.size()];
			for(int x=0; x < leftTableValues.size(); x++){				
				v[x] = new Vector<String>();
				v[x].add(leftTableValues.get(x));
				leftTableContainer.add(v[x]);
			}	
			
			return leftTableContainer;
			
		} else {
			return leftTableContainer;
		}
	}
	
	public Vector<String> getColumnName(){
		if(leftTableColumnName == null){			
			leftTableColumnName = new Vector<String>();
			leftTableColumnName.add("values:");			
			return leftTableColumnName;			
		} else {
			return leftTableColumnName;
		}
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		
	}
	
	public static void main(String args[]) {
		// Create an instance of the test application
		SplitPaneExample frame = new SplitPaneExample();
		frame.pack();
		frame.setVisible(true);
	}

}

Open in new window

0
Comment
Question by:epifanio67
  • 3
4 Comments
 
LVL 47

Assisted Solution

by:for_yan
for_yan earned 500 total points
ID: 37733284
check this answer:

http://stackoverflow.com/questions/5865343/why-does-jtable-always-trigger-listselectionlistener-twice

Look at the event that is passed to your listener, specifically

ListSelectionEvent.getValueIsAdjusting()

perform whatever ops you want to do when this returns false.
link|improve this answer
      
answered May 3 '11 at 5:22
MeBigFatGuy
6,9661715
      
      
Thanks... This solve the problem... –
0
 
LVL 47

Accepted Solution

by:
for_yan earned 500 total points
ID: 37733295
this does it only once:

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Vector;

public class SplitPaneExample1 extends JFrame implements ActionListener {

	private static final long serialVersionUID = 1L;
	JMenu menu;
	JMenuItem menuOpen, menuSave, menuQuit;
	JMenuBar menuBar;

	JFileChooser fileChoose;
	File file;
	FileReader fileReader;
	BufferedReader bufferReader;
	StringBuffer stringBuffer;

	JTextArea bottomArea, topLeft, topRight;
	JScrollPane scrollPane;

	JSplitPane hSplit, vSplit;
	JPanel mainPanel, leftPanel, rightPanel;

	JTable myLeftTable;
	JScrollPane myLeftTableScrollPane;
	@SuppressWarnings("rawtypes")
	Vector<Vector> leftTableContainer, rightTableContainer, bottomTableContainer;
	Vector<String> leftTableValues, rightTableValues, leftTableColumnName;


	public SplitPaneExample1(){
		createUserInterface();
	}

	private void createUserInterface() {
		setFrame();
		setPanels();
	}

	public void setFrame(){
		//set frame/window title, background color, dimensions...
		setTitle("test - top left and table listeners...");
		setBackground(Color.white);
		setPreferredSize(new Dimension(600, 500));
		setVisible(true);
	}

	public void setPanels(){
		//set text areas
		topLeft = new JTextArea();
		topLeft.setText("topLeft...");
		topLeft.setAlignmentX(CENTER_ALIGNMENT);

		topRight = new JTextArea();
		topRight.setText("topRight...");
		topRight.setAlignmentX(CENTER_ALIGNMENT);

		bottomArea = new JTextArea();
		bottomArea.setText("bottomArea...");
		bottomArea.setAlignmentX(CENTER_ALIGNMENT);

		//split panes
		vSplit = new JSplitPane();
		vSplit.setOrientation(JSplitPane.VERTICAL_SPLIT);
		vSplit.setDividerSize(3);
		vSplit.setDividerLocation(200);

		hSplit = new JSplitPane();
		hSplit.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
		hSplit.setDividerSize(3);
		hSplit.setDividerLocation(130);

		// add table to left component
		leftTableValues = new Vector<String>();
		leftTableValues.add("value 0");
		leftTableValues.add("value 1");
		leftTableValues.add("value 2");
		leftTableValues.add("value 3");

		hSplit.setLeftComponent(getLeftTable());
		hSplit.setRightComponent(topRight);

		vSplit.setLeftComponent(hSplit);
		vSplit.setRightComponent(bottomArea);

		//add vertical split: vSplit to content_pane
		Container content_pane = getContentPane();
		content_pane.add(vSplit, BorderLayout.CENTER);
	}

	public JScrollPane getLeftTable(){
		myLeftTable = new JTable(getLeftTableValues(), getColumnName());
		myLeftTable.setCellSelectionEnabled(true);

		ListSelectionModel cellSelectionModel = myLeftTable.getSelectionModel();
	    cellSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		cellSelectionModel
				.addListSelectionListener(new ListSelectionListener() {
					public void valueChanged(ListSelectionEvent e) {
                       if((!e.getValueIsAdjusting())){

						String valueSelected = null;
						int selectedRow = myLeftTable.getSelectedRow();
						valueSelected = leftTableValues.get(selectedRow);

						System.out.println("value selected: " + valueSelected);
					}
                    }
				});

		myLeftTableScrollPane = new JScrollPane(myLeftTable);
		return myLeftTableScrollPane;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Vector<Vector> getLeftTableValues(){
		if(leftTableContainer == null){

			leftTableContainer = new Vector<Vector>();

			//left table values
			Vector[] v = new Vector[leftTableValues.size()];
			for(int x=0; x < leftTableValues.size(); x++){
				v[x] = new Vector<String>();
				v[x].add(leftTableValues.get(x));
				leftTableContainer.add(v[x]);
			}

			return leftTableContainer;

		} else {
			return leftTableContainer;
		}
	}

	public Vector<String> getColumnName(){
		if(leftTableColumnName == null){
			leftTableColumnName = new Vector<String>();
			leftTableColumnName.add("values:");
			return leftTableColumnName;
		} else {
			return leftTableColumnName;
		}
	}

	//@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub

	}

	public static void main(String args[]) {
		// Create an instance of the test application
		SplitPaneExample1 frame = new SplitPaneExample1();
		frame.pack();
		frame.setVisible(true);
	}

}

Open in new window

0
 
LVL 47

Assisted Solution

by:for_yan
for_yan earned 500 total points
ID: 37733394
check this:

http://docs.oracle.com/javase/6/docs/api/javax/swing/event/ListSelectionEvent.html#getValueIsAdjusting%28%29

getValueIsAdjusting

public boolean getValueIsAdjusting()

    Returns whether or not this is one in a series of multiple events, where changes are still being made. See the documentation for ListSelectionModel.setValueIsAdjusting(boolean) for more details on how this is used.

    Returns:
        true if this is one in a series of multiple events, where changes are still being made


----------------------

then go to your original code - then click on the upper row and drag the mouse down to the bottom
You'll see each time you cross the row - it prints the event

now go to the code with modification I posted above
do the same thing - you'll see only when you reach the last row it will printout the
value selected event.

So this getValueIsAdjusting()  is a pretty useful method
0
 

Author Closing Comment

by:epifanio67
ID: 37733497
thank you so much for_yan....

regards,
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
eclipse shortcuts 9 63
session migration servlets 2 42
javap bin 2 41
How to execute a Python program and gather return output in Java 2 40
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

828 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question