JTable ComboBox loses value when clicked elsewhere - java

I have set a jCombobox as DefaultCellEditor for a JTable cell.
The problem comes when I type a value in the cell (jCombobox) and whenever I click somewhere else, the value is lost. Someone knows why and how can I fix this?
table.getColumnModel().getColumn(1).setCellEditor(new SpringJobTablePopupCellEditor());
public class SpringJobTablePopupCellEditor extends AbstractCellEditor implements TableCellEditor {
JTextField jtf;
DefaultCellEditor other;
DefaultCellEditor checkbox;
private DefaultCellEditor lastSelected;
JComboBox cbox = null;
public SpringJobTablePopupCellEditor() {
jtf = new JTextField();
jtf.setDocument(new JTextFieldLimit(1000));
other = new DefaultCellEditor(jtf);
checkbox = new DefaultCellEditor(generateBox("10"));
}
#Override
public Object getCellEditorValue() {
return lastSelected.getCellEditorValue();
}
#Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
final JTable t = table;
cbox.getEditor().getEditorComponent().addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public void focusLost(FocusEvent e) {
if(t.isEditing()){
t.getCellEditor().stopCellEditing();
}
}
});
String val = table.getModel().getValueAt(row, column - 1).toString();
if("ak".equals(val)){
lastSelected = checkbox;
return checkbox.getTableCellEditorComponent(table, value, isSelected, row, column);
}
lastSelected = other;
return other.getTableCellEditorComponent(table, value, isSelected, row, column);
}
private JComboBox generateBox(String type) {
cbox = new JComboBox();
cbox.setEditable(true);
for (Map.Entry<String, String> entry : SpringJob.akMap.entrySet()) {
cbox.addItem(entry.getValue());
}
return cbox;
}
}

try
JTable table = new yourTable();
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
When you go from one combobox to another you need to force your table to stop editing
i achieved similar with adding a focusListener to the combobox and in the focuslost adding
public void focusLost(FocusEvent e) {
if (table.isEditing())
table.getCellEditor().stopCellEditing();
}
}

Combo box has stored more than one items list normally. when you click JCombo box in jtable and type the value it will not add directly in to combobox list item. you must add value first in combo-box. Combo-box contains array of objects.
Try this code its dynamically add value in Jtable combo-box
static JComboBox combo = new JComboBox();
static JTable table = new JTable();
public static void main(String[] args)
{
JFrame frame = new JFrame();
JPanel topPanel = new JPanel();
JPanel middlepanel = new JPanel();
combo.addItem("First");
combo.addItem("Second");
combo.addItem("Third");
JButton button = new JButton("Add Item");
topPanel.add(button);
frame.setLayout(new BorderLayout());
frame.setSize(500, 500);
frame.add(topPanel, BorderLayout.NORTH);
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addColumn("A", new Object[] { "item1" });
middlepanel.setLayout(new BorderLayout());
middlepanel.add(table,BorderLayout.CENTER);
String str[] = new String[combo.getItemCount()];
for(int i=0;i<combo.getItemCount();i++){
str[i] = combo.getItemAt(i).toString();
}
table.getColumnModel().getColumn(0).setCellEditor(new MyComboBoxEditor(combo));
table.getColumnModel().getColumn(0).setCellRenderer(new MyComboBoxRenderer(str));
table.setRowHeight(25);
frame.add(middlepanel,BorderLayout.CENTER);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
switch(cmd)
{
case "Add Item":
combo.addItem("Fourth");
combo.addItem("Fifth");
String str[] = new String[combo.getItemCount()];
for(int i=0;i<combo.getItemCount();i++){
str[i] = combo.getItemAt(i).toString();
}
table.getColumnModel().getColumn(0).setCellEditor(new MyComboBoxEditor(combo));
table.getColumnModel().getColumn(0).setCellRenderer(new MyComboBoxRenderer(str));
break;
}
}
});
}
#Override
public void actionPerformed(ActionEvent e)
{
}

Related

How can I add two jTextFields to JTable cell on button click

