Changing Columns in JTable using JRadioButtons doesn't refresh structure - java

I've removed most of my GUI to keep the code short.
I have a buttongroup of 3 JRadioButtons to select the table schema i want to display in my JTable, which is contained in a JScrollPane
I have tried to use fireTableStructureChanged() andfireTableDataChanged() as well as JTable.repaint() to no avail. Can anyone help me?
Here is a simple example that runs a window with my configuration but does not update the table.
public class test1 implements ActionListener {
private boolean payrollActive = false;
private JPanel mainPanel = new JPanel();
private JTable dataTable;
private Vector<String> courseColumns = new Vector<String>();
private Vector<String> courseColumnsPay = new Vector<String>();
private Vector<String> profsColumns = new Vector<String>();
private Vector<String> offSpaceColumns = new Vector<String>();
public test1() {
//Add columns for tables
String[] courseColsPay = {"Year", "Program", "Course", "Code", "CCCode",
"Weight", "Session", "Section", "Day", "STime", "FTime",
"BookedRM", "EnrolCap", "Description", "ProfFName",
"ProfLName", "ProfEmail", "Notes", "Syllabus", "Exam",
"CrossList", "PreReqs", "EnrolCtrls", "Shared",
"TrackChanges", "Address", "WageType", "BasePay",
"BenefitRate", "Budgeted", "PayAmount",
"MthAmount", "Term", "AccNumber", "PayAdmin", "PayableTo"};
for (String col : courseColsPay) {
courseColumnsPay.add(col);
}
for (int i = 0; i < 25; i++) {
courseColumns.add(courseColsPay[i]);
}
String[] profCols = {"FName", "LName", "Email", "UTEmail", "Birthdate",
"OfficeBC", "OfficeRM", "Department", "Status",
"Fellowship", "OfficeStat", "PhoneNum", "HomeAddr",
"HomePhoneNum", "Notes"};
for (String col : profCols) {
profsColumns.add(col);
}
String[] offSpaceCols = {"Building", "DeptID", "DivisionName", "BldgID", "RoomID",
"Category", "Description", "ShareType", "DeptName",
"Status", "SharePerc", "ShareOccupancy", "Area",
"Fellow", "Commments", "Name", "Position",
"Dept", "FTE", "CrossApp", "CrossPos", "CrossDept",
"CrossFTE", "OtherOffice"};
for (String col : offSpaceCols) {
offSpaceColumns.add(col);
}
mainPanel.setSize(1260, 630);
mainPanel.setLayout(null);
JRadioButton coursesBtn = new JRadioButton("Courses");
coursesBtn.setMnemonic(KeyEvent.VK_C);
coursesBtn.setActionCommand("Course");
coursesBtn.setSelected(true);
coursesBtn.addActionListener(this);
JRadioButton profsBtn = new JRadioButton("Professors");
profsBtn.setMnemonic(KeyEvent.VK_P);
profsBtn.setActionCommand("Professors");
coursesBtn.addActionListener(this);
JRadioButton officeSpBtn = new JRadioButton("Office Spaces");
officeSpBtn.setMnemonic(KeyEvent.VK_O);
officeSpBtn.setActionCommand("Office Spaces");
coursesBtn.addActionListener(this);
ButtonGroup tablesBtns = new ButtonGroup();
tablesBtns.add(coursesBtn);
tablesBtns.add(profsBtn);
tablesBtns.add(officeSpBtn);
JPanel tableRadioPanel = new JPanel(new GridLayout(0, 1));
tableRadioPanel.setOpaque(true);
tableRadioPanel.setBounds(0, 0, 150, 70);
tableRadioPanel.add(coursesBtn);
tableRadioPanel.add(profsBtn);
tableRadioPanel.add(officeSpBtn);
//table start
DefaultTableModel coursesModel = new DefaultTableModel(courseColumns, 200);
dataTable = new JTable(coursesModel);
dataTable.setFillsViewportHeight(true);
dataTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane scrollPane = new JScrollPane(dataTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(160, 0, 1016, 558);
//table code end
mainPanel.add(tableRadioPanel);
mainPanel.add(scrollPane);
}
public JComponent getMainPanel() {
return mainPanel;
}
public JTable getDataTable() {
return dataTable;
}
/**
* Returns the list of columns for the given table
* #param identifier the name of the table
* #return a Vector<String> of column names
*/
public Vector<String> getColumns(String identifier) {
switch (identifier) {
case "Courses":
if (payrollActive) {
return courseColumnsPay;
} else {
return courseColumns;
}
case "Professors":
return profsColumns;
case "Office Spaces":
return offSpaceColumns;
default:
return null;
}
}
public static void createAndShowGui() {
test1 vicu = new test1();
JFrame frame = new JFrame("Victoria University Database Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1260, 630);
frame.setLocationRelativeTo(null);
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(175, 100));
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
frame.getContentPane().add(vicu.getMainPanel());
frame.getContentPane().setLayout(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
JRadioButton targetBtn = (JRadioButton) e.getSource();
((DefaultTableModel) dataTable.getModel()).
setColumnIdentifiers(getColumns(targetBtn.getText()));
}
}

In your example, you are not registering an ActionListener to profsBtn or officeSpBtn, you keep registering to coursesBtn
JRadioButton coursesBtn = new JRadioButton("Courses");
//...
coursesBtn.addActionListener(this);
JRadioButton profsBtn = new JRadioButton("Professors");
//...
coursesBtn.addActionListener(this);
JRadioButton officeSpBtn = new JRadioButton("Office Spaces");
//...
coursesBtn.addActionListener(this);
Once I register the ActionListener to the correct buttons, it works fine

The problem seems to be that the code adds the listener 3 times to a single button, rather than once each to each of the 3 buttons!
..my application is for a very limited scope and can do without a layout manager for my purposes, unless you think this is affecting the table's behaviour?
No, not the table. It was however causing the emptyLabel to be assigned no space in the layout. Here is a robust, resizable version of the GUI.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
import java.util.*;
public class test1 implements ActionListener {
private boolean payrollActive = false;
private JPanel mainPanel = new JPanel(new BorderLayout(5,5));
private JTable dataTable;
private Vector<String> courseColumns = new Vector<String>();
private Vector<String> courseColumnsPay = new Vector<String>();
private Vector<String> profsColumns = new Vector<String>();
private Vector<String> offSpaceColumns = new Vector<String>();
public test1() {
mainPanel.setBorder(new EmptyBorder(5,5,5,5));
//Add columns for tables
String[] courseColsPay = {"Year", "Program", "Course", "Code", "CCCode",
"Weight", "Session", "Section", "Day", "STime", "FTime",
"BookedRM", "EnrolCap", "Description", "ProfFName",
"ProfLName", "ProfEmail", "Notes", "Syllabus", "Exam",
"CrossList", "PreReqs", "EnrolCtrls", "Shared",
"TrackChanges", "Address", "WageType", "BasePay",
"BenefitRate", "Budgeted", "PayAmount",
"MthAmount", "Term", "AccNumber", "PayAdmin", "PayableTo"};
for (String col : courseColsPay) {
courseColumnsPay.add(col);
}
for (int i = 0; i < 25; i++) {
courseColumns.add(courseColsPay[i]);
}
String[] profCols = {"FName", "LName", "Email", "UTEmail", "Birthdate",
"OfficeBC", "OfficeRM", "Department", "Status",
"Fellowship", "OfficeStat", "PhoneNum", "HomeAddr",
"HomePhoneNum", "Notes"};
for (String col : profCols) {
profsColumns.add(col);
}
String[] offSpaceCols = {"Building", "DeptID", "DivisionName", "BldgID", "RoomID",
"Category", "Description", "ShareType", "DeptName",
"Status", "SharePerc", "ShareOccupancy", "Area",
"Fellow", "Commments", "Name", "Position",
"Dept", "FTE", "CrossApp", "CrossPos", "CrossDept",
"CrossFTE", "OtherOffice"};
for (String col : offSpaceCols) {
offSpaceColumns.add(col);
}
//mainPanel.setSize(1260, 630);
//mainPanel.setLayout(null);
JRadioButton coursesBtn = new JRadioButton("Courses");
coursesBtn.setMnemonic(KeyEvent.VK_C);
coursesBtn.setActionCommand("Course");
coursesBtn.setSelected(true);
coursesBtn.addActionListener(this);
JRadioButton profsBtn = new JRadioButton("Professors");
profsBtn.setMnemonic(KeyEvent.VK_P);
profsBtn.setActionCommand("Professors");
profsBtn.addActionListener(this);
JRadioButton officeSpBtn = new JRadioButton("Office Spaces");
officeSpBtn.setMnemonic(KeyEvent.VK_O);
officeSpBtn.setActionCommand("Office Spaces");
officeSpBtn.addActionListener(this);
ButtonGroup tablesBtns = new ButtonGroup();
tablesBtns.add(coursesBtn);
tablesBtns.add(profsBtn);
tablesBtns.add(officeSpBtn);
JPanel tableRadioPanel = new JPanel(new GridLayout(0, 1));
tableRadioPanel.add(coursesBtn);
tableRadioPanel.add(profsBtn);
tableRadioPanel.add(officeSpBtn);
//table start
DefaultTableModel coursesModel = new DefaultTableModel(courseColumns, 200);
dataTable = new JTable(coursesModel);
dataTable.setFillsViewportHeight(true);
dataTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
JScrollPane scrollPane = new JScrollPane(dataTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
//scrollPane.setBounds(160, 0, 1016, 558);
//table code end
JPanel gridConstrain = new JPanel();
gridConstrain.add(tableRadioPanel);
mainPanel.add(gridConstrain, BorderLayout.LINE_START);
mainPanel.add(scrollPane);
}
public JComponent getMainPanel() {
return mainPanel;
}
public JTable getDataTable() {
return dataTable;
}
/**
* Returns the list of columns for the given table
* #param identifier the name of the table
* #return a Vector<String> of column names
*/
public Vector<String> getColumns(String identifier) {
switch (identifier) {
case "Courses":
if (payrollActive) {
return courseColumnsPay;
} else {
return courseColumns;
}
case "Professors":
return profsColumns;
case "Office Spaces":
return offSpaceColumns;
default:
return null;
}
}
public static void createAndShowGui() {
test1 vicu = new test1();
JFrame frame = new JFrame("Victoria University Database Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
JLabel emptyLabel = new JLabel("Empty Label");
emptyLabel.setFont(emptyLabel.getFont().deriveFont(80f));
//emptyLabel.setPreferredSize(new Dimension(175, 100));
frame.getContentPane().add(emptyLabel, BorderLayout.PAGE_START);
frame.getContentPane().add(vicu.getMainPanel());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Event: " + e);
JRadioButton targetBtn = (JRadioButton) e.getSource();
((DefaultTableModel) dataTable.getModel()).
setColumnIdentifiers(getColumns(targetBtn.getText()));
}
}

Related

How do I add an ActionListener to a JCheckBox?

Problem
So my program takes in a .csv file and loads the data and displays it. When data is loaded in, it creates a new JCheckBox for every column header there is in the data. How do I add an ActionListener such that when the user ticks/unticks any of the boxes, it should do a certain function?
When data is loaded in, it updates the JPanel by the code:
public void updateChecklistPanel(){
checklistPanel.removeAll();
checklistPanel.setLayout(new GridLayout(currentData.getColumnNames().length, 1, 10, 0));
for (String columnName : currentData.getColumnNames()){
JCheckBox checkBox = new JCheckBox();
checkBox.setText(columnName);
checklistPanel.add(checkBox);
}
checklistPanel.revalidate();
checklistPanel.repaint();
}
I also have the following at the bottom:
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == newDataFrameItem){
newFile();
System.out.println("New DataFrame Loaded in");
}
if (e.getSource() == loadDataFrameItem){
loadFile();
System.out.println(".csv Data loaded into DataFrame.");
}
if (e.getSource() == saveDataFrameItem){
System.out.println("Saved the data to a .csv file");
}
}
What I'm trying to do is that when a checkbox is unticked, it should hide a column in the JTable and when ticked, it should redisplay the column.
Current Solution
The solution that I have come up with is to make a variable allColumnHeaders that is an ArrayList of Strings. I then also have a variable shownColumnHeaders that is an ArrayList of Booleans. When the user wants to show/hide a column, the showColumn(String columnName) and hideColumn(String columnName) function finds the index of the column Name in allColumnHeaders and sets the Boolean value of the index in shownColumnHeaders to either true/false.
It the proceeds to create a new table model where the columns are only added if the Boolean value for that column is true. It will then set the model for the table to the new table model.
The code for the following is show below:
import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class MRE extends JPanel {
private static JTable table;
private static ArrayList<String> allColumnHeaders = new ArrayList<>();
private static ArrayList<Boolean> shownColumnHeaders = new ArrayList<>();
private static void createAndShowGUI()
{
table = new JTable(5, 7);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane( table );
JPanel buttons = new JPanel( new GridLayout(0, 1) );
for (int i = 0; i < table.getColumnCount(); i++) {
String column = table.getColumnName(i);
allColumnHeaders.add(column);
JCheckBox checkBox = new JCheckBox(column);
checkBox.addActionListener(event -> {
JCheckBox cb = (JCheckBox) event.getSource();
if (cb.isSelected()) {
System.out.println(checkBox.getText() + " is now being displayed");
showColumn(checkBox.getText());
} else {
System.out.println(checkBox.getText() + " is now being hidden");
hideColumn(checkBox.getText());
}
table.setModel(createTableModel());
});
checkBox.setSelected( true );
buttons.add( checkBox );
shownColumnHeaders.add(true);
}
JPanel wrapper = new JPanel();
wrapper.add( buttons );
JFrame frame = new JFrame("MRE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane, BorderLayout.CENTER);
frame.add(wrapper, BorderLayout.LINE_END);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static DefaultTableModel createTableModel(){
DefaultTableModel tableModel = new DefaultTableModel(0, 0);
String[] columnValues = new String[1];
for (int i = 0; i < shownColumnHeaders.size(); i++){
if (shownColumnHeaders.get(i)){
tableModel.addColumn(allColumnHeaders.get(i), columnValues);
}
}
return tableModel;
}
public static void showColumn(String columnName){
for (int i = 0; i < allColumnHeaders.size(); i++) {
if (allColumnHeaders.get(i).equals(columnName)){
shownColumnHeaders.set(i, true);
}
}
}
public static void hideColumn(String columnName){
for (int i = 0; i < allColumnHeaders.size(); i++) {
if (allColumnHeaders.get(i).equals(columnName)){
shownColumnHeaders.set(i, false);
}
}
}
public static void main(String[] args) throws Exception
{
SwingUtilities.invokeLater( () -> createAndShowGUI() );
}
}
Introduction
It took me a while, but I came up with the following JTable GUI. Here's the starting display.
Here's the GUI after I remove the item description.
Here's the GUI after I remove the item price.
Here's the GUI after I add the columns back.
Explanation
I created an Item class to hold one item.
I created an Inventory class to hold a List of Item instances and a String array of the column headers.
I created the JFrame and two JPanels. One JPanel holds the JTable and the other holds the JCheckBoxes. I used Swing layout managers to create the JPanels.
So far, so basic. Creating the JTable took a bit of effort. I wanted to display the item price as currency, but that wasn't important for this example GUI.
I created an ActionListener to add and remove columns from the JTable. I had to experiment a bit. The TableColumnModel addColumn method appends the column to the table.
I had to create a DisplayTableColumn class to hold a TableColumn and a boolean that tells me whether or not to display the TableColumn. I wound up removing all the columns from the JTable and adding all the columns back to the JTable so that I could maintain the column sequence. I probably ran 100 tests before I could get this code to work.
Code
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
public class JCheckBoxTableGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new JCheckBoxTableGUI());
}
private final Inventory inventory;
private final InventoryTableModel tableModel;
private JFrame frame;
private JTable table;
public JCheckBoxTableGUI() {
this.tableModel = new InventoryTableModel();
this.inventory = new Inventory();
String[] columns = inventory.getTableHeader();
for (String column : columns) {
tableModel.addColumn(column);
}
List<Item> items = inventory.getInventory();
for (Item item : items) {
Object[] object = new Object[5];
object[0] = item.getItemNumber();
object[1] = item.getItemName();
object[2] = item.getItemDescription();
object[3] = item.getItemQuantity();
object[4] = item.getItemPrice();
tableModel.addRow(object);
}
}
#Override
public void run() {
frame = new JFrame("JCheckBox Table GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTablePanel(), BorderLayout.CENTER);
frame.add(createSelectionPanel(), BorderLayout.AFTER_LINE_ENDS);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createTablePanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
table = new JTable(tableModel);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.getColumnModel().getColumn(0).setPreferredWidth(100);
table.getColumnModel().getColumn(1).setPreferredWidth(150);
table.getColumnModel().getColumn(2).setPreferredWidth(150);
table.getColumnModel().getColumn(3).setPreferredWidth(100);
table.getColumnModel().getColumn(4).setPreferredWidth(100);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setPreferredSize(new Dimension(620, 300));
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
private JPanel createSelectionPanel() {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JPanel innerPanel = new JPanel(new GridLayout(0, 1, 5, 5));
ColumnListener listener = new ColumnListener(this);
String[] columns = inventory.getTableHeader();
for (String column : columns) {
JCheckBox checkBox = new JCheckBox("Display " + column);
checkBox.addActionListener(listener);
checkBox.setActionCommand(column);
checkBox.setSelected(true);
innerPanel.add(checkBox);
}
panel.add(innerPanel);
return panel;
}
public JTable getTable() {
return table;
}
public JFrame getFrame() {
return frame;
}
public class ColumnListener implements ActionListener {
private final JCheckBoxTableGUI frame;
private final List<DisplayTableColumn> displayColumns;
public ColumnListener(JCheckBoxTableGUI frame) {
this.frame = frame;
this.displayColumns = new ArrayList<>();
TableColumnModel tcm = frame.getTable().getColumnModel();
for (int index = 0; index < tcm.getColumnCount(); index++) {
TableColumn tc = tcm.getColumn(index);
displayColumns.add(new DisplayTableColumn(tc, true));
}
}
#Override
public void actionPerformed(ActionEvent event) {
JCheckBox checkBox = (JCheckBox) event.getSource();
String column = event.getActionCommand();
TableColumnModel tcm = frame.getTable().getColumnModel();
for (int index = 0; index < displayColumns.size(); index++) {
DisplayTableColumn dtc = displayColumns.get(index);
if (dtc.isShowTableColumn()) {
tcm.removeColumn(dtc.getTableColumn());
}
}
int columnIndex = getColumnIndex(column);
displayColumns.get(columnIndex).setShowTableColumn(
checkBox.isSelected());
for (int index = 0; index < displayColumns.size(); index++) {
DisplayTableColumn dtc = displayColumns.get(index);
if (dtc.isShowTableColumn()) {
tcm.addColumn(dtc.getTableColumn());
}
}
frame.getFrame().pack();
}
private int getColumnIndex(String column) {
for (int index = 0; index < displayColumns.size(); index++) {
DisplayTableColumn dtc = displayColumns.get(index);
if (column.equals(dtc.getTableColumn().getHeaderValue())) {
return index;
}
}
return -1;
}
}
public class DisplayTableColumn {
private boolean showTableColumn;
private final TableColumn tableColumn;
public DisplayTableColumn(TableColumn tableColumn, boolean showTableColumn) {
this.tableColumn = tableColumn;
this.showTableColumn = showTableColumn;
}
public boolean isShowTableColumn() {
return showTableColumn;
}
public void setShowTableColumn(boolean showTableColumn) {
this.showTableColumn = showTableColumn;
}
public TableColumn getTableColumn() {
return tableColumn;
}
}
public class InventoryTableModel extends DefaultTableModel {
private static final long serialVersionUID = 1L;
#Override
public Class<?> getColumnClass(int columnIndex) {
if (columnIndex <= 2) {
return String.class;
} else if (columnIndex == 3) {
return Integer.class;
} else {
return Integer.class;
}
}
}
public class Inventory {
private final List<Item> inventory;
private final String[] tableHeader;
public Inventory() {
this.tableHeader = new String[] { "Item Number", "Item Name",
"Item Description", "Item Quantity",
"Item Price" };
this.inventory = new ArrayList<>();
inventory.add(new Item("X101111", "Samsung Camera", " ", 20, 69.99));
inventory.add(new Item("X101112", "Samsung Monitor", " ", 10, 279.99));
inventory.add(new Item("X101113", "Samsung Smartphone", " ", 110, 599.99));
inventory.add(new Item("X101114", "Apple Watch", " ", 20, 1259.99));
inventory.add(new Item("X101115", "Sony Playstation 5", " ", 0, 399.99));
}
public String[] getTableHeader() {
return tableHeader;
}
public List<Item> getInventory() {
return inventory;
}
}
public class Item {
private int itemPrice;
private int itemQuantity;
private final String itemNumber;
private final String itemName;
private final String itemDescription;
public Item(String itemNumber, String itemName,
String itemDescription, int itemQuantity, double itemPrice) {
this.itemNumber = itemNumber;
this.itemName = itemName;
this.itemDescription = itemDescription;
this.itemQuantity = itemQuantity;
setItemPrice(itemPrice);
}
public int getItemPrice() {
return itemPrice;
}
public void setItemPrice(double itemPrice) {
this.itemPrice = (int) Math.round(itemPrice * 100.0);
}
public int getItemQuantity() {
return itemQuantity;
}
public void setItemQuantity(int itemQuantity) {
this.itemQuantity = itemQuantity;
}
public String getItemNumber() {
return itemNumber;
}
public String getItemName() {
return itemName;
}
public String getItemDescription() {
return itemDescription;
}
}
}
This only demonstrates how to create a basic MRE:
the csv file is irrelevant.
data in the model is irrelevant.
your loadFile, newFile and saveFile buttons are irrelevant.
the TableModel is irrelevant
Your question is about adding an ActionListener to dynamically created checkboxes based on the columns of the table.
So all you need is a table with some columns and the resulting checkboxes.
import java.awt.*;
import javax.swing.*;
public class MRE extends JPanel
{
private static void createAndShowGUI()
{
JTable table = new JTable(5, 7);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane( table );
JPanel buttons = new JPanel( new GridLayout(0, 1) );
for (int i = 0; i < table.getColumnCount(); i++)
{
String column = table.getColumnName(i);
JCheckBox checkBox = new JCheckBox("Display " + column);
checkBox.setSelected( true );
buttons.add( checkBox );
}
JPanel wrapper = new JPanel();
wrapper.add( buttons );
JFrame frame = new JFrame("MRE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane, BorderLayout.CENTER);
frame.add(wrapper, BorderLayout.LINE_END);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args) throws Exception
{
SwingUtilities.invokeLater( () -> createAndShowGUI() );
}
}
If you can modify this to demonstrate how to use your "reusable class" to manage column visibility, then I will update the above code to use my reusable class with 4 additional lines of code.
Edit:
Suggested improvements to your code:
Make the code reusable and self contained
Don't use static methods
Don't change the data.
Your original question was:
How do I add an ActionListener to a JCheckBox?
So to do that you need a class that:
implements an ActionListener
is self contained to implement the functionality you require.
So the basic structure could be like the following:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SomeFunction implements ActionListener
{
private JTable table;
public SomeFunction(JTable table)
{
this.table = table;
}
#Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() instanceof AbstractButton)
{
String command = e.getActionCommand();
AbstractButton button = (AbstractButton)e.getSource();
if (button.isSelected())
doSelected( command );
else
doUnselected( command );
}
}
private void doSelected(String command)
{
System.out.println(command + " selected");
}
private void doUnselected(String command)
{
System.out.println(command + " unselected");
}
private static void createAndShowGUI()
{
JTable table = new JTable(5, 7);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane( table );
JPanel buttons = new JPanel( new GridLayout(0, 1) );
SomeFunction listener = new SomeFunction( table ); // added
// TableColumnManager listener = new TableColumnManager(table, false);
// ColumnListener listener = new ColumnListener();
for (int i = 0; i < table.getColumnCount(); i++)
{
String column = table.getColumnName(i);
JCheckBox checkBox = new JCheckBox("Display " + column);
checkBox.setSelected( true );
checkBox.setActionCommand( column ); // added
checkBox.addActionListener( listener ); // added
buttons.add( checkBox );
}
JPanel wrapper = new JPanel();
wrapper.add( buttons );
JFrame frame = new JFrame("MRE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane, BorderLayout.CENTER);
frame.add(wrapper, BorderLayout.LINE_END);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args) throws Exception
{
SwingUtilities.invokeLater( () -> createAndShowGUI() );
}
}
Whatever your function does it only needs to know about the table it should act upon.
So try to restructure your code into a reusable class.
If you want to use Gilberts code, then you need to restructure the ColumnListener class into a separate reusable self contained class.
Finally you can also try my reusable class. Check out Table Column Manager for the class to download.
Whatever reusable class you decide to use, you will only need to change a single line of code from the above example (once your functionality is contained in a reusable class).
Note the static methods would not be part of the final class. They are only there so simplify testing and posting of an MRE in a single class file.
Hope this helps with future design considerations.

How to count data in jtable and show on the bottom of my gui

I have such an api. It shows JTable with 3 columns. I want that when I insert price and quantity to the jtable result will be seen on the bottom of my jframe. For example I insert data like on the picture and then get the result (2*5)+(2*5)=20. My result will be 20. And this result will be seen on the bottom of the gui window.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class Demo extends JFrame implements ActionListener{
private static void createAndShowUI() {
JFrame frame = new JFrame("Customer Main");
frame.getContentPane().add(new FuGui(), BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
class FuGui extends JPanel {
FuDisplayPanel displayPanel = new FuDisplayPanel();
FuButtonPanel buttonPanel = new FuButtonPanel();
FuInformationPanel informationPanel = new FuInformationPanel();
public FuGui() {
//JTextField textField;
//textField = new JTextField(20);
//textField.addActionListener(this);
JPanel bottomPanel = new JPanel();
bottomPanel.add(buttonPanel);
bottomPanel.add(Box.createHorizontalStrut(10));
bottomPanel.add(informationPanel);
setLayout(new BorderLayout());
add(displayPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.SOUTH);
buttonPanel.addInfoBtnAddActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = informationPanel.getName();
String price = informationPanel.getPrice();
String quantity = informationPanel.getQuantity();
displayPanel.addRow(name, price, quantity);
}
});
}
}
class FuDisplayPanel extends JPanel {
private String[] COLUMNS = {"Name", "Price", "Quantity"};
private DefaultTableModel model = new DefaultTableModel(COLUMNS, 1);
private JTable table = new JTable(model);
public FuDisplayPanel() {
setLayout(new BorderLayout());
add(new JScrollPane(table));
}
public void addRow(String name, String price, String quantity) {
Object[] row = new Object[3];
row[0] = name;
row[1] = price;
row[2] = quantity;
model.addRow(row);
}
}
class FuButtonPanel extends JPanel {
private JButton addInfoButton = new JButton("Add Information");
public FuButtonPanel() {
add(addInfoButton);
}
public void addInfoBtnAddActionListener(ActionListener listener) {
addInfoButton.addActionListener(listener);
}
}
class FuInformationPanel extends JPanel {
private JTextField nameField = new JTextField(10);
private JTextField priceField = new JTextField(10);
private JTextField quantityField = new JTextField(10);
public FuInformationPanel() {
add(new JLabel("Kwota:"));
add(nameField);
add(Box.createHorizontalStrut(10));
// add(new JLabel("Price:"));
// add(priceField);
//add(new JLabel("Quantity:"));
// add(quantityField);
}
public String getName() {
return nameField.getText();
}
public String getPrice() {
return priceField.getText();
}
public String getQuantity() {
return quantityField.getText();
}
}
update your addRow method in class FuDisplayPanel to return the total like this and
public int addRow(String name, String price, String quantity) {
Object[] row = new Object[3];
row[0] = name;
row[1] = price;
row[2] = quantity;
model.addRow(row);
int total = 0;
for (int count = 0; count < model.getRowCount(); count++){
price = model.getValueAt(count, 1).toString();
quantity = model.getValueAt(count, 2).toString();
if(price != null && !price.trim().equals("") && quantity != null && !quantity.trim().equals("")) {
total += Integer.parseInt(price) * Integer.parseInt(quantity);
}
}
return total;
}
public class FuButtonPanel extends JPanel {
private JButton addInfoButton = new JButton("Add Information");
public JLabel total = new JLabel("Total : ");
public FuButtonPanel() {
add(addInfoButton);
add(total);
}
public void addInfoBtnAddActionListener(ActionListener listener) {
addInfoButton.addActionListener(listener);
}
public void setTotal(int total) {
this.total.setText("Total : " + total);
}
}
and do this at FuGui.class
int total = displayPanel.addRow(name, price, quantity);
buttonPanel.setTotal(total);
Access the underlying data in the table via the model (Swing fundamental):
TableModel model = table.getModel();
Add a listener to the table model to do the automatic updates:
TableModelListener listener = new TableModelListener(tableChanged(TableModelEvent e) {
// update code here
}};
table.getModel().addTableModelListener(listener);

Changing only 1 JTable column renderer from default

Hello all i have the following situation, I want to set all columns in a JTable to be a specific renderer (centered) and I want the right most column to have a background color as yellow. I've tried with the following code:
public class LView extends JInternalFrame {
private static final long serialVersionUID = -4248667075312220111L;
private LModel model;
private JPanel mainPanel;
private JButton btnRefresh;
private JTable lTable;
private DefaultTableModel lTableModel;
private String [] columnNames = {"col1", "col2", "col3", "col4", "col5"};
public LView() {
super("L Title", true, true, true, true);
setSize(650,300);
mainPanel = new JPanel(new FlowLayout());
JPanel topPanel = new JPanel();
btnRefresh = new JButton("Refresh");
btnRefresh.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
try { model.refresh(); }
catch (Exception e) { model.logException(e); }
}
});
topPanel.add(btnRefresh);
lTableModel = new DefaultTableModel() {
private static final long serialVersionUID = 2130745775009581358L;
#Override
public boolean isCellEditable(int row, int col) {
return false;
}
};
for (String col : columnNames)
lTableModel.addColumn(col);
lTable = new JTable();
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment( SwingConstants.CENTER );
lTable.setDefaultRenderer(Object.class, centerRenderer);
DefaultTableCellRenderer estColumnRenderer = new DefaultTableCellRenderer();
estColumnRenderer.setBackground(java.awt.Color.YELLOW);
estColumnRenderer.setFont(new Font(null, Font.BOLD, 12));
estColumnRenderer.setHorizontalAlignment( SwingConstants.CENTER );
lTable.setModel(lTableModel);
lTable.getColumnModel().getColumn(columnNames.length-1).setCellRenderer(estColumnRenderer);
lTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
lTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
lTable.getColumn(columnNames[0]).setPreferredWidth(225);
JScrollPane scrollPane = new JScrollPane(lTable);
JPanel tablePanel = new JPanel();
tablePanel.add(scrollPane);
mainPanel.add(topPanel);
mainPanel.add(tablePanel);
add(mainPanel);
}
public LModel getModel() {
return model;
}
public void setModel(LModel model) {
this.model = model;
}
public void addData(List<Object []> dataList) throws Exception {
lTableModel.getDataVector().removeAllElements();
lTableModel.fireTableDataChanged();
for (Object [] data : dataList) {
lmeTableModel.addRow(new Object[] {data[0],
data[1],
data[2],
data[3],
data[4]});
}
lTable.setPreferredScrollableViewportSize(lTable.getPreferredSize());
lTable.setFillsViewportHeight(true);
lTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
lTableModel.fireTableStructureChanged();
}
}
It sets all the columns to the top "centerRenderer" but the last column is not altered in any way. Am I missing something? Thanks -
EDIT: full code

JTable : Complex Cell Renderer

There are a lot of time, that I'm trying to make the Cell Renderer in the JavaOne 2007's talk maked by Shanon Hickey, Romain Guy and Chris Campbell, in the pages 38 and 39 (that you can find here : http://docs.huihoo.com/javaone/2007/desktop/TS-3548.pdf).
I asked Romain Guy, and Chris campbell, but without success, they say that they cannot pulish the source code.
So, any one can, give an idea, or even a source code on how to make this complex cell renderer ?
I learned this slides of many times, they say :
1)Cell Renderer: Column Spanning
Viewport clips column contents
and
2) Viewport moves to
expose the right text
for each column
I don't understand that, please can you give more in depth explanations ?
Cheers
Windows 7
JDK 1.7.0_21
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class ComplexCellRendererTest {
private static boolean DEBUG = true;
private JRadioButton r1 = new JRadioButton("scrollRectToVisible");
private JRadioButton r2 = new JRadioButton("setViewPosition");
public JComponent makeUI() {
String[] columnNames = {"AAA", "BBB"};
Object[][] data = {
{new Test("1", "aaaaaaaaaaaaaaaaa\nbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"), "4"},
{new Test("2", "1234567890\nabcdefghijklmdopqrstuvwxyz"), "5"},
{new Test("3", "ccccccccccccccccccccccccccccccccccc\ndddddddddddd"), "6"},
};
DefaultTableModel model = new DefaultTableModel(data, columnNames) {
#Override public boolean isCellEditable(int row, int column) {
return false;
}
};
final JTable table = new JTable(model);
table.getTableHeader().setReorderingAllowed(false);
table.setRowSelectionAllowed(true);
table.setFillsViewportHeight(true);
table.setShowVerticalLines(false);
table.setIntercellSpacing(new Dimension(0,1));
table.setRowHeight(56);
for(int i=0; i<table.getColumnModel().getColumnCount(); i++) {
TableColumn c = table.getColumnModel().getColumn(i);
c.setCellRenderer(new ComplexCellRenderer());
c.setMinWidth(50);
}
ActionListener al = new ActionListener() {
#Override public void actionPerformed(ActionEvent e) {
DEBUG = (e.getSource()==r1);
table.repaint();
}
};
Box box = Box.createHorizontalBox();
ButtonGroup bg = new ButtonGroup();
box.add(r1); bg.add(r1); r1.addActionListener(al);
box.add(r2); bg.add(r2); r2.addActionListener(al);
r1.setSelected(true);
JPanel p = new JPanel(new BorderLayout());
p.add(box, BorderLayout.NORTH);
p.add(new JScrollPane(table));
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new ComplexCellRendererTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
static class ComplexCellRenderer extends JPanel implements TableCellRenderer {
private final JTextArea textArea = new JTextArea(2, 999999);
private final JLabel label = new JLabel();
private final JScrollPane scroll = new JScrollPane();
public ComplexCellRenderer() {
super(new BorderLayout(0,0));
scroll.setViewportView(textArea);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scroll.setBorder(BorderFactory.createEmptyBorder());
scroll.setViewportBorder(BorderFactory.createEmptyBorder());
scroll.setOpaque(false);
scroll.getViewport().setOpaque(false);
textArea.setBorder(BorderFactory.createEmptyBorder());
//textArea.setMargin(new Insets(0,0,0,0));
textArea.setForeground(Color.RED);
textArea.setOpaque(false);
label.setBorder(BorderFactory.createMatteBorder(0,0,1,1,Color.GRAY));
setBackground(Color.WHITE);
setOpaque(true);
add(label, BorderLayout.NORTH);
add(scroll);
}
#Override public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
Test test;
if(value instanceof Test) {
test = (Test)value;
} else {
String title = value.toString();
Test t = (Test)table.getModel().getValueAt(row, 0);
test = new Test(title, t.text);
}
label.setText(test.title);
textArea.setText(test.text);
Rectangle cr = table.getCellRect(row, column, false);
if(DEBUG) {
//Unexplained flickering on first row?
textArea.scrollRectToVisible(cr);
} else {
//Work fine for me (JDK 1.7.0_21, Windows 7 64bit):
scroll.getViewport().setViewPosition(cr.getLocation());
}
if(isSelected) {
setBackground(Color.ORANGE);
} else {
setBackground(Color.WHITE);
}
return this;
}
}
}
class Test {
public final String title;
public final String text;
//public final Icon icon;
public Test(String title, String text) {
this.title = title;
this.text = text;
}
}

