?
Solved

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

Posted on 2012-03-17
4
Medium Priority
?
288 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
4 Comments
 
LVL 47

Assisted Solution

by:for_yan
for_yan earned 2000 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 2000 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 2000 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

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

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

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…
The viewer will learn how to implement Singleton Design Pattern in Java.
This video teaches viewers about errors in exception handling.
Suggested Courses

718 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