I have a JTable, edit button and save button. when I click the edit button , I want to insert two JTextFields into a particular cell which is selected . So I can write (strings) into these text fields .
when I click on save button want to remove those two textfields from the cell and paste that strings (into the same cell of the table).
You don't need to add a JTextField to a JTable in order for a cell to be editable. The isCellEditable(int row, int column) function can be overridden to return a boolean dependent on the edit button. Here's an example:
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.EventQueue;
import java.awt.event.*;
import java.awt.Dimension;
public class EditTableExample extends JFrame {
private boolean editable = false;
public EditTableExample() {
//set up jframe
setPreferredSize(new Dimension(500, 500));
setMinimumSize(new Dimension(500, 500));
setResizable(false);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
//set up content pane
JPanel contentPane = new JPanel();
setContentPane(contentPane);
//table model
Object[][] tableContents = new Object[][]{ //contents of our table
{"Person1", "City1"},
{"Person2", "City2"},
{"Person3", "City3"}
};
Object[] tableHeader = new Object[]{
"Name", "City"
};
DefaultTableModel model = new DefaultTableModel(tableContents, tableHeader) {
#Override
public boolean isCellEditable(int row, int column) {
return editable;
}
};
//table
JTable table = new JTable(model);
//scrollpane to house table
JScrollPane tablePane = new JScrollPane(table);
tablePane.setPreferredSize(new Dimension(450, 450));
//button that will add a row
JButton add = new JButton("Add Row");
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
model.addRow(new Object[model.getColumnCount()]); //adds a new, empty row to the table
}
});
//button that will toggle edit mode
JButton edit = new JButton("Toggle Edit");
edit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
editable = !editable; //switches the value of 'editable' on click
}
});
//button to remove a row
JButton remove = new JButton("Remove Row");
remove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
try {
model.removeRow(table.getSelectedRow()); //remove selected row
}
catch (ArrayIndexOutOfBoundsException e) {
JOptionPane.showMessageDialog(rootPane, "No Row Selected");
}
}
});
//add everything together
contentPane.add(tablePane);
contentPane.add(add);
contentPane.add(edit);
contentPane.add(remove);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
EditTableExample e = new EditTableExample();
e.setVisible(true);
}
});
}
}
As you can see, the isCellEditable function will return the value of 'editable', a boolean whose value is toggled by the 'edit' button. Instead of having one cell per person that contains "Name, City" there are two columns, one for the person's name and one for their city. Let me know if you have any other questions.

refresh button doesn't refresh jtable

