3 Replies - 1023 Views - Last Post: 07 June 2014 - 01:19 AM Rate Topic: **--- 3 Votes

#1 incredibleX  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 212
  • Joined: 01-November 13

JTable specific cell selected

Posted 06 June 2014 - 12:58 PM

I want perform some calculations whenever a specific cell block is focused in JTable, I've tried using focusListener on JTable but looks like my table isn't triggering the event.
I don't know why, what to do?
Is This A Good Question/Topic? 0
  • +

Replies To: JTable specific cell selected

#2 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10803
  • View blog
  • Posts: 40,269
  • Joined: 27-December 08

Re: JTable specific cell selected

Posted 06 June 2014 - 03:32 PM

You should look into adding a ListSelectionListener to the ListSelectionModel of the JTable.

I came across a sample here.
Was This Post Helpful? 0
  • +
  • -

#3 x68zeppelin80x  Icon User is offline

  • D.I.C Addict

Reputation: 130
  • View blog
  • Posts: 576
  • Joined: 07-March 09

Re: JTable specific cell selected

Posted 06 June 2014 - 04:16 PM

Sorry for the length of code, but I grabbed the base of this code right out of the Oracle docs.

Here is the class that this is modeled after: TableDemo.java

You will essentially be grabbing the selected row and column from the table. I added a matrix to keep track of where you clicked. It is important to know that the columns are generated statically, so moving them around may cause the printing to be incorrect.
table.addMouseListener(new MouseAdapter() {
	public void mouseClicked(MouseEvent e) {
		if (e.getClickCount() == 1) {
			JTable target = (JTable) e.getSource();
			int row = target.getSelectedRow();
			int col = target.getSelectedColumn();

			lastClicked.setText(String.format(
					"Clicked: Cell[%d][%d] => %s%n",
					row, col, getModelValue(row, col)));
				
			stats[row][col]++;
				
			if (DEBUG) printStats();
		}
	}
});


Here is an example of the code running:

Posted Image

/*
 * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle or the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * TableDemo.java requires no other files.
 */

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

/**
 * TableDemo is just like SimpleTableDemo, except that it uses a custom
 * TableModel.
 */
public class TableDemo extends JPanel {
	private static final long serialVersionUID = 1L;
	private static final boolean DEBUG = true;
	private JTable table = new JTable(new EmployeeTableModel());
	private JLabel lastClicked = new JLabel("Clicked: ");
	
	private final int ROWS = 6;
	private final int COLS = 5;
	private int[][] stats = new int[ROWS][COLS];
	