updating JTable date

For initialization:
Vector<Vector> rowdata = new Vector<Vector>();
Vector columnname = new Vector();
JTabel result = new JTable(rowdata, columnname);
JScrollPane sqlresult = new JScrollPane(result);
In the later part, I assign values in rowdata and columnname vector. How to show new values in JTable on GUI?
In addition..
result.repaint();
..and..
((DefaultTableModel)result.getModel()).fireTabelDataChanged()
..seem to do nothing.
1) use DefaultTableModel for JTable
2) define Column Class
3) add row(s) DefaultTableModel.addRow(myVector);
for example
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
public class DefaultTableModelDemo {
public static final String[] COLUMN_NAMES = {
"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"
};
private DefaultTableModel model = new DefaultTableModel(COLUMN_NAMES, 0);
private JTable table = new JTable(model);
private JPanel mainPanel = new JPanel(new BorderLayout());
private Random random = new Random();
public DefaultTableModelDemo() {
JButton addDataButton = new JButton("Add Data");
JPanel buttonPanel = new JPanel();
buttonPanel.add(addDataButton);
addDataButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
addDataActionPerformed();
}
});
model = new DefaultTableModel(COLUMN_NAMES, 0) {
private static final long serialVersionUID = 1L;
#Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
table = new JTable(model) {
private static final long serialVersionUID = 1L;
#Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component c = super.prepareRenderer(renderer, row, column);
if (isRowSelected(row) && isColumnSelected(column)) {
((JComponent) c).setBorder(new LineBorder(Color.red));
}
return c;
}
};
mainPanel.add(new JScrollPane(table), BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
}
private void addDataActionPerformed() {
for (int i = 0; i < 5; i++) {
Object[] row = new Object[COLUMN_NAMES.length];
for (int j = 0; j < row.length; j++) {
row[j] = random.nextInt(5);
}
model.addRow(row);
}
}
public JComponent getComponent() {
return mainPanel;
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("DefaultTableModelDemo");
frame.getContentPane().add(new DefaultTableModelDemo().getComponent());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
rowdata and columnname are used for the initialization of JTable, after the component JTable exists you need to use JTable.getColumnModel() and JTable.getModel() to add columns or rows.
Or JTable.addColumn(TableColumn aColumn) if you only wants to add a column.
Look here if you want to know how to add a row following an example.

Categories