public class WeatherFrame extends JFrame {
private JPanel contentPane;
private JTable table;
HealthData health = new HealthData();
private DefaultTableModel model;
String[] columnNames = {"zipcode", "county", "city", "state", "year", "month","ageGroup",
"numOfVisits", "MonthlyMax", "MonthlyMin", "MonthlyNor"};
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
WeatherFrame frame = new WeatherFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public WeatherFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 300);
contentPane = new JPanel();
contentPane.setBounds(100, 100,750, 200);
setContentPane(contentPane);
contentPane.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(6, 25, 788, 180);
contentPane.add(scrollPane);
populateTable();
table = new JTable(model);
scrollPane.setViewportView(table);
JButton btnInsert = new JButton("insert");
btnInsert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
InsertFrame frame = new InsertFrame();
frame.setVisible(true);
}
});
btnInsert.setBounds(279, 217, 117, 29);
contentPane.add(btnInsert);
JButton btnDelete = new JButton("delete");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DeleteFrame delete = new DeleteFrame();
delete.setVisible(true);
}
});
btnDelete.setBounds(412, 217, 117, 29);
contentPane.add(btnDelete);
JButton btnSearch = new JButton("search");
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
SelectFrame search = new SelectFrame();
search.setVisible(true);
}
});
btnSearch.setBounds(530, 217, 117, 29);
contentPane.add(btnSearch);
JLabel lblWeatherTable = new JLabel("Weather Table");
lblWeatherTable.setBounds(149, 6, 107, 16);
contentPane.add(lblWeatherTable);
JButton btnNext = new JButton("update");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
UpdateFrame update = new UpdateFrame();
update.setVisible(true);
}
});
btnNext.setBounds(150, 217, 117, 29);
contentPane.add(btnNext);
JButton btnRefresh = new JButton("refresh");
btnRefresh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
populateTable();
}
});
btnRefresh.setBounds(29, 217, 117, 29);
contentPane.add(btnRefresh);
JButton btnAnalyze = new JButton("Analyze");
btnAnalyze.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ShowAnalyze analyze = new ShowAnalyze(health.analyze());
analyze.setVisible(true);
}
});
btnAnalyze.setBounds(662, 217, 117, 29);
contentPane.add(btnAnalyze);
}
#SuppressWarnings("serial")
public void populateTable() {
model = new DefaultTableModel(){
#Override
public boolean isCellEditable(int row, int column) {
//all cells false
return false;
}
};
for(String name: columnNames)
model.addColumn(name);
ArrayList<Health> temp = new ArrayList<Health>();
temp = health.showAllData();
for(int i = 0; i< temp.size(); i++) {
Object[] data = {temp.get(i).getZipCode(), temp.get(i).getCounty(), temp.get(i).getCounty(), temp.get(i).getState(),temp.get(i).getYear(),
temp.get(i).getMonth(), temp.get(i).getAgeGroup(), temp.get(i).getNumOfVisits(), temp.get(i).getMMax(), temp.get(i).getMMin(), temp.get(i).getMNor()};
model.addRow(data);
}
table.setModel(model);
}
}
I'm trying to refresh the jtable using a refresh button, when I click the button it seems like it is loading, but after that nothing changes on the table. How can I fix this problem? In the action performed method of the refresh button, I called populateTable which is a function to load data into table.
In the populateTable method, you change the table model but you do not pass that new model to the JTable.
Option 1: replace the table model
In the constructor, you call:
table = new JTable(model);
populateTable();
In the populateTable, I would expect something like:
table.setModel(model);
Option 2: update the table model
As mKorbel already suggested, you can also update your table model instead of throwing the existing model away and creating a new one. Your populateTable method could look like this (using Java 8 and with a new initializeModel method to create the table model initially):
public void populateTable() {
boolean firstTime = (model == null);
if (firstTime) {
initializeModel();
} else {
model.getDataVector().clear();
}
for (Health item : health.showAllData()) {
model.addRow(new Vector<>(Arrays.asList(
item.getZipCode(), item.getCounty(), item.getState(), item.getYear(),
item.getMonth(), item.getAgeGroup(), item.getNumOfVisits(),
item.getMMax(), item.getMMin(), item.getMNor()
)));
}
if (firstTime && table != null) {
table.setModel(model);
}
}
private void initializeModel() {
model = new DefaultTableModel() {
#Override
public boolean isCellEditable(int row, int column) {
//all cells false
return false;
}
};
for (String name : columnNames)
model.addColumn(name);
}
JTable and its DefaultTableModel (desclared as private JTable table; and private DefaultTableModel model;) doesn't know something that a new model = new DefaultTableModel(){ is (re)created in public void populateTable() {,
you have to
add a new DefaultTableModel to JTables instance that is already visible in your Swing GUI
(better option is) add a new data directly to private DefaultTableModel model;, this model is designated for
rest is very well described in comment by # Andrew Thompson

Java Eclipse Jtable Cell / Column

