Solved

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

Posted on 2012-03-17
4
266 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
groupSum6 challenge 6 77
How can I do a Massively massive community reviewing-and-grading site? 7 71
unix in java example 9 55
simple java question 3 44
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
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…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

863 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

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now