Solved

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

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

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Convert ArrayList of custom objects to JSON 4 53
countX 22 70
parentbit challenge 3 52
for i loop in grovy 1 32
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…

760 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

19 Experts available now in Live!

Get 1:1 Help Now