for Java Kepler Eclipse and Jtable, I am trying to make it so as when a specific table cell is selected, that cell will work as an editorPane; or have the whole column work as editorPane. When I click a cell on column COMMENTS it enlargens the row but I cant get it to work as an editorPane. My project is actualy very different but I wrote this mini one with the table so you can copy, paste and run it to see exactly what the problem is when you click on a COMMENTS cell.
I tried to make the column an editorPane to begin with like I made the column DONE with checkBox, but it doesnt work or I am doing it wrong. I also tried cellRenderer but I couldnt make that work either.
Whether the whole column works as an editorPane or just the selected cell it doesnt matter, whatever is easier and as long as it works
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
public class JavaTestOne {
JFrame frmApp;
private JTable table;
private JCheckBox checkbox;
DefaultTableModel model;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
JavaTestOne window = new JavaTestOne();
window.frmApp.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public JavaTestOne() {
initialize();
}
private void initialize() {
frmApp = new JFrame();
frmApp.getContentPane().setFont(new Font("Tahoma", Font.PLAIN, 13));
frmApp.setBounds(50, 10, 1050, 650);
frmApp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmApp.getContentPane().setLayout(new CardLayout(0, 0));
frmApp.setTitle("App");
{
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(0, 42, 984, 484);
frmApp.add(scrollPane);
{
table = new JTable();
table.setFillsViewportHeight(true);
Object[][] data = {
{"I01", "Tom",new Boolean(false), ""},
{"I02", "Jerry",new Boolean(false), ""},
{"I03", "Ann",new Boolean(false), ""}};
String[] cols = {"ID","NAME","DONE","COMMENTS"};
model = new DefaultTableModel(data, cols) {
private static final long serialVersionUID = -7158928637468625935L;
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
table.setModel(model);
table.setRowHeight(20);
table.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
int row = table.rowAtPoint(evt.getPoint());
int col = table.columnAtPoint(evt.getPoint());
table.setRowHeight(20);
if(col==3){
table.setRowHeight(row, 100);
//this is where I need it to work as an editorPane if it is only for the selected cell
}
}
});
table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
scrollPane.setViewportView(table);
checkbox = new JCheckBox("OK");
checkbox.setHorizontalAlignment(SwingConstants.CENTER);
checkbox.setBounds(360, 63, 97, 23);
}
}
}
}
Another alternative is to display a popup window to edit the cell:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
/*
* The editor button that brings up the dialog.
*/
//public class TablePopupEditor extends AbstractCellEditor
public class TablePopupEditor extends DefaultCellEditor
implements TableCellEditor
{
private PopupDialog popup;
private String currentText = "";
private JButton editorComponent;
public TablePopupEditor()
{
super(new JTextField());
setClickCountToStart(1);
// Use a JButton as the editor component
editorComponent = new JButton();
editorComponent.setBackground(Color.white);
editorComponent.setBorderPainted(false);
editorComponent.setContentAreaFilled( false );
// Make sure focus goes back to the table when the dialog is closed
editorComponent.setFocusable( false );
// Set up the dialog where we do the actual editing
popup = new PopupDialog();
}
public Object getCellEditorValue()
{
return currentText;
}
public Component getTableCellEditorComponent(
JTable table, Object value, boolean isSelected, int row, int column)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
popup.setText( currentText );
// popup.setLocationRelativeTo( editorComponent );
Point p = editorComponent.getLocationOnScreen();
popup.setLocation(p.x, p.y + editorComponent.getSize().height);
popup.show();
fireEditingStopped();
}
});
currentText = value.toString();
editorComponent.setText( currentText );
return editorComponent;
}
/*
* Simple dialog containing the actual editing component
*/
class PopupDialog extends JDialog implements ActionListener
{
private JTextArea textArea;
public PopupDialog()
{
super((Frame)null, "Change Description", true);
textArea = new JTextArea(5, 20);
textArea.setLineWrap( true );
textArea.setWrapStyleWord( true );
KeyStroke keyStroke = KeyStroke.getKeyStroke("ENTER");
textArea.getInputMap().put(keyStroke, "none");
JScrollPane scrollPane = new JScrollPane( textArea );
getContentPane().add( scrollPane );
JButton cancel = new JButton("Cancel");
cancel.addActionListener( this );
JButton ok = new JButton("Ok");
ok.setPreferredSize( cancel.getPreferredSize() );
ok.addActionListener( this );
JPanel buttons = new JPanel();
buttons.add( ok );
buttons.add( cancel );
getContentPane().add(buttons, BorderLayout.SOUTH);
pack();
getRootPane().setDefaultButton( ok );
}
public void setText(String text)
{
textArea.setText( text );
}
/*
* Save the changed text before hiding the popup
*/
public void actionPerformed(ActionEvent e)
{
if ("Ok".equals( e.getActionCommand() ) )
{
currentText = textArea.getText();
}
textArea.requestFocusInWindow();
setVisible( false );
}
}
private static void createAndShowUI()
{
String[] columnNames = {"Item", "Description"};
Object[][] data =
{
{"Item 1", "Description of Item 1"},
{"Item 2", "Description of Item 2"},
{"Item 3", "Description of Item 3"}
};
JTable table = new JTable(data, columnNames);
table.getColumnModel().getColumn(1).setPreferredWidth(300);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
// Use the popup editor on the second column
TablePopupEditor popupEditor = new TablePopupEditor();
table.getColumnModel().getColumn(1).setCellEditor( popupEditor );
JFrame frame = new JFrame("Popup Editor Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JTextField(), BorderLayout.NORTH);
frame.add( scrollPane );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
Using this approach you don't continually manipulate the row size. You could even customize the code to make the dialog fit the width of the cell and appear below the cell.
Seems you need to implement your own TableCellEditor, read more in tutorial.
For example like that:
private class CustomEditor extends AbstractCellEditor implements TableCellEditor{
private JTextPane pane = new JTextPane();
private JScrollPane scroll = new JScrollPane(pane);
private int row = -1;
#Override
public Object getCellEditorValue() {
return pane.getText();
}
#Override
public Component getTableCellEditorComponent(JTable table,
Object value, boolean isSelected, int row, int column) {
if(this.row != -1)
table.setRowHeight(this.row, 20);
this.row = row;
table.setRowHeight(row, 100);
pane.setText(value == null ? "" : value.toString());
return scroll;
}
}
and then set it as column editor: table.getColumn("COMMENTS").setCellEditor(new CustomEditor());

java: dialog with 2 button for event "click on Jtable cell"?

I have a jtable with "data" in my java project:
DefaultTableModel model=(DefaultTableModel)jTablePolicyView.getModel();
for(Policy policy : sngltn.GetPerPolicies(cstmr.getPer()))
{
model.addRow(new Object[] {String.valueOf(policy.getPolicyId()),...,....});
}
I want that :
for clicking on each cell in my jtable , will spring a dialog(not Form...).
will be two buttons (with "my label") on this dialog.
i will be able to determine what action will happen(this action should use the contents of the cell) for clicking each button.
So what I'm asking?
Is it possible?
Example code, greatly help me...
Thank!
i try this code for my first mission(for clicking on each cell in my jtable)...
but it's didnt work, why?
my code:
public class UpdateCstmrForm extends javax.swing.JFrame
{
......
public UpdateCstmrForm(long person_id) throws Exception
{
DefaultTableModel model=(DefaultTableModel)jTablePolicyView.getModel();
.....
initComponents();
.....
for(Policy policy : sngltn.GetPerPolicies(cstmr.getPer()))
{
model.addRow(new Object[] {......});
}
jTablePolicyView.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
if (e.getClickCount() == 2)
{
JTable target = (JTable)e.getSource();
int row = target.getSelectedRow();
int column = target.getSelectedColumn();
System.out.println(model.getValueAt(row, column));
}
}
}
.....
}
}
You need to use a custom editor. The following example should get you started:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
/*
* The editor button that brings up the dialog.
*/
//public class TablePopupEditor extends AbstractCellEditor
public class TablePopupEditor extends DefaultCellEditor
implements TableCellEditor
{
private PopupDialog popup;
private String currentText = "";
private JButton editorComponent;
public TablePopupEditor()
{
super(new JTextField());
setClickCountToStart(1);
// Use a JButton as the editor component
editorComponent = new JButton();
editorComponent.setBackground(Color.white);
editorComponent.setBorderPainted(false);
editorComponent.setContentAreaFilled( false );
// Make sure focus goes back to the table when the dialog is closed
editorComponent.setFocusable( false );
// Set up the dialog where we do the actual editing
popup = new PopupDialog();
}
public Object getCellEditorValue()
{
return currentText;
}
public Component getTableCellEditorComponent(
JTable table, Object value, boolean isSelected, int row, int column)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
popup.setText( currentText );
// popup.setLocationRelativeTo( editorComponent );
Point p = editorComponent.getLocationOnScreen();
popup.setLocation(p.x, p.y + editorComponent.getSize().height);
popup.show();
fireEditingStopped();
}
});
currentText = value.toString();
editorComponent.setText( currentText );
return editorComponent;
}
/*
* Simple dialog containing the actual editing component
*/
class PopupDialog extends JDialog implements ActionListener
{
private JTextArea textArea;
public PopupDialog()
{
super((Frame)null, "Change Description", true);
textArea = new JTextArea(5, 20);
textArea.setLineWrap( true );
textArea.setWrapStyleWord( true );
KeyStroke keyStroke = KeyStroke.getKeyStroke("ENTER");
textArea.getInputMap().put(keyStroke, "none");
JScrollPane scrollPane = new JScrollPane( textArea );
getContentPane().add( scrollPane );
JButton cancel = new JButton("Cancel");
cancel.addActionListener( this );
JButton ok = new JButton("Ok");
ok.setPreferredSize( cancel.getPreferredSize() );
ok.addActionListener( this );
JPanel buttons = new JPanel();
buttons.add( ok );
buttons.add( cancel );
getContentPane().add(buttons, BorderLayout.SOUTH);
pack();
getRootPane().setDefaultButton( ok );
}
public void setText(String text)
{
textArea.setText( text );
}
/*
* Save the changed text before hiding the popup
*/
public void actionPerformed(ActionEvent e)
{
if ("Ok".equals( e.getActionCommand() ) )
{
currentText = textArea.getText();
}
textArea.requestFocusInWindow();
setVisible( false );
}
}
private static void createAndShowUI()
{
String[] columnNames = {"Item", "Description"};
Object[][] data =
{
{"Item 1", "Description of Item 1"},
{"Item 2", "Description of Item 2"},
{"Item 3", "Description of Item 3"}
};
JTable table = new JTable(data, columnNames);
table.getColumnModel().getColumn(1).setPreferredWidth(300);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
// Use the popup editor on the second column
TablePopupEditor popupEditor = new TablePopupEditor();
table.getColumnModel().getColumn(1).setCellEditor( popupEditor );
JFrame frame = new JFrame("Popup Editor Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JTextField(), BorderLayout.NORTH);
frame.add( scrollPane );
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
It demonstrates how to use a JTextArea as an editor for a cell.

Refreshing/updating JTable with setValueAt doesn't work correctly

I'm working on a project for my college and I need two of JFrame. The first one is the Main menu and the second one visible when JButton(Run) pressed.
I need to paint a memory in both of JFrame, So I used JTable to show the memory.
Memory class is:
public class Memory extends JPanel{
private JPanel panel;
private JTable table;
private String[] array;
private JScrollPane scrollpane;
public Memory()
{
array = new String[256]
this.addMemoryGUI();
}
public final JPanel addMemoryGUI()
{
this.panel = new JPanel();
this.panel.setPreferredSize(new Dimension(315,490));
this.panel.setLayout(null);
this.add(panel);
String info[][] = new String[256][2];
for(int j=0;j<256;j++)
{
info[j][0] = j;
info[j][1] = null;
}
String[] title = new String[]{"Address","Value"};
DefaultTableModel model = new DefaultTableModel(info,title);
table = new JTable(model){
#Override
public boolean isCellEditable(int rowIndex, int colIndex) {
return false;
}
};
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment( JLabel.CENTER );
table.getColumnModel().getColumn(0).setCellRenderer( centerRenderer );
table.getColumnModel().getColumn(1).setCellRenderer( centerRenderer );
JTableHeader header = table.getTableHeader();
header.setBackground(Color.GRAY);
this.scrollpane = new JScrollPane(this.table);
this.scrollpane.setBounds(0, 0,315, 490);
this.panel.add(this.scrollpane);
return panel;
}
public void setAddrValue(int addr,String value)
{
Memory.this.array[addr] = value;
this.table.setValueAt(value,addr , 1);
}
public String getAddrValue(int addr)
{
return Memory.this.array[addr];
}
public String[] getMemory()
{
return Memory.this.array;
}
public void deleteValue(int i)
{
array[i]=null;
this.table.setValueAt(null, i, 1);
}
}
I add this JTable into my main JFrame and another JComponents:
public class MainGUI extends JFrame{
private JTextField field1;
private JTextField field2;
private JButton button1;
private JButton button2;
private Memory mem;
public MainGUI()
{
this.GraphicComponents();
}
public final void GraphicComponents()
{
this.setTitle("Machine");
this.setSize(800, 620);
this.setLayout(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.field1=new JTextField();
this.field1.setBounds(10,50,70,20);
this.add(field1);
this.field2=new JTextField();
this.field2.setBounds(90,50,70,20);
this.add(field2);
this.button1=new JButton("Write Value");
this.button1.setBounds(170,50,130,20);
this.button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
MainGUI.this.mem.setAddrValue(MainGUI.this.field1.getText().toString(),MainGUI.this.field2.getText().toString() );
}
});
this.add(button1);
this.button2 = new JButton("Run");
this.button2.setBounds(500,550,100,30);
this.button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
ExecutionGUI exe = new ExecutionGUI(mem);
exe.setVisible(true);
}
});
this.add(button2);
this.mem = new Memory();
this.mem.setBounds(450, 30, 315, 490);
this.add(mem);
}
}
Here in this code, setValueAt() method work perfect and there is no any problem.
but when I use same code of JTabel in the second JFrame when I press run JButton but create new JTable not that in the Memory class and insert value to the JTable using setValueAt(), JTabel doesn't update.
Code of the second JFrame:
public class ExecutionGUI extends JFrame {
private JTextField field1;
private JTextField field2;
private JButton button1;
private JScrollPane scrollpane;
private JButton button2;
private Memory mem;
private JTable table;
private static DefaultTableModel model;
private String info[][];
private String[] title;
private Memory mem;
public ExecutionGUI(Memory mem)
{
this.mem = mem;
this.GraphicComponents();
}
public final void GraphicComponents()
{
this.setTitle("Run");
this.setBounds(200, 100, 800, 600);
this.setLayout(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setResizable(false);
this.info = new String[256][2];
for(int j=0;j<256;j++)
{
info[j][0] = j;
if(mem.getAddrValue(j)==null)
{
}
else
{
info[j][1] = mem.getAddrValue(j);
}
}
title = new String[]{"Address","Value"};
model = new DefaultTableModel(info,title);
table = new JTable(model){
#Override
public boolean isCellEditable(int rowIndex, int colIndex) {
return false;
}
};
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment( JLabel.CENTER );
table1.getColumnModel().getColumn(0).setCellRenderer( centerRenderer );
table1.getColumnModel().getColumn(1).setCellRenderer( centerRenderer );
JTableHeader header = table.getTableHeader();
header.setBackground(Color.GRAY);
this.scrollpane = new JScrollPane(table);
this.scrollpane.setBounds(610, 30,170, 470);
this.add(this.scrollpane);
this.field1=new JTextField();
this.field1.setBounds(10,50,70,20);
this.add(field1);
this.field2=new JTextField();
this.field2.setBounds(90,50,70,20);
this.add(field2);
this.button1=new JButton("Write Value");
this.button1.setBounds(170,50,130,20);
this.button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
table.setValueAt(MainGUI.this.field2.getText().toString(),MainGUI.this.field1.getText().toString(),1 );
}
});
this.add(button1);
}
so I have a problem only with the second JFrame and I can't refresh JTable with new data.
I have tried more than one way to take right result but there is nothing.
Thanks for your help.

Categories

Resources