I have a JTable with some rows. How can i block edit row just when radiobutton unlock is selected? Below a small project to use as a working example
Update
ElencoPersoneFrame class
package test;
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class ElencoPersoneFrame extends JFrame {
private PersonaTableModel tableModel;
private JTable table;
private JScrollPane scrollPane;
JRadioButton rdbtnFilm = new JRadioButton("Editable");
JRadioButton rdbtnSerieTv = new JRadioButton("Not editable");
public ElencoPersoneFrame()
{
super ("Elenco Persone");
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
setSize(400, 250);
ArrayList<Persona> listaPersone = new ArrayList<Persona>();
listaPersone.add(new Persona("Mario", "Rossi", 1972, false));
listaPersone.add(new Persona("Giacomo", "Bianchi", 1946, false));
listaPersone.add(new Persona("Roberto", "Verdi", 1985, true));
tableModel = new PersonaTableModel(listaPersone);
table = new JTable(tableModel);
scrollPane = new JScrollPane(table);
JPanel rdpnl=new radioPanel();
getContentPane().add(rdpnl, BorderLayout.NORTH);
getContentPane().add(scrollPane, BorderLayout.CENTER);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ElencoPersoneFrame f = new ElencoPersoneFrame();
f.setVisible(true);
}
});
}
}
Persona class
package test;
public class Persona
{
private String nome;
private String cognome;
private int annoNascita;
private boolean disoccupato;
/*costruttore*/
public Persona(String nome, String cognome, int annoNascita, boolean disoccupato) {
this.nome = nome;
this.cognome = cognome;
this.annoNascita = annoNascita;
this.disoccupato = disoccupato;
}
public String getNome() { return nome; }
public String getCognome() { return cognome; }
public int getAnnoNascita() { return annoNascita; }
public boolean isDisoccupato() { return disoccupato; }
public void setNome(String nome) { this.nome = nome; }
public void setCognome(String cognome) { this.cognome = cognome; }
public void setAnnoNascita(int annoNascita) { this.annoNascita = annoNascita; }
public void setDisoccupato(boolean disoccupato) { this.disoccupato = disoccupato; }
}
PersonaTableModel class
package test;
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
public class PersonaTableModel extends AbstractTableModel
{
private ArrayList<Persona> listaPersone;
public PersonaTableModel(ArrayList<Persona> listaPersone) {
this.listaPersone = listaPersone;
}
public int getRowCount() {
return listaPersone.size();
}
public int getColumnCount() {
return 4;
}
public String getColumnName(int column) {
switch (column) {
case 0: return "Nome";
case 1: return "Cognome";
case 2: return "Anno nascita";
case 3: return "Disoccupato?";
}
return "";
}
public Class getColumnClass(int column) {
switch (column) {
case 0: return String.class;
case 1: return String.class;
case 2: return Number.class;
case 3: return Boolean.class;
}
return Object.class;
}
public boolean isCellEditable(int row, int column) {
return true;
}
public Object getValueAt(int row, int column) {
Persona p = listaPersone.get(row);
switch (column) {
case 0: return p.getNome();
case 1: return p.getCognome();
case 2: return p.getAnnoNascita();
case 3: return p.isDisoccupato();
}
return null;
}
public void setValueAt(Object value, int row, int column)
{
Persona p = listaPersone.get(row);
switch (column)
{
case 0: p.setNome((String) value); break;
case 1: p.setCognome((String) value); break;
case 2: p.setAnnoNascita((Integer) value); break;
case 3: p.setDisoccupato((Boolean) value); break;
}
}
public void aggiungiPersona(Persona p) {
listaPersone.add(p);
int row = listaPersone.size() - 1;
fireTableRowsInserted(row, row);
}
}
radioPanel class
package test;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class radioPanel extends JPanel implements ActionListener
{
private JRadioButton unlock;
private JRadioButton lock;
private ButtonGroup rdgroup;
public radioPanel()
{
rdgroup=new ButtonGroup();
unlock = new JRadioButton("Editable");
lock = new JRadioButton("Not editable");
rdgroup.add(unlock);
rdgroup.add(lock);
rdgroup.setSelected(unlock.getModel(), true);
this.add(unlock);
this.add(lock);
lock.addActionListener(this);
unlock.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == this.lock)
{
}
if(e.getSource() == this.unlock)
{
}
}
}
So there doesn't seem to be (AFAIK) some magic method to set the table uneditable. What you can do though is create a method in your model, like setEditable(boolean), where you can set a class member boolean editable. Use the same field for isCellEditable. After you change the state, you should fire the table change. Something like
class PersonaTableModel extends AbstractTableModel {
...
private boolean editable = true;
public boolean isEditable() {
return editable;
}
public boolean isCellEditable(int row, int column) {
return editable;
}
public void setEditable(boolean editable) {
this.editable = editable;
fireTableDataChanged();
}
...
}
You'll also need to way for the ActionListener to get hold of the table model. So you can refactor your radio panel to something like
class radioPanel extends JPanel {
private JRadioButton unlock;
private JRadioButton lock;
private ButtonGroup rdgroup;
...
public ButtonGroup getButtonGroup() {
return rdgroup;
}
public AbstractButton getUnlock() {
return unlock;
}
public AbstractButton getLock() {
return lock;
}
}
This way you can just get the radio buttons from anywhere and add the ActionListener. So you can change you main class code to something like:
radioPanel rdpnl = new radioPanel();
rdpnl.getUnlock().addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
tableModel.setEditable(true);
}
});
rdpnl.getLock().addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
tableModel.setEditable(false);
}
});
getContentPane().add(rdpnl, BorderLayout.NORTH);
Tested, and seems to work as expected.
Aside: Please make note of Java naming convention. Class names should begin with upper case letters i.e. radioPanel → RadioPanel
You need to implement the isCellEditable method for your TableModel:
public boolean isCellEditable(int row, int col)
return false;
See also the tutorials.
Related
I am dynamically creating JTextField based on click event on '+' button. Below is screen shot.
The problem is when I click '+' button, fields created but not shown on JFrame. When I put the cursor on next row under 'item Name', text field becomes visible.
Where is the problem?
Below is my code.
CreateBill()
{
jf = new JFrame("Create Bill");
jf.getContentPane().setLayout(null);
jf.setExtendedState(JFrame.MAXIMIZED_BOTH);
jf.setBounds(0, 0, d1.width, d1.height);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createRow(); // This will create first row by default.
jf.pack();
jf.setVisible(true);
}
private void createRow() {
textField = new JTextField();
textField.setToolTipText("item name");
textField.setBounds(143, 46+j, 288, 20);
textField.setColumns(10);
textField.getDocument().addDocumentListener(new DocumentListener()
{
#Override
public void insertUpdate(DocumentEvent e) {
updatePrice();
}
#Override
public void removeUpdate(DocumentEvent e) {
}
#Override
public void changedUpdate(DocumentEvent e) {
updatePrice();
}
});
AutoCompleteDecorator.decorate(textField, names, true);
jf.getContentPane().add(comboComplete);
jf.getContentPane().add(textField);
comboComplete.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e)
{
String ItemSel = textField.getText().trim();
for(Item s:items)
{
if(s.getItemName().equals(ItemSel))
{
textField_1.setText(String.valueOf(s.getUnitPrice()));
}
}
}
});
textFields.add(textField);
textField_1 = new JTextField();
textField_1.setEditable(false);
textField_1.setBounds(639, 46+j, 175, 20);
jf.getContentPane().add(textField_1);
textField_1.setColumns(10);
qty = new JTextField();
qty.setBounds(455, 46+j, 156, 20);
jf.getContentPane().add(qty);
qty.setColumns(10);
qty.getDocument().addDocumentListener(new DocumentListener()
{
#Override
public void insertUpdate(DocumentEvent e) {
getTotal();
}
#Override
public void removeUpdate(DocumentEvent e) {
}
#Override
public void changedUpdate(DocumentEvent e) {
getTotal();
}
});
textFields.add(qty);
textFields.add(textField_1);
textField_3 = new JTextField();
textField_3.setEditable(false);
textField_3.setBounds(1038, 46+j, 156, 20);
jf.getContentPane().add(textField_3);
textField_3.setColumns(10);
textFields.add(textField_3);
JButton button = new JButton("+");
button.setBounds(1235, 45+j, 89, 23);
jf.getContentPane().add(button);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("value of J"+j);
createRow(); // after pressing '+' button i am calling same method again. by changing value of j.
}
});
j=j+22;
jf.setVisible(true);
}
I want my all 4 text fields appear simultaneously.
You need to call repaint() on the container after adding a component to it. You also should call revalidate() too, before calling repaint, since this tells the layout managers to layout the new component, but you're using null layouts, something that you really want to avoid doing.
So my suggestion is to either 1) use nested JPanels with appropriate layout managers, and call revalidate and repaint on your containers after adding or removing components, or 2) yeah, use a Cardlayout to swap views as Andrew Thompson astutely recommends. You can have your second JPanel have a JTextField that uses the same Document as the previous JPanel, so it looks like both are using the same JTextField (as the top JTextField).
On looking further at your images, I have to wonder if a JTable might be an even better solution overall. And yeah, after you start using the layout managers, do also call pack() on your top level window after adding all components and before setting it visible.
For an example of a JTable implementation of this, something along the lines of...
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
#SuppressWarnings("serial")
public class CreateRowGui extends JPanel {
private static final Item[] ITEMS = {
new Item("Light Bulb", 2.00),
new Item("Toilet Paper", 3.00),
new Item("Toothpaste", 1.50),
new Item("Aspirin", 3.75) };
private ItemTableModel tableModel = new ItemTableModel();
private JTable table = new JTable(tableModel);
private AddRowAction addRowAction = new AddRowAction("Add Row", KeyEvent.VK_A);
public CreateRowGui() {
TableCellRenderer moneyRenderer = new DefaultTableCellRenderer() {
private NumberFormat currFormat = NumberFormat.getCurrencyInstance();
#Override
protected void setValue(Object value) {
if (value != null) {
value = currFormat.format(value);
}
super.setValue(value);
}
};
table.getColumnModel().getColumn(2).setCellRenderer(moneyRenderer);
table.getColumnModel().getColumn(3).setCellRenderer(moneyRenderer);
JPanel btnPanel = new JPanel();
btnPanel.add(new JButton(addRowAction));
btnPanel.add(new JButton("Remove Row")); // TODO: need Action for this
setLayout(new BorderLayout());
add(new JScrollPane(table));
add(btnPanel, BorderLayout.PAGE_END);
}
class AddRowAction extends AbstractAction {
private NewRowPanel newRowPanel = new NewRowPanel(ITEMS);
public AddRowAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
newRowPanel.reset();
int reply = JOptionPane.showConfirmDialog(table,
newRowPanel.getMainPanel(),
"Select Item and Quantity",
JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);
if (reply == JOptionPane.OK_OPTION) {
Item item = newRowPanel.getSelectedItem();
int quantity = newRowPanel.getQuantity();
tableModel.addRow(item, quantity);
}
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("CreateRowGui");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new CreateRowGui());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
class NewRowPanel {
private JPanel mainPanel = new JPanel();
private JComboBox<Item> itemsCombo;
private JSpinner quantitySpinner = new JSpinner(new SpinnerNumberModel(0, 0, 20, 1));
#SuppressWarnings("serial")
public NewRowPanel(Item[] items) {
itemsCombo = new JComboBox<>(items);
itemsCombo.setRenderer(new DefaultListCellRenderer(){
#Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected,
boolean cellHasFocus) {
if (value != null) {
value = ((Item) value).getName();
} else {
value = "";
}
return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
}
});
mainPanel.add(new JLabel("Item:"));
mainPanel.add(itemsCombo);
mainPanel.add(Box.createHorizontalStrut(15));
mainPanel.add(new JLabel("Quantity"));
mainPanel.add(quantitySpinner);
}
public void reset() {
itemsCombo.setSelectedIndex(-1);
quantitySpinner.setValue(0);
}
public JPanel getMainPanel() {
return mainPanel;
}
public Item getSelectedItem() {
return (Item) itemsCombo.getSelectedItem();
}
public int getQuantity() {
return (int) quantitySpinner.getValue();
}
}
class ItemTableModel extends AbstractTableModel {
private static final String[] COL_NAMES = { "Item Name", "Quantity", "Unit Price", "Total" };
private static final long serialVersionUID = 1L;
private List<ItemWithCount> itemsWithCount = new ArrayList<>();
#Override
public int getColumnCount() {
return 4;
}
#Override
public int getRowCount() {
return itemsWithCount.size();
}
#Override
public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case 0:
return super.getColumnClass(columnIndex);
case 1:
return Integer.class;
case 2:
case 3:
return Double.class;
}
return super.getColumnClass(columnIndex);
}
#Override
public String getColumnName(int column) {
return COL_NAMES[column];
}
#Override
public Object getValueAt(int row, int column) {
ItemWithCount itemWithCount = itemsWithCount.get(row);
switch (column) {
case 0:
return itemWithCount.getItem().getName();
case 1:
return itemWithCount.getCount();
case 2:
return itemWithCount.getItem().getUnitPrice();
case 3:
return itemWithCount.getCount() * itemWithCount.getItem().getUnitPrice();
}
return null;
}
#Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
ItemWithCount itemWithCount = itemsWithCount.get(rowIndex);
switch (columnIndex) {
case 1:
itemWithCount.setCount((int) aValue);
fireTableRowsUpdated(rowIndex, rowIndex);
break;
default:
break;
}
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return columnIndex == 0 || columnIndex == 1;
}
public void addRow(Item item, int quantity) {
ItemWithCount itemWithCount = new ItemWithCount(item, quantity);
itemsWithCount.add(itemWithCount);
int row = itemsWithCount.size() - 1;
fireTableRowsInserted(row, row);
}
private class ItemWithCount {
private Item item;
private int count;
public ItemWithCount(Item item, int count) {
this.item = item;
this.count = count;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public Item getItem() {
return item;
}
}
}
class Item {
private String name;
private double unitPrice;
public Item(String name, double unitPrice) {
this.name = name;
this.unitPrice = unitPrice;
}
public String getName() {
return name;
}
public double getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
#Override
public String toString() {
return "Item [name=" + name + ", unitPrice=" + unitPrice + "]";
}
}
The JDialog isn't showing the JPanel after closing of the dialog and then if the user immediately repeats the action it isn't showing a panel at all but a dialog that is solid black with a small white box in the top left corner. I have tried creating a SSCCE but couldn't develop one. If I remove the window adapter in MainControl class it will just keep adding another panel to the dialog after closing and repeating the opening of the dialog. Below is the code of the SSCCE that I tried creating but it still behaves the same. The code below is the minimal amount needed to run the dialog.
public class CreateAndShowUI {
public static void createUI() {
JFrame frame = new JFrame();
MainPanel mainPanel = new MainPanel();
Dialog dialog = new Dialog();
MainControl mainControl = new MainControl(frame, mainPanel,
dialog);
frame.getContentPane().add(mainPanel.getMainPanel());
frame.setUndecorated(true);
frame.setPreferredSize(new Dimension(1100, 550));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
createUI();
}
}
public class MainControl {
private JFrame frame;
private MainPanel mainPanel;
private Dialog dialog;
public MainControl(JFrame frame, MainPanel panel, Dialog dialog) {
this.frame = frame;
this.mainPanel = panel;
this.dialog = dialog;
mainPanel.getTable().addMouseListener(new MouseListener());
dialog.getDialog().addWindowListener(new DialogWindowListener());
}
public class MouseListener extends MouseAdapter {
#Override
public void mousePressed(MouseEvent evt) {
if (evt.getButton() == MouseEvent.BUTTON3) {
dialog.showDialog(new KeywordPanel().getKeywordPanel(),
evt.getXOnScreen(), evt.getYOnScreen());
}
}
}
public class DialogWindowListener extends WindowAdapter {
#Override
public void windowClosing(final WindowEvent event) {
dialog.getDialog().dispose();
dialog.getDialog().removeAll();
}
}
}
public class MainPanel {
private JPanel mainPanel;
private JScrollPane listScrollPane;
private JTable table;
public MainPanel() {
mainPanel = new JPanel(new MigLayout("", "", "[]13[]"));
table = new JTable(new ProductTableModel());
listScrollPane = new JScrollPane(table,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
listScrollPane.setPreferredSize(new Dimension(850, 990));
mainPanel.add(listScrollPane, "cell 0 1");
}
public JPanel getMainPanel() {
return mainPanel;
}
public JTable getTable() {
return table;
}
}
public class KeywordPanel {
private JPanel keywordPanel;
private JLabel searchLbl;
public KeywordPanel() {
searchLbl = new JLabel("KeyWords");
keywordPanel = new JPanel();
keywordPanel.add(searchLbl);
}
public JPanel getKeywordPanel() {
return keywordPanel;
}
}
public class Dialog {
private JDialog dialog = new JDialog();
public Dialog() {
dialog.setLayout(new MigLayout());
}
public void showDialog(JPanel panel, int x, int y) {
dialog.add(panel);
dialog.pack();
dialog.setVisible(true);
}
public JDialog getDialog() {
return dialog;
}
}
public class ProductTableModel extends AbstractTableModel {
private ArrayList<Object> list = new ArrayList<Object>();
private String[] columnNames = { "ID", "Description", "Inventory",
"Minimum Quantity", "Cost", "Order Quantity" };
public ProductTableModel() {
list.add(new Product("Sup", "Sup", "Sup", 10, 20, "null"));
}
#Override
public int getColumnCount() {
return columnNames.length;
}
#Override
public String getColumnName(int column) {
switch (column) {
case 0:
return "<html>ID<br></html>";
case 1:
return "<html>Description<br></html>";
case 2:
return "<html>Inventory<br></html>";
case 3:
return "<html>Minimum<br>Quantity</html>";
case 4:
return "<html>Cost<br></html>";
case 5:
return "<html>Order<br>Quantity</html>";
default:
return null;
}
}
#Override
public int getRowCount() {
return list.size();
}
#Override
public boolean isCellEditable(int row, int column) {
return true;
}
#Override
public Object getValueAt(int row, int column) {
if (list.get(row) instanceof Product) {
Product product = (Product) list.get(row);
switch (column) {
case 0:
return product.getId();
case 1:
return product.getProductDescription();
case 2:
return product.getQtyOnHand();
case 3:
return product.getMinQty();
case 4:
return product.getCost();
case 5:
return product.getOrderQty();
default:
throw new IndexOutOfBoundsException();
}
} else {
return null;
}
}
}
public class Product {
private int minQty;
private double cost;
private String productDescription, id, category, qtyOnHand, orderQty;
public Product(String id, String productDescription, String qtyOnHand,
int minQty, double cost, String orderQty) {
this.setQtyOnHand(qtyOnHand);
this.setOrderQty(orderQty);
this.setId(id);
this.setMinQty(minQty);
this.setCost(cost);
this.setProductDescription(productDescription);
}
public String getQtyOnHand() {
return qtyOnHand;
}
public void setQtyOnHand(String qtyOnHand) {
this.qtyOnHand = qtyOnHand;
}
public String getOrderQty() {
return orderQty;
}
public void setOrderQty(String orderQty) {
this.orderQty = orderQty;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public double getCost() {
return cost;
}
public void setCost(double cost) {
this.cost = cost;
}
public String getProductDescription() {
return productDescription;
}
public void setProductDescription(String productDescription) {
this.productDescription = productDescription;
}
public int getMinQty() {
return minQty;
}
public void setMinQty(int minQty) {
this.minQty = minQty;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
You should use
dialog.getContentPane().add(panel);
and
dialog.getDialog().getContentPane().removeAll();
And you also must NOT dispose the dialog,
Hi,
I have created my TableModel and want to refresh JTable once I added a new row. What should be added to the listener to "refresh" JTable?
public class MyTableModel implements TableModel {
private Set<TableModelListener> listeners = new HashSet<TableModelListener>();
//List<Staff> staffs = Factory.getInstance().getStaffDAO().getAllStaff();
private List<Staff> staffs;
public MyTableModel(List<Staff> staffs){
this.staffs = staffs;
}
#Override
public int getRowCount() {
return staffs.size();
}
#Override
public int getColumnCount() {
return 5;
}
#Override
public String getColumnName(int columnIndex) {
switch (columnIndex){
case 0:
return "First Name";
case 1:
return "Second Name";
case 2:
return "Date";
case 3:
return "Position";
case 4:
return "Salary";
}
return "";
}
#Override
public Class<?> getColumnClass(int columnIndex) {
return Object.class;
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Staff staff = staffs.get(rowIndex);
switch (columnIndex){
case 0:
return staff.getName();
case 1:
return staff.getSurname();
case 2:
return staff.getDate();
case 3:
return staff.getPosition();
case 4:
return staff.getSalary();
}
return "";
}
#Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
}
#Override
public void addTableModelListener(TableModelListener l) {
}
#Override
public void removeTableModelListener(TableModelListener l) {
}
}
Here is my listener of my Add row Button:
#Override
public void actionPerformed(ActionEvent e) {
Staff staff = new Staff();
staff.setName(JOptionPane.showInputDialog("Enter First Name"));
staff.setSurname(JOptionPane.showInputDialog("Enter Second Name"));
staff.setDate(JOptionPane.showInputDialog("Enter Date"));
staff.setPosition(JOptionPane.showInputDialog("Enter Position"));
staff.setSalary(JOptionPane.showInputDialog("Enter Salary"));
try {
Factory.getInstance().getStaffDAO().addStaff(staff);
} catch (SQLException e1) {
e1.printStackTrace();
}
!!!Here should be some code that will be firing my table after adding new row!!!
}
I've tried to use method firetabledatachanged() of AbstractTableModel in my actionPerformed() but with unluck, it is appeared ClassCastException.
UPDATE 1
WorkPlaceGui.java
public class WorkPlaceGui extends JFrame implements ActionListener {
AbstractTableModel model;
JTable jTable;
JScrollPane jScrollPane;
public WorkPlaceGui()throws SQLException{
List<Staff> staffs = Factory.getInstance().getStaffDAO().getAllStaff();
for(int i = 0; i < 0; i++) {
staffs.add(new Staff("First Name " + staffs.get(i).getName(), "Second Name " + staffs.get(i).getSurname(), "Date " + staffs.get(i).getDate(), "Position " + staffs.get(i).getPosition(), "Salary " + staffs.get(i).getSalary()));
}
model = new MyTableModel(staffs);
jTable = new JTable(model);
JButton jBtnAdd = new JButton("Добавить");
JButton jBtnDel = new JButton("Удалить");
JButton jBtnUpd = new JButton("Обновить");
JButton jBtnAdmin = new JButton("Админка");
JPanel panelNorth = new JPanel();
JPanel panelCenter = new JPanel();
JPanel panelSouth = new JPanel();
jTable.setPreferredScrollableViewportSize(new Dimension(350, 150));
jScrollPane = new JScrollPane(jTable);
panelNorth.setLayout(new FlowLayout());
panelNorth.add(jBtnAdd);
panelNorth.add(jBtnDel);
panelNorth.add(jBtnUpd);
panelNorth.add(jBtnAdmin);
panelCenter.add(jScrollPane);
setLayout(new BorderLayout());
add(panelNorth, BorderLayout.NORTH);
add(panelCenter, BorderLayout.CENTER);
jBtnAdd.addActionListener(this);
setPreferredSize(new Dimension(550, 300));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setTitle("Staff data base");
pack();
setVisible(true);
setLocationRelativeTo(null);
}
#Override
public void actionPerformed(ActionEvent e) {
Staff staff = new Staff();
staff.setName(JOptionPane.showInputDialog("Enter First Name"));
staff.setSurname(JOptionPane.showInputDialog("Enter Second Name"));
staff.setDate(JOptionPane.showInputDialog("Enter Date"));
staff.setPosition(JOptionPane.showInputDialog("Enter Position"));
staff.setSalary(JOptionPane.showInputDialog("Enter Salary"));
try {
Factory.getInstance().getStaffDAO().addStaff(staff);
} catch (SQLException e1) {
e1.printStackTrace();
}
model.fireTableDataChanged();
}
}
MyTableModel.java
public class MyTableModel extends AbstractTableModel {
private List<Staff> staffs;
public MyTableModel(List<Staff> staffs){
this.staffs = staffs;
}
#Override
public int getRowCount() {
return staffs.size();
}
#Override
public int getColumnCount() {
return 5;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Staff staff = staffs.get(rowIndex);
switch (columnIndex){
case 0:
return staff.getName();
case 1:
return staff.getSurname();
case 2:
return staff.getDate();
case 3:
return staff.getPosition();
case 4:
return staff.getSalary();
}
return "";
}
}
You've done it the hard way.
First of all, you've implemented directly from TableModel and secondly you've failed to implement the listener requirements...
Instead, try extending from the AbstractTableModel instead, which already includes the implementations of the listener registration and notification.
You will need to provide a method that will allow you to add a row to the table model. In this method you need to use the fireTableRowsInserted method which will notify any tables using the model, that a new row has been added...
Update with example
This is VERY, VERY basic example. It's only intention is to demonstrate the use of fireTableRowsInserted. It uses a Swing Timer to add a new row every 125 milliseconds until you kill it ;)
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;
public class DynamicTable {
public static void main(String[] args) {
new DynamicTable();
}
public DynamicTable() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
final MyTableModel model = new MyTableModel();
JTable table = new JTable(model);
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Timer timer = new Timer(125, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
model.addRow();
}
});
timer.start();
}
});
}
public class MyTableModel extends AbstractTableModel {
private List<String[]> rows;
public MyTableModel() {
rows = new ArrayList<>(25);
}
#Override
public int getRowCount() {
return rows.size();
}
#Override
public int getColumnCount() {
return 4;
}
#Override
public Class<?> getColumnClass(int columnIndex) {
return String.class;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
String[] row = rows.get(rowIndex);
return row[columnIndex];
}
public void addRow() {
int rowCount = getRowCount();
String[] row = new String[getColumnCount()];
for (int index = 0; index < getColumnCount(); index++) {
row[index] = rowCount + "x" + index;
}
rows.add(row);
fireTableRowsInserted(rowCount, rowCount);
}
}
}
Updated with another example
Because your table model is backed by its own List, it has no connection to your factory. It doesn't know when you add or remove objects from it. This means you become responsible for updating the model:
public class MyTableModel extends AbstractTableModel {
private List<Staff> staffs;
public MyTableModel(List<Staff> staffs){
this.staffs = staffs;
}
#Override
public int getRowCount() {
return staffs.size();
}
#Override
public int getColumnCount() {
return 5;
}
public void add(Staff staff) {
int size = getSize();
staffs.add(staff);
fireTableRowsInserted(size, size);
}
public void remove(Staff staff) {
if (staffs.contains(staff) {
int index = stafff.indexOf(staff);
staffs.remove(staff);
fireTableRowsDeleted(index, index);
}
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Staff staff = staffs.get(rowIndex);
switch (columnIndex){
case 0:
return staff.getName();
case 1:
return staff.getSurname();
case 2:
return staff.getDate();
case 3:
return staff.getPosition();
case 4:
return staff.getSalary();
}
return "";
}
}
And your actionPerformed:
#Override
public void actionPerformed(ActionEvent e) {
Staff staff = new Staff();
staff.setName(JOptionPane.showInputDialog("Enter First Name"));
staff.setSurname(JOptionPane.showInputDialog("Enter Second Name"));
staff.setDate(JOptionPane.showInputDialog("Enter Date"));
staff.setPosition(JOptionPane.showInputDialog("Enter Position"));
staff.setSalary(JOptionPane.showInputDialog("Enter Salary"));
try {
Factory.getInstance().getStaffDAO().addStaff(staff);
((MyTableModel)model).add(staff);
} catch (SQLException e1) {
e1.printStackTrace();
}
}
Your class MyTableModel implements TableModel, but it has no event handling mechanism to connect the model to the view. Instead extend AbstractTableModel, as shown here and here. AbstractTableModel provides the fireTable* methods needed for this.
public void setValueAt(Object value, int row, int col) {
data[row][col] = value;
fireTableCellUpdated(row, col);
}
Well, first of all, find more about Observer pattern (http://en.wikipedia.org/wiki/Observer_pattern).
I suggest that you create a ObservableModel class that will have a list of PropertyChangeListeners. Your StaffDAO should extend this ObservableModel. When the new staff is added (i.e. addStaff is called) you should call ObservableModel's firePorpertyChange or something like that. firePropertyChange notifyies all propertyChangeListeners. One of those listeners should be registered in your Table, and its propertyChanged method should be implemented with refreshing of the table (hd1) had a good answer.
myTableModel.fireTableDataChanged(); should be just enough to force a refresh of your table. As usual, if you have further problems, do feel free to leave a comment.
For a more general solution you can use the Row Table Model and just implement the getValueAt() and setValueAt() methods.
Here should be some code that will be firing my table after adding new row!
The model is responsible for invoking the proper fireXXX method.
Use this type of casting.
((AbstractTableModel)student.getModel()).fireTableCellUpdated();
My problem is:
I have a button that will add components to a JList when it is clicked. Each row of the list is composed by two jtextFields. The first is the ID of the row. Every time I press the "Add button", a new row appears, the ID is incremented, and the person who is using the application will write whatever he want on the second jTextField (forward the ID field).
Then it will have a scroll pane for when there are more than 4 rows.
And I want a Remove Button too. To be possible to remove some rows.
Can you help me with this? I don't know how to create a list like this...
Thanks!
Simply use JTable with two columns. This will allow you to establish two columns, one for the ID and one for the value. This will allow you make the second column editable.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.AbstractTableModel;
public class TestTable04 {
public static void main(String[] args) {
new TestTable04();
}
private int id = 0;
public TestTable04() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
final RecordTableModel model = new RecordTableModel();
JTable table = new JTable(model);
JButton add = new JButton("Add");
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
model.add(new Record(++id));
}
});
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(add, BorderLayout.SOUTH);
frame.add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class Record {
private int id;
private String value;
public Record(int id) {
this.id = id;
}
public int getID() {
return id;
}
public void setValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
public class RecordTableModel extends AbstractTableModel {
private List<Record> lstRecords;
public RecordTableModel() {
lstRecords = new ArrayList<>(24);
}
public void add(Record record) {
lstRecords.add(record);
fireTableRowsInserted(lstRecords.size() - 1, lstRecords.size() - 1);
}
public void remove(Record record) {
if (lstRecords.contains(record)) {
int index = lstRecords.indexOf(record);
remove(index);
}
}
public void remove(int index) {
lstRecords.remove(index);
fireTableRowsDeleted(index, index);
}
#Override
public int getRowCount() {
return lstRecords.size();
}
#Override
public int getColumnCount() {
return 2;
}
#Override
public Class<?> getColumnClass(int columnIndex) {
Class clazz = String.class;
switch (columnIndex) {
case 0:
clazz = Integer.class;
break;
}
return clazz;
}
#Override
public String getColumnName(int column) {
String name = null;
switch (column) {
case 0:
name = "ID";
break;
case 1:
name = "Value";
break;
}
return name;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Record record = lstRecords.get(rowIndex);
Object value = null;
switch (columnIndex) {
case 0:
value = record.getID();
break;
case 1:
value = record.getValue();
break;
}
return value;
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return columnIndex == 1;
}
#Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
Record record = lstRecords.get(rowIndex);
switch (columnIndex) {
case 1:
record.setValue(aValue == null ? null : aValue.toString());
fireTableCellUpdated(rowIndex, columnIndex);
break;
}
}
}
}
Check out How to use tables for more details
You can try creating a custom ListCellRenderer and use JList's setRenderer method to assign it. Override the getListCellRenderer() method of ListCellRenderer to return a JPanel containing two components, a JLabel for the id, and a JTextfield for the user input. You may need to keep a reference to the JTextField elsewhere so that you can retrieve the user input.
To implement the add and remove methods, I would recommend backing the JList with a ListModel. Add and remove to the ListModel will also update the JList UI.
I have a problem with the following code. My task is, I have to have radio buttons in the first column and when a user selects that radio button that row is selected and sent for processing. But my problem is, I am able to select the radio button which are in the first column, but afterwards when user clicks in any part of the table then my clicked radio button is being unchecked. I am not able to figure, why it is happeneing. I am really stuck with this problem. Help required. The following code shows my problem.
import java.awt.Component;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.ButtonGroup;
import javax.swing.DefaultCellEditor;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
public class DisplayTable extends JDialog {
public void initialize() {
SourceTableModel stm = new SourceTableModel();
JTable sourceTable = new JTable(stm);
sourceTable.getColumnModel().getColumn(0).setCellRenderer(new RadioButtonRenderer());
sourceTable.getColumnModel().getColumn(0).setCellEditor(new RadioButtonEditor(new JCheckBox ()));
JPanel panel = new JPanel();
panel.add(new JScrollPane(sourceTable));
add(panel);
setModal(true);
pack();
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new DisplayTable().initialize();
}
});
}
}
class SourceTableModel extends AbstractTableModel{
private static final long serialVersionUID = 1L;
private List<SourceModel> sourceList = new ArrayList<SourceModel>();
private String[] columnNamesList = {"Select", "Group", "Work"};
public SourceTableModel() {
this.sourceList = getSourceDOList();
}
public String getColumnName(int column) {
return columnNamesList[column];
}
public int getRowCount() {
return sourceList.size();
}
public int getColumnCount() {
return columnNamesList.length;
}
public Class<?> getColumnClass(int columnIndex) {
return (columnIndex == 0 ? Boolean.class : String.class);
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return (columnIndex == 0 ? true : false);
}
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
SourceModel model = (SourceModel) sourceList.get(rowIndex);
switch (columnIndex) {
case 0:
model.setSelect((Boolean)aValue);
break;
case 1:
model.setFactory((String) aValue);
break;
case 2:
model.setSupplier((String) aValue);
break;
}
fireTableCellUpdated(rowIndex, columnIndex);
}
public Object getValueAt(int rowIndex, int columnIndex) {
SourceModel source = sourceList.get(rowIndex);
switch(columnIndex){
case 0:
return source.isSelect();
case 1:
return source.getFactory();
case 2:
return source.getSupplier();
default:
return null;
}
}
private List<SourceModel> getSourceDOList() {
List<SourceModel> tempSourceList=new ArrayList<SourceModel>();
for (int index = 0; index < 5; index++) {
SourceModel source = new SourceModel();
source.setSelect(false);
source.setFactory("group");
source.setSupplier("Work");
tempSourceList.add(source);
}
return tempSourceList;
}
}
class SourceModel {
private boolean select;
private String factory;
private String supplier;
public SourceModel() {
// No Code;
}
public SourceModel(boolean select, String factory, String supplier) {
super();
this.select = select;
this.factory = factory;
this.supplier = supplier;
}
public boolean isSelect() {
return select;
}
public void setSelect(boolean select) {
this.select = select;
}
public String getFactory() {
return factory;
}
public void setFactory(String factory) {
this.factory = factory;
}
public String getSupplier() {
return supplier;
}
public void setSupplier(String supplier) {
this.supplier = supplier;
}
}
class RadioButtonEditor extends DefaultCellEditor implements ItemListener {
public JRadioButton btn = new JRadioButton();
public RadioButtonEditor(JCheckBox checkBox) {
super(checkBox);
}
public Component getTableCellEditorComponent(JTable table, Object
value, boolean isSelected, int row, int column) {
if (value==null)
return null;
btn.addItemListener(this);
if (( (Boolean) value).booleanValue())
btn.setSelected(true);
else
btn.setSelected(false);
return btn;
}
public Object getCellEditorValue() {
if(btn.isSelected() == true)
return new Boolean(true);
else
return new Boolean(false);
}
public void itemStateChanged(ItemEvent e) {
super.fireEditingStopped();
}
}
class RadioButtonRenderer implements TableCellRenderer {
public JRadioButton btn = new JRadioButton();
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (value==null) return null;
if(((Boolean)value).booleanValue())
btn.setSelected(true);
else
btn.setSelected(false);
if (isSelected) {
btn.setForeground(table.getSelectionForeground());
btn.setBackground(table.getSelectionBackground());
} else {
btn.setForeground(table.getForeground());
btn.setBackground(table.getBackground());
}
return btn;
}
}
EDIT:
I have updated my code and I have used Boolean class for the first column. The problem which I am facing is, if I remove super.fireEditingStopped(); from RadioButtonEditor class then I am able to check and then if I click at any part of the table then checked one I being unchecked. If I keep the super.fireEditingStopped(); then I am not even able to check the Radio button.
I know that super.fireEditingStopped(); will stop editing. But my question is how to check it?
P.S: Sorry I have posted my entire code. I thought it will be easy for some one to look at the problem.
This is the screen shot of the program.
From your illustration, it appears that you want to enforce mutual exclusion among the rows of a JTable, where each row has a single JRadioButton. As a ButtonGroup is unsuitable, this example due to #Guillaume Polet uses a custom manager.
I have a problem with the following code. My task is, I have to have
radio buttons in the first column and when a user selects that radio
button that row is selected and sent for processing. But my problem
is, I am able to select the radio button which are in the first
column, but afterwards when user clicks in any part of the table then
my clicked radio button is being unchecked. I am not able to figure,
why it is happeneing. I am really stuck with this problem. Help
required. The following code shows my problem.
don't to use JRadioButton, use built_in support for Boolean value in JTable == JCheckBox,
then you can sorting and filtering based on Boolean value
otherwise you have to override to String ("true" / "false")
there are a few good JRadioButtons as Renderer and Editor in JTable, including usage of JComboBox as Editor for RadioButtonGroup
If you need to dynamically change the Look and Feel, your CellEditor is recommended to extend Component.
//#see javax/swing/SwingUtilities.java
static void updateRendererOrEditorUI(Object rendererOrEditor) {
if (rendererOrEditor == null) {
return;
}
Component component = null;
if (rendererOrEditor instanceof Component) {
component = (Component)rendererOrEditor;
}
if (rendererOrEditor instanceof DefaultCellEditor) {
//Ahh, AbstractCellEditor ...
component = ((DefaultCellEditor)rendererOrEditor).getComponent();
}
if (component != null) {
SwingUtilities.updateComponentTreeUI(component);
}
}
Here is a "CellEditor extends JRadioButton ..." example:
import java.awt.*;
import java.awt.event.*;
import java.util.EventObject;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class DisplayTable2 extends JDialog {
public void initialize() {
Object[][] data = {
{ true, "Group1", "Work1" }, { false, "Group2", "Work2" },
{ false, "Group3", "Work3" }, { false, "Group4", "Work4" }
};
JTable sourceTable = new JTable(new SourceTableModel(data));
sourceTable.getColumnModel().getColumn(0).setCellRenderer(new RadioButtonRenderer());
sourceTable.getColumnModel().getColumn(0).setCellEditor(new RadioButtonEditor());
JPanel panel = new JPanel();
panel.add(new JScrollPane(sourceTable));
add(panel);
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setModal(true);
pack();
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override public void run() {
new DisplayTable2().initialize();
}
});
}
}
class SourceTableModel extends DefaultTableModel {
private static final String[] columnNamesList = {"Select", "Group", "Work"};
public SourceTableModel(Object[][] data) {
super(data, columnNamesList);
}
#Override public Class<?> getColumnClass(int columnIndex) {
return (columnIndex == 0 ? Boolean.class : String.class);
}
#Override public boolean isCellEditable(int rowIndex, int columnIndex) {
return (columnIndex == 0 ? true : false);
}
#Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
if(columnIndex==0 && aValue instanceof Boolean) {
//lazy development
for(int i=0; i<getRowCount(); i++) {
super.setValueAt(i==rowIndex, i, columnIndex);
}
} else {
super.setValueAt(aValue, rowIndex, columnIndex);
}
}
}
class RadioButtonRenderer extends JRadioButton implements TableCellRenderer {
#Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if(value instanceof Boolean) {
setSelected((Boolean)value);
}
return this;
}
}
class RadioButtonEditor extends JRadioButton implements TableCellEditor {
public RadioButtonEditor() {
super();
addActionListener(new ActionListener() {
#Override public void actionPerformed(ActionEvent e) {
fireEditingStopped();
}
});
}
#Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
if(value instanceof Boolean) {
setSelected((Boolean)value);
}
return this;
}
#Override public Object getCellEditorValue() {
return isSelected();
}
//Copid from AbstractCellEditor
//protected EventListenerList listenerList = new EventListenerList();
//transient protected ChangeEvent changeEvent = null;
#Override public boolean isCellEditable(EventObject e) {
return true;
}
#Override public boolean shouldSelectCell(EventObject anEvent) {
return true;
}
#Override public boolean stopCellEditing() {
fireEditingStopped();
return true;
}
#Override public void cancelCellEditing() {
fireEditingCanceled();
}
#Override public void addCellEditorListener(CellEditorListener l) {
listenerList.add(CellEditorListener.class, l);
}
#Override public void removeCellEditorListener(CellEditorListener l) {
listenerList.remove(CellEditorListener.class, l);
}
public CellEditorListener[] getCellEditorListeners() {
return listenerList.getListeners(CellEditorListener.class);
}
protected void fireEditingStopped() {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for(int i = listeners.length-2; i>=0; i-=2) {
if(listeners[i]==CellEditorListener.class) {
// Lazily create the event:
if(changeEvent == null) changeEvent = new ChangeEvent(this);
((CellEditorListener)listeners[i+1]).editingStopped(changeEvent);
}
}
}
protected void fireEditingCanceled() {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
// Process the listeners last to first, notifying
// those that are interested in this event
for(int i = listeners.length-2; i>=0; i-=2) {
if(listeners[i]==CellEditorListener.class) {
// Lazily create the event:
if(changeEvent == null) changeEvent = new ChangeEvent(this);
((CellEditorListener)listeners[i+1]).editingCanceled(changeEvent);
}
}
}
}