	public TableDemo() {
		super(new BorderLayout(0, 8));
		
		table.setPreferredScrollableViewportSize(new Dimension(400, 95));
		table.setFillsViewportHeight(true);

		table.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 1) {
					JTable target = (JTable) e.getSource();
					int row = target.getSelectedRow();
					int col = target.getSelectedColumn();

					lastClicked.setText(String.format(
							"Clicked: Cell[%d][%d] => %s%n",
							row, col, getModelValue(row, col)));
					
					stats[row][col]++;
					
					if (DEBUG) printStats();
				}
			}
		});

		// Create the scroll pane and add the table to it.
		JScrollPane scrollPane = new JScrollPane(table);

		// Add the scroll pane to this panel.
		add(scrollPane, BorderLayout.CENTER);
		add(lastClicked, BorderLayout.SOUTH);
		
		for (int r = 0; r < ROWS; r++) {
			for (int c = 0; c < COLS; c++) {
				stats[r][c] = 0;
			}
		}
	}
	
	public void printStats() {
		for (int r = 0; r < ROWS; r++) {
			for (int c = 0; c < COLS; c++) {
				System.out.printf("%3d, ", stats[r][c]);
			}
			System.out.println();
		}
		System.out.println("--------------------------");
	}
	
	public EmployeeTableModel getModel() {
		return (EmployeeTableModel) table.getModel();
	}
	
	public Object getModelValue(int row, int col) {
		return getModel().getValueAt(row, col);
	}

	enum EmployeeType {
		ADMIN("Administrator"), MGMT("Management"), SE("System Engineer"),
		MKTG("Marketing"), DEV("Developer");

		private String formalName;

		private EmployeeType(String formalName) {
			this.formalName = formalName;
		}

		public String getFormalName() {
			return formalName;
		}

		@Override
		public String toString() {
			return formalName;
		}
	}

	class Employee {
		private final NumberFormat formatter = NumberFormat.getCurrencyInstance();
		
		private String givenName;
		private String surName;
		private EmployeeType type;
		private Double wage;
		private Boolean vested;

		public Employee(String givenName, String surName, EmployeeType type,
				Double wage, Boolean vested) {
			this.givenName = givenName;
			this.surName = surName;
			this.type = type;
			this.wage = wage;
			this.vested = vested;
		}

		@Override
		public String toString() {
			return "Employee [givenName=" + givenName + ", surName=" + surName
					+ ", type=" + type + ", wage=" + wage + ", vested="
					+ vested + "]";
		}

		public String getGivenName() {
			return givenName;
		}

		public String getSurName() {
			return surName;
		}

		public EmployeeType getType() {
			return type;
		}

		public Double getWage() {
			return wage;
		}

		public Boolean getVested() {
			return vested;
		}
		
		public String getFormattedWage() {
			return formatter.format(wage.doubleValue());
		}
	}

	class EmployeeTableModel extends AbstractTableModel {
		private static final long serialVersionUID = 1L;
		private String[] columnNames = { "Given Name", "Sur Name", "Type",
				"Wage", "Vested" };
		private List<Employee> employees;
		
		private EmployeeTableModel() {
			employees = new ArrayList<Employee>();

			addRecord("JAMES", "SMITH", EmployeeType.ADMIN, 90000.00, true);
			addRecord("JOHN", "JOHNSON", EmployeeType.MGMT, 78000.00, true);
			addRecord("MARY", "WILLIAMS", EmployeeType.MKTG, 60000.00, true);
			addRecord("LINDA", "BROWN", EmployeeType.SE, 75000.00, false);
			addRecord("LISA", "JONES", EmployeeType.DEV, 70000.00, true);
			addRecord("PAUL", "MILLER", EmployeeType.DEV, 65000.00, false);
		}

		private void addRecord(String givenName, String surName,
				EmployeeType type, Double wage, Boolean vested) {
			employees.add(new Employee(givenName, surName, type, wage, vested));
		}

		public int getColumnCount() {
			return 5;
		}

		public int getRowCount() {
			return employees.size();
		}

		public String getColumnName(int col) {
			return columnNames[col];
		}

		public Object getValueAt(int row, int col) {
			Employee employee = employees.get(row);

			switch (col) {
				case 0: return employee.getGivenName();
				case 1: return employee.getSurName();
				case 2: return employee.getType();
				case 3: return employee.getFormattedWage();
				case 4: return employee.getVested();
			}
			
			return null;
		}

		/*
		 * JTable uses this method to determine the default renderer/ editor for
		 * each cell. If we didn't implement this method, then the last column
		 * would contain text ("true"/"false"), rather than a check box.
		 */
		public Class<?> getColumnClass(int c) {
			return getValueAt(0, c).getClass();
		}

		/*
		 * Don't need to implement this method unless your table's editable.
		 */
		public boolean isCellEditable(int row, int col) {
			switch (col) {
				case 4:
					return true;
			}
			
			return false;
		}
	}

	/**
	 * Create the GUI and show it. For thread safety, this method should be
	 * invoked from the event-dispatching thread.
	 */
	private static void createAndShowGUI() {
		// Create and set up the window.
		JFrame frame = new JFrame("Employee Table Demo");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		// Create and set up the content pane.
		TableDemo newContentPane = new TableDemo();
		newContentPane.setOpaque(true); // content panes must be opaque
		frame.setContentPane(newContentPane);
		// Display the window.
		frame.pack();
		frame.setLocationRelativeTo(null);
		frame.setVisible(true);
	}

	public static void main(String[] args) {
		// Schedule a job for the event-dispatching thread:
		// creating and showing this application's GUI.
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				createAndShowGUI();
			}
		});
	}
}

This post has been edited by x68zeppelin80x: 06 June 2014 - 04:21 PM

Was This Post Helpful? 1
  • +
  • -

#4 incredibleX  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 212
  • Joined: 01-November 13

Re: JTable specific cell selected

Posted 07 June 2014 - 01:19 AM

Thankuu so much for your response and time. :)
Is there any way i can do all this with some mouse key listener?
because working with mouse every time you need to click which is far more time taking than just focusing some row with keys and it performs some calculations (sum all last column values) back hand.

Why focus listener and key listener don't trigger?

Thanks again.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1