Related
By running the example (neglected but functional to demonstrate my problem) you can see the steps in the console in the focustraversalpolicy
Test1: simply press TAB or ShiftTab
In console you see the steps in the getComponentAfter and getComponentBefore methods; in particular it is seen that, since the cells are not in edit, in the case of the second component, the JScrollPane component is returned. so it's ok
Test2: click on a JTable cell, write something (to enter edit) and press TAB
In console you see the passage in the getComponentAfter method; in particular it is seen that, having the focus the JTable, the JTable component is returned. so it's ok
Test3: click on a JTable cell, write something (to enter edit) and press ShiftTAB
Nothing happens at least in terms of focustraversalpolicy
If you press ShiftTab again
In console you see the passage in the getComponentBefore method; in particular we see that the JTextField component used for editing the cell is returned
Why shift TAB first time have no effect on on focustraversalpolicy policy?
Why TAB in focustraversalpolicy return a JTable component and Shift TAB return a JTextField component?
public class Prova2
{
public static final Double VideoDefaultFontIncrementWidth = 0.92;
public static final Double VideoDefaultFontIncrementHeight = 1.5;
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new Prova2();
}
});
}
public Prova2()
{
JFrame frame = new JFrame("Prova");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//
Object[] columnHeaders = {"Codice", "Nome", "Prezzo", "Data", "Noedit"};
Object rows[][] = {
{ "A", "About", 44.36, null, "aa" },
{ "B", "Boy", 44.84, null, "aa" },
{ "C", "Cat", 463.63, null, "aa" },
{ "D", "Day", 27.14, null, "aa" },
{ "E", "Eat", 44.57, null, "aa" },
{ "F", "Fail", 23.15, null, "aa" },
{ "G", "Good", 4.40, null, "aa" },
{ "H", "Hot", 24.96, null, "aa" },
{ "I", "Ivey", 5.45, null, "aa" },
{ "J", "Jack", 49.54, null, "aa" },
{ "K", "Kids", 280.00, null, "aa" },
{ "2A", "About", 44.36, null, "aa" },
{ "2B", "Boy", 44.84, null, "aa" },
{ "2C", "Cat", 463.63, null, "aa" },
{ "2D", "Day", 27.14, null, "aa"},
{ "2E", "Eat", 44.57, null, "aa" },
{ "2F", "Fail", 23.15, null, "aa" },
{ "2G", "Good", 4.40, null, "aa" },
{ "2H", "Hot", 24.96, null, "aa" },
{ "2I", "Ivey", 5.45, null, "aa" },
{ "2J", "Jack", 49.54, null, "aa" },
{ "2K", "Kids", 280.00, null, "aa" } };
//
// text 1
JTextField Text1 = new JTextField("");
Text1.setName("Text1");
frame.add(Text1, BorderLayout.NORTH);
//
// JTable soluzione 2
JTable myTable = new JTable(rows, columnHeaders);
myTable.setName("Table");
myTable.setFillsViewportHeight(true);
myTable.putClientProperty("autoStartsEdit", true);
myTable.putClientProperty("terminateEditOnFocusLost", true);
ActionMap myTableActionMap = myTable.getActionMap();
myTableActionMap.put("selectPreviousColumnCell", new myPreviousFocusHandler());
myTableActionMap.put("selectNextColumnCell", new myNextFocusHandler());
for (int i = 0; i < myTable.getColumnCount()-1; i++)
{
JTextField myTextField = new JTextField();
myTable.getColumn(columnHeaders[i]).setCellEditor(new DefaultCellEditor(myTextField));
}
JScrollPane pane = new JScrollPane(myTable);
frame.add(pane, BorderLayout.CENTER);
//
// text2
JTextField Text2 = new JTextField("");
Text2.setName("Text2");
frame.add(Text2, BorderLayout.SOUTH);
//
// frame
frame.setFocusTraversalPolicy(new MyFocusTraversalPolicy());
frame.setSize(800, 400);
frame.setVisible(true);
}
public static class MyFocusTraversalPolicy extends FocusTraversalPolicy
{
#Override
public Component getComponentAfter(Container arg0, Component arg1)
{
System.out.println("getComponentAfter1: "+arg1.toString());
JRootPane myRootPane=(JRootPane)arg0.getComponent(0);
JPanel myPanel = (JPanel) myRootPane.getLayeredPane().getComponent(0);
if (arg1 instanceof JPanel == true)
{
return getFirstComponent(arg0);
}
int myNewPosition = 0;
myNewPosition = myComponentPosition(myPanel, arg1);
myNewPosition = myComponentNext(myPanel, myNewPosition, 1);
if (myNewPosition > -1)
{
System.out.println("getComponentAfter2: "+myComponent(myPanel, myNewPosition));
return myComponent(myPanel, myNewPosition);
}
else
{
return getFirstComponent(arg0);
}
}
#Override
public Component getComponentBefore(Container arg0, Component arg1)
{
System.out.println("getComponentBefore1: "+arg1.toString());
JRootPane myRootPane=(JRootPane)arg0.getComponent(0);
JPanel myPanel = (JPanel) myRootPane.getLayeredPane().getComponent(0);
if (arg1 instanceof JPanel == true)
{
return getFirstComponent(arg0);
}
int myNewPosition = 0;
myNewPosition = myComponentPosition(myPanel, arg1);
myNewPosition = myComponentNext(myPanel, myNewPosition, -1);
if (myNewPosition > -1)
{
System.out.println("getComponentBefore2: "+myComponent(myPanel, myNewPosition));
return myComponent(myPanel, myNewPosition);
}
else
{
return getLastComponent(arg0);
}
}
#Override
public Component getDefaultComponent(Container arg0)
{
System.out.println("getDefaultComponent1: ");
JRootPane myRootPane=(JRootPane)arg0.getComponent(0);
JPanel myPanel = (JPanel) myRootPane.getLayeredPane().getComponent(0);
System.out.println("getDefaultComponent2: "+myPanel.getComponent(0));
return myPanel.getComponent(0);
}
#Override
public Component getFirstComponent(Container arg0)
{
System.out.println("getFirstComponent1: ");
JRootPane myRootPane=(JRootPane)arg0.getComponent(0);
JPanel myPanel = (JPanel) myRootPane.getLayeredPane().getComponent(0);
System.out.println("getFirstComponent2: "+myPanel.getComponent(0));
return myPanel.getComponent(0);
}
#Override
public Component getLastComponent(Container arg0)
{
System.out.println("getLastComponent1: ");
JRootPane myRootPane=(JRootPane)arg0.getComponent(0);
JPanel myPanel = (JPanel) myRootPane.getLayeredPane().getComponent(0);
System.out.println("getLastComponent2: "+myPanel.getComponent(myPanel.getComponentCount()-1));
return myPanel.getComponent(myPanel.getComponentCount()-1);
}
private int myComponentPosition(Container parm_Container, Component parm_Component)
{
for (int i = 0; i < parm_Container.getComponentCount(); i++)
{
if (parm_Container.getComponent(i) == parm_Component)
{
return i;
}
if (parm_Container.getComponent(i).getClass() == JScrollPane.class)
{
if (parm_Component.getClass() == JTable.class)
{
return i;
}
}
}
return -1;
}
private int myComponentNext(Container parm_Container, int parm_Position, int parm_Increment)
{
for (int i = parm_Position + parm_Increment; i > -1 && i < parm_Container.getComponentCount(); i = i + parm_Increment)
{
if (parm_Container.getComponent(i).isEnabled() && parm_Container.getComponent(i).isFocusable())
{
return i;
}
}
return -1;
}
private Component myComponent(Container parm_Container, int parm_Position)
{
return parm_Container.getComponent(parm_Position);
}
}
public class myPreviousFocusHandler extends AbstractAction
{
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent arg0)
{
KeyboardFocusManager myManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
myManager.focusPreviousComponent();
}
}
public class myNextFocusHandler extends AbstractAction
{
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent arg0)
{
KeyboardFocusManager myManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
myManager.focusNextComponent();
}
}
}
I am trying to listen to two linked tables using one TableModelListener each. My first table changes the content of the second table while the second table changes the content of a text box. However, after changing the table content of the second table the TableModelListener of the second table stops registering the event.
I cannot get this code to work. Could anyone please point me into the right direction?
package tablelistenertest;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.Dimension;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
public class TableListenerTest extends JPanel {
private javax.swing.JTable table1;
private javax.swing.JTable table2;
private javax.swing.JTextField text1;
public TableListenerTest() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
table1 = new javax.swing.JTable();
table1.setPreferredScrollableViewportSize(new Dimension(500, 70));
table1.setFillsViewportHeight(true);
add(new JScrollPane(table1));
table2 = new javax.swing.JTable();
table2.setPreferredScrollableViewportSize(new Dimension(500, 70));
table2.setFillsViewportHeight(true);
add(new JScrollPane(table2));
text1 = new javax.swing.JTextField("", 40);
text1.setEditable(false);
add(new JScrollPane(text1));
String[] columnNames = {
"Column 1",
"Column 2",
"Column 3"
};
Object[][] data = {
{new Boolean(true), "1", "a" },
{new Boolean(false), "2", "b"},
};
Object[][] data2 = {
{new Boolean(false), "3", "c"},
{new Boolean(false), "4", "d"}
};
table1.setModel( new MyTableModel( columnNames, data ) );
table2.setModel( new MyTableModel( columnNames, data2 ) );
text1.setText("test");
table1.getModel().addTableModelListener( new TableModelListener() {
#Override
public void tableChanged(TableModelEvent evt) {
if( evt.getColumn() == 0 && evt.getFirstRow() > -1 ){
if( (Boolean) table1.getValueAt(0, 0) && !(Boolean) table1.getValueAt(1, 0) ){
Object[][] data2 = {
{new Boolean(true), "5", "e" },
{new Boolean(false), "6", "f"}
};
table2.setModel( new MyTableModel( columnNames, data2 ) );
}
else if( !(Boolean) table1.getValueAt(0, 0) && (Boolean) table1.getValueAt(1, 0) ){
Object[][] data2 = {
{new Boolean(true), "7", "g" },
{new Boolean(false), "8", "h"}
};
table2.setModel( new MyTableModel( columnNames, data2 ) );
}
else if( (Boolean) table1.getValueAt(0, 0) && (Boolean) table1.getValueAt(1, 0) ){
Object[][] data2 = {
{new Boolean(true), "9", "i" },
{new Boolean(false), "10", "j"}
};
table2.setModel( new MyTableModel( columnNames, data2 ) );
}
else{
Object[][] data2 = {
{new Boolean(true), "11", "k" },
{new Boolean(false), "12", "l"}
};
table2.setModel( new MyTableModel( columnNames, data2 ) );
}
}
}
} );
table2.getModel().addTableModelListener( new TableModelListener() {
#Override
public void tableChanged(TableModelEvent evt) {
if( evt.getColumn() == 0 && evt.getFirstRow() > -1 ){
if( (Boolean) table2.getValueAt(0, 0) && !(Boolean) table2.getValueAt(1, 0) ){
text1.setText("test1");
}
else if( !(Boolean) table2.getValueAt(0, 0) && (Boolean) table2.getValueAt(1, 0) ){
text1.setText("test2");
}
else if( (Boolean) table2.getValueAt(0, 0) && (Boolean) table2.getValueAt(1, 0) ){
text1.setText("test3");
}
else{
text1.setText("test4");
}
}
}
} );
}
class MyTableModel extends AbstractTableModel {
private String[] columnNames;
private Object[][] data;
public MyTableModel(String[] columnNames, Object[][] data) {
this.columnNames = columnNames;
this.data = data;
}
#Override
public int getColumnCount() {
return columnNames.length;
}
#Override
public int getRowCount() {
return data.length;
}
#Override
public String getColumnName(int col) {
return columnNames[col];
}
#Override
public Object getValueAt(int row, int col) {
return data[row][col];
}
#Override
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
#Override
public boolean isCellEditable(int row, int col) {
return col == 0;
}
#Override
public void setValueAt(Object value, int row, int col) {
data[row][col] = value;
fireTableCellUpdated(row, col);
}
}
private static void createAndShowGUI() {
UIManager.put("swing.boldMetal", Boolean.FALSE);
JFrame frame = new JFrame("TableListenerTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TableListenerTest newContentPane = new TableListenerTest();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
I made simple project in Java using swing. Below is code, I would like to get selected value from combobox placed in table, how I can do this? Good to be if thats data were placed in array. Thx for all answers.
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.swing.JFormattedTextField;
public class SWD_GUI implements ActionListener {
JButton button;
public JFrame frame;
private JTable table;
private JTable table_1;
private JTable table_2;
private JTable table_3;
private JFormattedTextField formattedTextField;
JComboBox<ComboItem> comboBox;
TableColumn column_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SWD_GUI window = new SWD_GUI();
window.frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public SWD_GUI() {
initialize();
}
public void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 846, 546);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.pack();
frame.getContentPane().setLayout(null);
JLabel lblSwdTelephone = new JLabel("SWD TELEPHONE");
lblSwdTelephone.setHorizontalAlignment(SwingConstants.CENTER);
lblSwdTelephone.setFont(new Font("Tahoma", Font.BOLD, 16));
lblSwdTelephone.setBounds(10, 11, 810, 20);
frame.getContentPane().add(lblSwdTelephone);
button = new JButton("DO IT!");
button.setBounds(379, 432, 89, 23);
frame.getContentPane().add(button);
button.addActionListener(this);
createTables();
}
private void createTables() {
createFirstTable();
createSecondTable();
createThirdTable();
createFourthTable();
}
private void createFourthTable() {
TableModel tableModel_3 = new DefaultTableModel(new Object[][] {
{ "BATTERY", "Samsung", "HTC", "LG" },
{ "Samsung", new Double(1.0), null, null },
{ "HTC", null, new Double(1.0), null },
{ "LG", null, null, new Double(1.0) }, }, new String[] {
"New column", "Price", "Specification", "Baterry" }) {
private static final long serialVersionUID = 1L;
boolean[] columnEditables = new boolean[] { false, true, true, true };
boolean[] rowEditables = new boolean[] { false, true, true, true };
public boolean isCellEditable(int row, int column) {
return columnEditables[column] && rowEditables[row];
}
};
createTable(table_3, tableModel_3, 304);
}
private void createThirdTable() {
TableModel tableModel_2 = new DefaultTableModel(new Object[][] {
{ "SPECIFICATION", "Samsung", "HTC", "LG" },
{ "Samsung", new Double(1.0), null, null },
{ "HTC", null, new Double(1.0), null },
{ "LG", null, null, new Double(1.0) }, }, new String[] {
"New column", "Price", "Specification", "Baterry" }) {
private static final long serialVersionUID = 1L;
boolean[] columnEditables = new boolean[] { false, true, true, true };
boolean[] rowEditables = new boolean[] { false, true, true, true };
public boolean isCellEditable(int row, int column) {
return columnEditables[column] && rowEditables[row];
}
};
createTable(table_2, tableModel_2, 214);
}
private void createSecondTable() {
TableModel tableModel_1 = new DefaultTableModel(new Object[][] {
{ "PRICE", "Samsung", "HTC", "LG" },
{ "Samsung", new Double(1.0), null, null },
{ "HTC", null, new Double(1.0), null },
{ "LG", null, null, new Double(1.0) }, }, new String[] {
"New column", "Price", "Specification", "Baterry" }) {
private static final long serialVersionUID = 1L;
boolean[] columnEditables = new boolean[] { false, true, true, true };
boolean[] rowEditables = new boolean[] { false, true, true, true };
public boolean isCellEditable(int row, int column) {
return columnEditables[column] && rowEditables[row];
}
};
createTable(table_1, tableModel_1, 124);
}
private void createFirstTable() {
TableModel tableModel = new DefaultTableModel(new Object[][] {
{ null, "Price", "Specification", "Baterry" },
{ "Price", new Double(1.0), null, null },
{ "Specification", null, new Double(1.0), null },
{ "Baterry", null, null, new Double(1.0) }, }, new String[] {
"New column", "Price", "Specification", "Baterry" }) {
private static final long serialVersionUID = 1L;
boolean[] columnEditables = new boolean[] { false, true, true, true };
boolean[] rowEditables = new boolean[] { false, true, true, true };
public boolean isCellEditable(int row, int column) {
return columnEditables[column] && rowEditables[row];
}
};
createTable(table, tableModel, 39);
}
private void createTable(JTable table, TableModel tableModel, int y) {
table = new JTable();
table.setColumnSelectionAllowed(true);
table.setCellSelectionEnabled(true);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setFillsViewportHeight(true);
table.setBounds(10, y, 424, 64);
frame.getContentPane().add(table);
table.setModel(tableModel);
addColumn(table, 1);
addColumn(table, 2);
addColumn(table, 3);
}
class ComboItem
{
public String key;
public String value;
public ComboItem(String key, String value)
{
this.key = key;
this.value = value;
}
//#Override
public String toString()
{
return key;
}
public String getKey()
{
return key;
}
public String getValue()
{
return value;
}
}
public void addColumn(JTable table, int columnIndex) {
{
TableColumn column_1 = table.getColumnModel()
.getColumn(columnIndex);
JComboBox<Object> comboBox = new JComboBox<Object>();
comboBox.addItem(new ComboItem("1", "1.0"));
comboBox.addItem(new ComboItem("3", "3.0"));
comboBox.addItem(new ComboItem("5", "5.0"));
comboBox.addItem(new ComboItem("7", "7.0"));
comboBox.addItem(new ComboItem("1/3", "0.333333333"));
comboBox.addItem(new ComboItem("1/5", "0.2"));
comboBox.addItem(new ComboItem("1/7", "0,1428571428571429"));
//comboBox.addItem((double) 1);
//comboBox.addItem((double) 3);
//comboBox.addItem((double) 5);
//comboBox.addItem((double) 7);
//comboBox.addItem((double) 9);
//comboBox.addItem((double) (1.0/3.0));
//comboBox.addItem((double) (1.0/5.0));
//comboBox.addItem((double) (1.0/7.0));
//comboBox.addItem((double) (1.0/9.0));
column_1.setCellEditor(new DefaultCellEditor(comboBox));
Object item = comboBox.getSelectedItem();
String value = ((ComboItem)item).getValue();
System.out.println(value);
}
formattedTextField = new JFormattedTextField();
formattedTextField.setBounds(462, 36, 358, 333);
frame.getContentPane().add(formattedTextField);
}
//public void getContents() {
// TODO Auto-generated method stub
//}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stud
Object source = e.getSource();
if (source == button) {
}
//for(int i = 0; i<7; i++){
//System.out.println(anArrays[i]);
//}
// getContents();
//int row = table.getSelectedRow();
//String idS = table.getValueAt(row, 0).toString();
//String al = column_1.getMaxWidth().toString();
//System.out.println(al);
// System.out.println(item);
// formattedTextField.add(table);
//formattedTextField.setValue(table);
}
}
You get the data from the table, not the combo box.
ComboItem item = (ComboItem)table.getValueAt(...);
System.out.println( item.getValue() );
I have an object A that instance another object B.
I was wondering whether or not is possible to modify A with instructions in B.
In my circumstance, I have a Timetable (its code is under "Object A") that open (by InsertLesson.setVisible(true);) a Window to let the user compile its cells with lesson. At this time, the Window (InsertLesson, code under "object B") get the lesson selection by user but it is not able to write in the table that selection. How can I do?
Here the code
Object A:
public class TablePanel extends JPanel
{
private JTable table;
public Tabella()
{
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
table = new JTable(new MyTableModel());
table.setFillsViewportHeight(true);
table.setPreferredScrollableViewportSize(new Dimension(500, 100));
JScrollPane jps = new JScrollPane(table);
add(jps);
add(new JScrollPane(table));
table.setCellSelectionEnabled(true);
table.addMouseListener(
new MouseAdapter(){
public void mouseClicked(MouseEvent e) {
int row = table.rowAtPoint(new Point(e.getX(), e.getY()));
int col = table.columnAtPoint(new Point(e.getX(), e.getY()));
if (col>0) {
if (e.getClickCount() > 1) {
if (row == 5 | row == 6)
{
JOptionPane.showMessageDialog(null, "Impossible to set lesson.");
return;
}
else {
table.getColumnName(col);
String day = table.getColumnName(col);
String hour = (String) table.getValueAt(row, 0);
InsertLesson cell = new InsertLesson(day, hour);
cel.setVisible(true);
}
}
}
}
}
);
}
private class MyTableModel extends AbstractTableModel {
private String[] columns = {"","Monday","Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
private String[][] data = {{"8:30 - 9:30","","","","","",""},
{"9:30 - 10:30","","","","","",""},
{"10:30 - 11:30","","","","","",""},
{"11:30 - 12:30","","","","","",""},
{"12:30 - 13:30","","","","","",""},
{"13:30 - 14:30","","","","","",""},
{"14:30 - 15:30","","","","","",""},
{"15:30 - 16:30","","","","","",""},
{"16:30 - 17:30","","","","","",""}};
public int getColumnCount() {
return columns.length;
}
public int getRowCount() {
return data.length;
}
public String getColumnName(int col) {
return columns[col];
}
public Object getValueAt(int row, int col) {
return data[row][col];
}
}
Object B (which has to modify A):
public InsertLesson (String day, String hour)
{
initialize(day, hour);
}
private void initialize(String day, String hour) {
this.setSize(600,200);
this.setTitle("Insert Lesson");
this.setLocationRelativeTo(null);
String[] lessons = {"math", "english", "art"};
String [] classrooms = {"class1", "class2"};
JPanel centralPnl = new JPanel();
this.getContentPane().add(centralPnl, BorderLayout.CENTER);
final JComboBox classBox = new JComboBox(classrooms );
centralPnl.add(classBox);
final JComboBox lessonsBox = new JComboBox(lessons);
centralPnl.add(lessonsBox);
JPanel southPnl = new JPanel();
this.getContentPane().add(southPnl, BorderLayout.SOUTH);
JButton insLessonBtn = new JButton("Insert Lesson");
southPnl.add(insLessonBtn);
lessonsBox.addItemListener(new ItemListener()
{
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED)
{
selectedLesson = lessonsBox.getSelectedItem().toString();
}
}
});
classBox.addItemListener(new ItemListener(){
#Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED)
{
selectedClass = classBox.getSelectedItem().toString();
}
}
});
class MouseSpy implements MouseListener
{
public void mouseClicked(MouseEvent e)
{
JOptionPane.showMessageDialog(null,"Do something for modify table with\n"
+ "values of selectedLesson and selectedClass");
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
}
MouseListener listener = new MouseSpy();
insLessonBtn.addMouseListener(listener);
}
}
}
To update the table in A, B must invoke the method setValueAt() on the TableModel of A. Alternatively, add a method to your TableModel that does the update. A typical implementation of setValueAt() is seen here. If that doesn't help, please edit your question to include an sscce that exhibits the problem you encounter.
Addendum: I want to update the table … after the user press the … button.
As a concrete example using your TableModel, the Update button below updates the table's model with each press. Compare the implmentation of setValueAt () to the one cited above. The button's actionPerformed() method accesses a final reference to the TableModel in the enclosing scope, but you can pass a reference to your TableModel as a parameter to the constructor of InsertLesson.
Addendum: Would you write [it for] me?
No, but I will outline the approach, assuming a class InsertLesson,
TableModel model = new MyTableModel();
JTable table = new JTable(model);
InsertLesson cell = new InsertLesson(day, hour, model);
…
class InsertLesson {
TableModel model;
public InsertLesson(String day, String hour, TableModel model) {
this.model = model;
…
}
…
}
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
/**
* #see http://stackoverflow.com/a/18764073/230513
*/
public class Test {
private static class MyTableModel extends AbstractTableModel {
private String[] columns = {
"Time", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
private String[][] data = {
{"8:30 - 9:30", "", "", "", "", ""},
{"9:30 - 10:30", "", "", "", "", ""},
{"10:30 - 11:30", "", "", "", "", ""},
{"11:30 - 12:30", "", "", "", "", ""},
{"12:30 - 13:30", "", "", "", "", ""},
{"13:30 - 14:30", "", "", "", "", ""},
{"14:30 - 15:30", "", "", "", "", ""},
{"15:30 - 16:30", "", "", "", "", ""},
{"16:30 - 17:30", "", "", "", "", ""}};
#Override
public int getColumnCount() {
return columns.length;
}
#Override
public int getRowCount() {
return data.length;
}
#Override
public String getColumnName(int col) {
return columns[col];
}
#Override
public Object getValueAt(int row, int col) {
return data[row][col];
}
#Override
public void setValueAt(Object aValue, int row, int col) {
data[row][col] = (String) aValue;
fireTableCellUpdated(row, col);
}
}
private void display() {
JFrame f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final TableModel model = new MyTableModel();
f.add(new JScrollPane(new JTable(model) {
#Override
public Dimension getPreferredScrollableViewportSize() {
return new Dimension(600, 128);
}
}));
f.add(new JButton(new AbstractAction("Update") {
#Override
public void actionPerformed(ActionEvent e) {
model.setValueAt(String.valueOf(e.getWhen() % 1000000), 1, 1);
}
}), BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new Test().display();
}
});
}
}
I'm working on a code in Java Swing. I have created a JComboBox in JTable. It's working :). But once I select a value and click on the save or cancel button, it has to reset to the default value (1st value in the combo box). I tried a lot of ways like combobox.setSelectedIndex(0). This isn't working.
Code:
String[] manTimeHr = { "00","01", "02", "03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23"};
String[] manTimeMin = {"00","01", "02", "03","04","05","06","07","08","09","10","11","12","13", "14", "15","16","17","18","19","20","21","22","23","24","25", "26", "27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","51","52","53","54","55","56","57","58","59"};
String[][] data = {{"-select-","-select-"}};
String[] cols = {"Hrs","Mins"};
String[][] data1 = {{"-select-","-select-"}};
String[] cols1 = {"Hrs","Mins"};
JLabel manTimeStart = new JLabel("Start From",JLabel.LEFT);
STimeTbl = new JTable(data,cols);
hrsColumn=STimeTbl.getColumnModel().getColumn(0);
minsColumn=STimeTbl.getColumnModel().getColumn(1);
manSiteStimeHrCBx = new JComboBox(manTimeHr);
manSiteStimeHrCBx.setSelectedIndex(0);
hrsColumn.setCellEditor(new DefaultCellEditor(manSiteStimeHrCBx));
manSiteStimeMinCBx = new JComboBox(manTimeMin);
manSiteStimeMinCBx.setSelectedIndex(0);
minsColumn.setCellEditor(new DefaultCellEditor(manSiteStimeMinCBx));
JLabel manTimeEnd = new JLabel("End To",JLabel.LEFT);
ETimeTbl = new JTable(data1,cols1);
hrsColumn1=ETimeTbl.getColumnModel().getColumn(0);
minsColumn1=ETimeTbl.getColumnModel().getColumn(1);
manSiteEtimeHrCBx = new JComboBox(manTimeHr);
manSiteEtimeHrCBx.setSelectedIndex(0);
hrsColumn1.setCellEditor(new DefaultCellEditor(manSiteEtimeHrCBx));
manSiteEtimeMinCBx = new JComboBox(manTimeMin);
manSiteEtimeMinCBx.setSelectedIndex(0);
minsColumn1.setCellEditor(new DefaultCellEditor(manSiteEtimeMinCBx));
.
.
.
.
if("Save".equals(e.getActionCommand())) {
try{
mSHr = Integer.parseInt((String)manSiteStimeHrCBx.getSelectedItem());
mEHr=Integer.parseInt((String)manSiteEtimeHrCBx.getSelectedItem());
mSMin=Integer.parseInt((String)manSiteStimeMinCBx.getSelectedItem());
mEMin=Integer.parseInt((String)manServEtimeMinCBx.getSelectedItem());
}catch (Exception en){
System.out.println("Main Exception : "+ en);
return;
}
if(validateBlockTime(mSHr,mEHr,mSMin,mEMin) != true)
{
System.out.println("Enter valid Time");
return;
}
manSiteStimeHrCBx.setSelectedIndex(0);
manSiteStimeMinCBx.setSelectedIndex(0);
manSiteEtimeHrCBx.setSelectedIndex(0);
manSiteEtimeMinCBx.setSelectedIndex(0);
.
.
.
private static boolean validateBlockTime(int val3, int val4, int val5, int val6){
if(val4 > val3)
return true;
else if((val4 == val3) && (val6 > val5))
return true;
else
return false;
}
JTable tutorial contains description about Combo Box as an Editor
all data are stored in the XxxTableModel
all changes in the JTable view are described in Concepts: Editors and Renderers
then you have to know that in the XxxTableModel is stored only String value (or Double or Long or Integer or Icon, depends of value stored in ComboBoxModel) for Combo Box as an Editor
result is
quick code (sorry I'm so lazy) based on tutorial code
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class TableRenderDemo extends JPanel {
private static final long serialVersionUID = 1L;
private boolean DEBUG = false;
public TableRenderDemo() {
super(new BorderLayout(5, 5));
final JTable table = new JTable(new MyTableModel());
table.setRowHeight(18);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
initColumnSizes(table);
setUpSportColumn(table, table.getColumnModel().getColumn(2));
add(scrollPane);
JButton resetButton = new JButton("Reset to default");
resetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < table.getRowCount(); i++) {
table.getModel().setValueAt("None of the above", i, 2);
}
}
});
add(resetButton, BorderLayout.SOUTH);
}
private void initColumnSizes(JTable table) {
MyTableModel model = (MyTableModel) table.getModel();
TableColumn column = null;
Component comp = null;
int headerWidth = 0;
int cellWidth = 0;
Object[] longValues = model.longValues;
TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();
for (int i = 0; i < 5; i++) {
column = table.getColumnModel().getColumn(i);
comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
headerWidth = comp.getPreferredSize().width;
comp = table.getDefaultRenderer(model.getColumnClass(i)).getTableCellRendererComponent(table, longValues[i], false, false, 0, i);
cellWidth = comp.getPreferredSize().width;
if (DEBUG) {
System.out.println("Initializing width of column " + i + ". " + "headerWidth = " + headerWidth + "; cellWidth = " + cellWidth);
}
column.setPreferredWidth(Math.max(headerWidth, cellWidth));
}
}
private void setUpSportColumn(JTable table, TableColumn sportColumn) {
JComboBox comboBox = new JComboBox();
comboBox.addItem("Snowboarding");
comboBox.addItem("Rowing");
comboBox.addItem("Knitting");
comboBox.addItem("Speed reading");
comboBox.addItem("Pool");
comboBox.addItem("None of the above");
sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
sportColumn.setCellRenderer(renderer);
}
private class MyTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private String[] columnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
private Object[][] data = {
{"Kathy", "Smith", "Snowboarding", new Integer(5), false},
{"John", "Doe", "Rowing", new Integer(3), true},
{"Sue", "Black", "Knitting", new Integer(2), false},
{"Jane", "White", "Speed reading", new Integer(20), true},
{"Joe", "Brown", "Pool", new Integer(10), false}
};
public final Object[] longValues = {"Jane", "Kathy", "None of the above", new Integer(20), Boolean.TRUE};
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return data.length;
}
#Override
public String getColumnName(int col) {
return columnNames[col];
}
public Object getValueAt(int row, int col) {
return data[row][col];
}
#Override
public Class<?> getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
#Override
public boolean isCellEditable(int row, int col) {
if (col < 2) {
return false;
} else {
return true;
}
}
#Override
public void setValueAt(Object value, int row, int col) {
data[row][col] = value;
fireTableCellUpdated(row, col);
System.out.println(getValueAt(row, col));
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("TableRenderDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TableRenderDemo newContentPane = new TableRenderDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
output from AbstractTableModel, code line 135th.
run:
None of the above
None of the above
None of the above
None of the above
None of the above
BUILD SUCCESSFUL (total time: 37 seconds)