I need to display JList with custom JPanel components called Item. These components have unique identification name. They may be dynamically added to the JList, or just updated (if already exist). I try the following implementation, but it produces just an empty JList. Please advise.
class Item extends JPanel {
JLabel name = new JLabel(" ");
JLabel col1 = new JLabel(" ");
JLabel col2 = new JLabel(" ");
Item(){
setMinimumSize(new Dimension(100, 20));
setLayout(new BorderLayout());
add(name, BorderLayout.WEST);
add(col1, BorderLayout.CENTER);
add(col2, BorderLayout.EAST);
}
}
public class Test_List extends JFrame {
private final JList list = new JList(new Item[0]);
HashMap<String, Item> map = new HashMap<String, Item>();
Test_List(){
setTitle("Test JList");
setLayout(new BorderLayout());
add(new JScrollPane(list), BorderLayout.CENTER);
pack();
}
public void update_item(String name, String s1, String s2){
Item item = map.get(name);
if (item == null){ // add new
item = new Item();
item.name.setText(name);
map.put(name, item);
list.add(item);
}
item.col1.setText(s1);
item.col2.setText(s2);
}
public static void main(String s[]) {
final Test_List frame = new Test_List();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
frame.setVisible(true);
}
});
frame.update_item("A", "a", "aa"); // add new item
frame.update_item("B", "b", "bb"); // add new item
frame.update_item("A", "aa", "a"); // update existing item
}
}
A model is responsible for modeling data, it should NEVER contain UI specific information, as the model shouldn't care how it is to be displayed, it is responsible for transforming the data so it confirms to the view/model contract, in this case the ListModel contract.
Start by taking a look at Writing a Custom Cell Renderer
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
public class TestListCellRenderer {
public static void main(String[] args) {
new TestListCellRenderer();
}
public TestListCellRenderer() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
DefaultListModel model = new DefaultListModel();
model.addElement(new Item("A", "a", "aa"));
model.addElement(new Item("B", "b", "bb"));
model.addElement(new Item("C", "c", "cc"));
model.addElement(new Item("D", "d", "dd"));
JList list = new JList(model);
list.setCellRenderer(new ItemCellRenderer());
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(list));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class Item {
private String name;
private String col1;
private String col2;
public Item(String name, String col1, String col2) {
this.name = name;
this.col1 = col1;
this.col2 = col2;
}
public String getCol1() {
return col1;
}
public String getCol2() {
return col2;
}
public String getName() {
return name;
}
}
public static class ItemCellRenderer extends JPanel implements ListCellRenderer<Item>{
private static final Border SAFE_NO_FOCUS_BORDER = new EmptyBorder(1, 1, 1, 1);
private static final Border DEFAULT_NO_FOCUS_BORDER = new EmptyBorder(1, 1, 1, 1);
protected static Border noFocusBorder = DEFAULT_NO_FOCUS_BORDER;
JLabel name = new JLabel(" ");
JLabel col1 = new JLabel(" ");
JLabel col2 = new JLabel(" ");
public ItemCellRenderer() {
setLayout(new BorderLayout());
add(name, BorderLayout.WEST);
add(col1, BorderLayout.CENTER);
add(col2, BorderLayout.EAST);
}
#Override
public Dimension getMinimumSize() {
return new Dimension(100, 20);
}
#Override
public Dimension getPreferredSize() {
return getMinimumSize();
}
protected Border getNoFocusBorder() {
Border border = UIManager.getBorder("List.cellNoFocusBorder");
if (System.getSecurityManager() != null) {
if (border != null) return border;
return SAFE_NO_FOCUS_BORDER;
} else {
if (border != null &&
(noFocusBorder == null ||
noFocusBorder == DEFAULT_NO_FOCUS_BORDER)) {
return border;
}
return noFocusBorder;
}
}
#Override
public Component getListCellRendererComponent(JList<? extends Item> list, Item value, int index, boolean isSelected, boolean cellHasFocus) {
setComponentOrientation(list.getComponentOrientation());
Color bg = null;
Color fg = null;
JList.DropLocation dropLocation = list.getDropLocation();
if (dropLocation != null
&& !dropLocation.isInsert()
&& dropLocation.getIndex() == index) {
bg = UIManager.getColor("List.dropCellBackground");
fg = UIManager.getColor("List.dropCellForeground");
isSelected = true;
}
if (isSelected) {
setBackground(bg == null ? list.getSelectionBackground() : bg);
setForeground(fg == null ? list.getSelectionForeground() : fg);
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
name.setText(value.getName());
col1.setText(value.getCol1());
col2.setText(value.getCol2());
name.setForeground(getForeground());
col1.setForeground(getForeground());
col2.setForeground(getForeground());
setEnabled(list.isEnabled());
name.setFont(list.getFont());
col1.setFont(list.getFont());
col2.setFont(list.getFont());
Border border = null;
if (cellHasFocus) {
if (isSelected) {
border = UIManager.getBorder("List.focusSelectedCellHighlightBorder");
}
if (border == null) {
border = UIManager.getBorder("List.focusCellHighlightBorder");
}
} else {
border = getNoFocusBorder();
}
setBorder(border);
return this;
}
}
}
Having said all that, I think you would be better off with a using a JTable, see How to Use Tables
Related
how to create jcomboBox with two /multiple columns in the drop down let but when we select only one selected value show in Jcombobox
please give me any solution for this .
You might be able to use JList#setLayoutOrientation(JList.VERTICAL_WRAP):
import java.awt.*;
import javax.accessibility.Accessible;
import javax.swing.*;
import javax.swing.plaf.basic.ComboPopup;
public class TwoColumnsDropdownTest {
private Component makeUI() {
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>();
model.addElement("111");
model.addElement("2222");
model.addElement("3");
model.addElement("44444");
model.addElement("55555");
model.addElement("66");
model.addElement("777");
model.addElement("8");
model.addElement("9999");
int rowCount = (model.getSize() + 1) / 2;
JComboBox<String> combo = new JComboBox<String>(model) {
#Override public Dimension getPreferredSize() {
Insets i = getInsets();
Dimension d = super.getPreferredSize();
int w = Math.max(100, d.width);
int h = d.height;
int buttonWidth = 20; // ???
return new Dimension(buttonWidth + w + i.left + i.right, h + i.top + i.bottom);
}
#Override public void updateUI() {
super.updateUI();
setMaximumRowCount(rowCount);
setPrototypeDisplayValue("12345");
Accessible o = getAccessibleContext().getAccessibleChild(0);
if (o instanceof ComboPopup) {
JList<?> list = ((ComboPopup) o).getList();
list.setLayoutOrientation(JList.VERTICAL_WRAP);
list.setVisibleRowCount(rowCount);
list.setFixedCellWidth((getPreferredSize().width - 2) / 2);
}
}
};
JPanel p = new JPanel();
p.add(combo);
return p;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new TwoColumnsDropdownTest().makeUI());
frame.setSize(320, 240);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
You need to do a few things.
By default, what is displayed in the JComboBox, as the selected item, is the value returned by method toString of the items in the ComboBoxModel. Based on your comment I wrote an Item class and overrode the toString method.
In order to display something different in the drop-down list, you need a custom ListCellRenderer.
In order for the drop-down list to display the entire details of each item, the drop-down list needs to be wider than the JComboBox. I used code from the following SO question to achieve that:
How can I change the width of a JComboBox dropdown list?
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Point;
import java.math.BigDecimal;
import java.text.NumberFormat;
import javax.accessibility.Accessible;
import javax.accessibility.AccessibleContext;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.plaf.basic.BasicComboPopup;
public class MultiColumnCombo implements PopupMenuListener {
private JComboBox<Item> combo;
public void popupMenuCanceled(PopupMenuEvent event) {
// Do nothing.
}
public void popupMenuWillBecomeInvisible(PopupMenuEvent event) {
// Do nothing.
}
public void popupMenuWillBecomeVisible(PopupMenuEvent event) {
AccessibleContext comboAccessibleContext = combo.getAccessibleContext();
int comboAccessibleChildrenCount = comboAccessibleContext.getAccessibleChildrenCount();
if (comboAccessibleChildrenCount > 0) {
Accessible comboAccessibleChild0 = comboAccessibleContext.getAccessibleChild(0);
if (comboAccessibleChild0 instanceof BasicComboPopup) {
EventQueue.invokeLater(() -> {
BasicComboPopup comboPopup = (BasicComboPopup) comboAccessibleChild0;
JScrollPane scrollPane = (JScrollPane) comboPopup.getComponent(0);
Dimension d = setCurrentDimension(scrollPane.getPreferredSize());
scrollPane.setPreferredSize(d);
scrollPane.setMaximumSize(d);
scrollPane.setMinimumSize(d);
scrollPane.setSize(d);
Point location = combo.getLocationOnScreen();
int height = combo.getPreferredSize().height;
comboPopup.setLocation(location.x, location.y + height - 1);
comboPopup.setLocation(location.x, location.y + height);
});
}
}
}
private void createAndDisplayGui() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createCombo());
frame.setSize(450, 300);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createCombo() {
JPanel panel = new JPanel();
Item[] items = new Item[]{new Item("A", "Item A", new BigDecimal(1.99d), new BigDecimal(2.99d)),
new Item("B", "Item B", new BigDecimal(7.5d), new BigDecimal(9.0d)),
new Item("C", "Item C", new BigDecimal(0.25d), new BigDecimal(3.15d))};
combo = new JComboBox<>(items);
AccessibleContext comboAccessibleContext = combo.getAccessibleContext();
int comboAccessibleChildrenCount = comboAccessibleContext.getAccessibleChildrenCount();
if (comboAccessibleChildrenCount > 0) {
Accessible comboAccessibleChild0 = comboAccessibleContext.getAccessibleChild(0);
if (comboAccessibleChild0 instanceof BasicComboPopup) {
BasicComboPopup comboPopup = (BasicComboPopup) comboAccessibleChild0;
comboPopup.getList().setCellRenderer(new MultiColumnRenderer());
}
}
combo.addPopupMenuListener(this);
panel.add(combo);
return panel;
}
private Dimension setCurrentDimension(Dimension dim) {
Dimension d = new Dimension(dim);
d.width = 120;
return d;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new MultiColumnCombo().createAndDisplayGui());
}
}
class Item {
private String code;
private String name;
private BigDecimal price;
private BigDecimal salePrice;
public Item(String code, String name, BigDecimal price, BigDecimal salePrice) {
this.code = code;
this.name = name;
this.price = price;
this.salePrice = salePrice;
}
public String displayString() {
return String.format("%s %s %s %s",
code,
name,
NumberFormat.getCurrencyInstance().format(price),
NumberFormat.getCurrencyInstance().format(salePrice));
}
public String toString() {
return name;
}
}
class MultiColumnRenderer implements ListCellRenderer<Object> {
/** Component returned by method {#link #getListCellRendererComponent}. */
private JLabel cmpt;
public MultiColumnRenderer() {
cmpt = new JLabel();
cmpt.setOpaque(true);
cmpt.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
}
public Component getListCellRendererComponent(JList<? extends Object> list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus) {
String text;
if (value == null) {
text = "";
}
else {
if (value instanceof Item) {
text = ((Item) value).displayString();
}
else {
text = value.toString();
}
}
cmpt.setText(text);
if (isSelected) {
cmpt.setBackground(list.getSelectionBackground());
cmpt.setForeground(list.getSelectionForeground());
}
else {
cmpt.setBackground(list.getBackground());
cmpt.setForeground(list.getForeground());
}
cmpt.setFont(list.getFont());
return cmpt;
}
}
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.
I have a textbox with search button, if i click on search text, String gets highlighted in JTable cells, if the search text is having multiple Strings with comma separated, all those comma separated Strings has to be displayed in a different colors dynamically.
Can you please suggest what changes i need to do to the below working code(single String highlight)
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.text.DefaultHighlighter;
import java.awt.*;
public class TableExample {
JFrame f;
private JTextField textField;
TableExample() {
f = new JFrame();
String data[][] = {{"101", "lala", "670000"}, {"101", "lala", "670000"}, {"102", "Jai", "780000"},
{"101", "Sachin", "700000"}};
String column[] = {"ID", "NAME", "SALARY"};
JTable jt = new JTable();
jt.setBounds(30, 40, 200, 300);
JScrollPane sp = new JScrollPane(jt);
DefaultTableModel dtm = new DefaultTableModel(data, column);
dtm.setColumnIdentifiers(column);
jt.setModel(dtm);
JPanel inputpanel = new JPanel();
inputpanel.setLayout(new BoxLayout(inputpanel, BoxLayout.LINE_AXIS));
textField = new JTextField();
JButton button = new JButton("Highlight");
button.addActionListener(e -> {
jt.repaint();
});
inputpanel.add(textField);
inputpanel.add(button);
jt.setDefaultRenderer(Object.class, new CellHighlightRenderer());
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, inputpanel, sp);
f.add(splitPane);
f.setSize(300, 400);
}
class CellHighlightRenderer extends JTextField implements TableCellRenderer {
public DefaultHighlighter high = new DefaultHighlighter();
public DefaultHighlighter.DefaultHighlightPainter highlight_painter = new DefaultHighlighter.DefaultHighlightPainter(
Color.YELLOW);
public CellHighlightRenderer() {
setBorder(BorderFactory.createEmptyBorder());
setHighlighter(high);
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
setForeground(isSelected ? table.getSelectionForeground() : table.getForeground());
setFont(table.getFont());
setValue(value);
int pos = 0;
String pattern = textField.getText(); // Grab the text.
if (pattern != null && pattern.trim().length() > 0)
while ((pos = value.toString().indexOf(pattern, pos)) >= 0) {
try {
high.addHighlight(pos, pos + pattern.length(), highlight_painter);
pos += pattern.length();
} catch (Exception e) {
e.printStackTrace();
}
}
return this;
}
protected void setValue(Object value) {
setText((value == null) ? "" : value.toString());
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(()->{
TableExample te = new TableExample();
te.f.setVisible(true);
});
}
}
I have done what i think you asked. Read commends inside the code. Whenever u see a comment, try to compare it with your code. I didnt know what colors you want so i have done with random color to each word.
Preview:
package test;
import java.awt.Color;
import java.awt.Component;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.text.DefaultHighlighter;
public class TableExample {
JFrame f;
private JTextField textField; // make the textfield a field so u can grab its text whenever u need it (in our
// case in renderer)
private HashMap<String, Color> words = new HashMap<>();
TableExample() {
f = new JFrame();
// I changed the data a bit for my tests, take care of that.
String data[][] = { { "101", "lala", "670000" }, { "101", "lala", "670000" }, { "102", "Jai", "780000" },
{ "101", "Sachin", "700000" } };
String column[] = { "ID", "NAME", "SALARY" };
JTable jt = new JTable();
jt.setBounds(30, 40, 200, 300);
JScrollPane sp = new JScrollPane(jt); // You were not adding the sp into your panel, take care that next time.
DefaultTableModel dtm = new DefaultTableModel(data, column); // Create the model with our data.
dtm.setColumnIdentifiers(column);
jt.setModel(dtm);
JPanel inputpanel = new JPanel();
inputpanel.setLayout(new BoxLayout(inputpanel, BoxLayout.LINE_AXIS));
textField = new JTextField();
JButton button = new JButton("Highlight");
button.addActionListener(e -> { // Button should only repaint the table (a.k.a read the renderer again).
words.clear(); //Clear the map with the words
String text = textField.getText(); // Grab the text.
if (text.trim().length() > 0) {
String[] splitPattern = text.split(","); //Split the words
for (String s : splitPattern) {
words.put(s, getARandomColor()); //Put each word with a RANDOM color.
}
}
jt.repaint();// Changing the table's renderer is bad on every button click, and no needed.
});
inputpanel.add(textField);
inputpanel.add(button);
jt.setDefaultRenderer(Object.class, new CellHighlightRenderer()); // Add the renderer only 1 time.
// I add sp here, not the table (if you want your table to actually have a
// scrollpane)
JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, inputpanel, sp);
f.add(splitPane);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Hopefully you didnt forget this.
f.setSize(300, 400);
f.pack(); // Use pack() to the frame between set it visible.
// f.setVisible(true); //setVisible to constructor is bad idea. I suggest you to
// avoid that, and show your frame after its initiation.
}
class CellHighlightRenderer extends JTextField implements TableCellRenderer {
public DefaultHighlighter high = new DefaultHighlighter();
public DefaultHighlighter.DefaultHighlightPainter highlight_painter = new DefaultHighlighter.DefaultHighlightPainter(
Color.YELLOW);
public CellHighlightRenderer() {
setBorder(BorderFactory.createEmptyBorder());
setHighlighter(high);
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
setForeground(isSelected ? table.getSelectionForeground() : table.getForeground());
setFont(table.getFont());
setValue(value);
int pos = 0;
if (words.size() > 0) {
for (String word : words.keySet()) {
while ((pos = value.toString().indexOf(word, pos)) >= 0) {
try {
highlight_painter = new DefaultHighlighter.DefaultHighlightPainter(words.get(word));
// high.addHighlight(first, last, highlight_painter);
high.addHighlight(pos, pos + word.length(), highlight_painter);
pos += word.length();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return this;
}
protected void setValue(Object value) {
setText((value == null) ? "" : value.toString());
}
}
private Color getARandomColor() {
return new Color((int) (Math.random() * 255), (int) (Math.random() * 255), (int) (Math.random() * 255));
}
public static void main(String[] args) {
/* *******THIS IS VERY IMPORTANT******* */
/* All swing applications should run in their own thread, named EDT */
SwingUtilities.invokeLater(() -> {
TableExample te = new TableExample();
te.f.setVisible(true); // Here, make it visisble
});
}
}
I'm trying to bind a shortcut for JTable It's working fine for Alphabets but not for Keys like Insert,Delete,Space etc.
For Ex the below code is working for Ctrl+I or whatever alphabet but If I go for Ctrl+Insert it's not working why is that?
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.table.DefaultTableModel;
public class NewClass {
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewClass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(createTable()), BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static JTable createTable() {
DefaultTableModel tmodel = new DefaultTableModel(3, 5);
JTable table = new JTable(tmodel);
table.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_I, KeyEvent.CTRL_MASK), "Insert");
//Not working for VK_INSERT or VK_DELETE or VK_SPACE
table.getActionMap().put("Insert", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Insert Action");
}
});
return table;
}
}
Update 1
It's not working when using WHEN_IN_FOCUSED_WINDOW but working fine if I go for WHEN_FOCUSED or WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
required WHEN_ANCESTOR_OF_FOCUSED_COMPONENT as corect setting for focus (hidden behind JScrolPanes JViewport)
JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
The component contains (or is) the component that has the focus. This input map is commonly used for a composite component — a
component whose implementation depends on child components. For
example, JTables make all their bindings using
WHEN_ANCESTOR_OF_FOCUSED_COMPONENT so that if the user is editing, the
up-arrow key (for example) still changes the selected cell.
then all KeyEvent combinations from OPs question and comments works me correctly in Win7 / Win10, Java7 / Java8, from deleted post by MadProgrammer too ( users_rep > 10k )
AFAIK there is restiction, with numbers of modifiers, if is > 2, then CTRL + ALT + SHIFT + Whatever is possible to catch from AWTEventListener or from very complicated KeyListener
code for simulation in SSCCE /MCVE form
.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.table.DefaultTableModel;
public class NewClass {
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info
: javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException |
IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(
NewClass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.add(new JScrollPane(createTable()), BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static JTable createTable() {
DefaultTableModel tmodel = new DefaultTableModel(3, 5);
JTable table = new JTable(tmodel);
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, KeyEvent.CTRL_MASK), "Insert");
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, KeyEvent.CTRL_MASK), "Insert");
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, KeyEvent.CTRL_MASK), "Insert");
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke(KeyEvent.VK_I, KeyEvent.CTRL_MASK), "Insert");
table.getActionMap().put("Insert", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Action from JTable");
}
});
return table;
}
}
code made by Rob (camickr), print out the KeyBindings (sorry I haven't a link to his and Darryls code ...)
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
import javax.swing.filechooser.*;
public class KeyBindings implements ItemListener {
private static final String PACKAGE = "javax.swing.";
private static final String[] COLUMN_NAMES = {"Action", "When Focused",
"When In Focused Window", "When Ancestor"};
private static String selectedItem;
private JComponent contentPane;
private JMenuBar menuBar;
private JTable table;
private JComboBox comboBox;
private Hashtable<String, DefaultTableModel> models;
public KeyBindings() {
models = new Hashtable<String, DefaultTableModel>();
contentPane = new JPanel(new BorderLayout());
contentPane.add(buildNorthComponent(), BorderLayout.NORTH);
contentPane.add(buildCenterComponent(), BorderLayout.CENTER);
resetComponents();
}
public JComponent getContentPane() {
return contentPane;
}
public JMenuBar getMenuBar() {
if (menuBar == null) {
menuBar = createMenuBar();
}
return menuBar;
}
private JComponent buildNorthComponent() {
comboBox = new JComboBox();
JLabel label = new JLabel("Select Component:");
label.setDisplayedMnemonic('S');
label.setLabelFor(comboBox);
JPanel panel = new JPanel();
panel.setBorder(new EmptyBorder(15, 0, 15, 0));
panel.add(label);
panel.add(comboBox);
return panel;
}
private String checkForUIKey(String key) {
if (key.endsWith("UI") && key.indexOf(".") == -1) {
String componentName = key.substring(0, key.length() - 2);
if (componentName.equals("PopupMenuSeparator")
|| componentName.equals("ToolBarSeparator")
|| componentName.equals("DesktopIcon")) {
return null;
} else {
return componentName;
}
}
return null;
}
private JComponent buildCenterComponent() {
DefaultTableModel model = new DefaultTableModel(COLUMN_NAMES, 0);
table = new JTable(model) {
private static final long serialVersionUID = 1L;
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
table.setAutoCreateColumnsFromModel(false);
table.getColumnModel().getColumn(0).setPreferredWidth(200);
table.getColumnModel().getColumn(1).setPreferredWidth(200);
table.getColumnModel().getColumn(2).setPreferredWidth(200);
table.getColumnModel().getColumn(3).setPreferredWidth(200);
Dimension d = table.getPreferredSize();
d.height = 350;
table.setPreferredScrollableViewportSize(d);
table.getTableHeader().setFocusable(true);
return new JScrollPane(table);
}
public void resetComponents() {
models.clear();
Vector<String> comboBoxItems = new Vector<String>(50);
UIDefaults defaults = UIManager.getLookAndFeelDefaults();
for (Object key : defaults.keySet()) {
String componentName = checkForUIKey(key.toString());
if (componentName != null) {
comboBoxItems.add(componentName);
}
}
Collections.sort(comboBoxItems);
comboBox.removeItemListener(this);
comboBox.setModel(new DefaultComboBoxModel(comboBoxItems));
comboBox.setSelectedIndex(-1);
comboBox.addItemListener(this);
comboBox.requestFocusInWindow();
if (selectedItem != null) {
comboBox.setSelectedItem(selectedItem);
}
}
private JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
menuBar.add(createFileMenu());
menuBar.add(createLAFMenu());
return menuBar;
}
private JMenu createFileMenu() {
JMenu menu = new JMenu("Application");
menu.setMnemonic('A');
menu.addSeparator();
menu.add(new ExitAction());
return menu;
}
private JMenu createLAFMenu() {
ButtonGroup bg = new ButtonGroup();
JMenu menu = new JMenu("Look & Feel");
menu.setMnemonic('L');
String lafId = UIManager.getLookAndFeel().getID();
UIManager.LookAndFeelInfo[] lafInfo = UIManager.getInstalledLookAndFeels();
for (int i = 0; i < lafInfo.length; i++) {
String laf = lafInfo[i].getClassName();
String name = lafInfo[i].getName();
Action action = new ChangeLookAndFeelAction(laf, name);
JRadioButtonMenuItem mi = new JRadioButtonMenuItem(action);
menu.add(mi);
bg.add(mi);
if (name.equals(lafId)) {
mi.setSelected(true);
}
}
return menu;
}
#Override
public void itemStateChanged(ItemEvent e) {
String componentName = (String) e.getItem();
changeTableModel(getClassName(componentName));
selectedItem = componentName;
}
private String getClassName(String componentName) {
if (componentName.equals("TableHeader")) {
return PACKAGE + "table.JTableHeader";
} else {
return PACKAGE + "J" + componentName;
}
}
private void changeTableModel(String className) {
DefaultTableModel model = models.get(className);
if (model != null) {
table.setModel(model);
return;
}
model = new DefaultTableModel(COLUMN_NAMES, 0);
table.setModel(model);
models.put(className, model);
JComponent component = null;
try {// Hack so I don't have to sign the jar file for usage in Java Webstart
if (className.endsWith("JFileChooser")) {
component = new JFileChooser(new DummyFileSystemView());
} else {
Object o = Class.forName(className).newInstance();
component = (JComponent) o;
}
} catch (Exception e) {
Object[] row = {e.toString(), "", "", ""};
model.addRow(row);
return;
}
ActionMap actionMap = component.getActionMap();
Object[] keys = actionMap.allKeys();
if (keys == null) {
Object[] row = {"No actions found", "", "", ""};
model.addRow(row);
return;
}
for (int i = 0; i < keys.length; i++) {
Object key = keys[i];
if (key instanceof String) {
continue;
} else {
keys[i] = "";
}
}
Arrays.sort(keys);
for (int i = 0; i < keys.length; i++) {
Object key = keys[i];
if (key != "") {
Object[] row = {key, "", "", ""};
model.addRow(row);
}
}
updateModelForInputMap(model, 1,
component.getInputMap(JComponent.WHEN_FOCUSED));
updateModelForInputMap(model, 2,
component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW));
updateModelForInputMap(model, 3,
component.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT));
}
private void updateModelForInputMap(TableModel model, int column, InputMap inputMap) {
if (inputMap == null) {
return;
}
KeyStroke[] keys = inputMap.allKeys();
if (keys == null) {
return;
}
Hashtable<Object, String> actions = new Hashtable<Object, String>(keys.length);
for (int i = 0; i < keys.length; i++) {
KeyStroke key = keys[i];
Object actionName = inputMap.get(key);
Object value = actions.get(actionName);
if (value == null) {
actions.put(actionName, key.toString().replace("pressed ", ""));
} else {
actions.put(actionName, value + ", " + key.toString().replace("pressed ", ""));
}
}
for (int i = 0; i < model.getRowCount(); i++) {
String o = actions.get(model.getValueAt(i, 0));
if (o != null) {
model.setValueAt(o.toString(), i, column);
}
}
}
class ChangeLookAndFeelAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private String laf;
protected ChangeLookAndFeelAction(String laf, String name) {
this.laf = laf;
putValue(Action.NAME, name);
putValue(Action.SHORT_DESCRIPTION, getValue(Action.NAME));
}
#Override
public void actionPerformed(ActionEvent e) {
try {
JMenuItem mi = (JMenuItem) e.getSource();
JPopupMenu popup = (JPopupMenu) mi.getParent();
JRootPane rootPane = SwingUtilities.getRootPane(popup.getInvoker());
Component c = rootPane.getContentPane().getComponent(0);
rootPane.getContentPane().remove(c);
UIManager.setLookAndFeel(laf);
KeyBindings bindings = new KeyBindings();
rootPane.getContentPane().add(bindings.getContentPane());
SwingUtilities.updateComponentTreeUI(rootPane);
rootPane.requestFocusInWindow();
} catch (Exception ex) {
System.out.println("Failed loading L&F: " + laf);
System.out.println(ex);
}
}
}
class ExitAction extends AbstractAction {
private static final long serialVersionUID = 1L;
public ExitAction() {
putValue(Action.NAME, "Exit");
putValue(Action.SHORT_DESCRIPTION, getValue(Action.NAME));
putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_X));
}
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
class DummyFileSystemView extends FileSystemView {
#Override
public File createNewFolder(File containingDir) {
return null;
}
#Override
public File getDefaultDirectory() {
return null;
}
#Override
public File getHomeDirectory() {
return null;
}
}
private static void createAndShowGUI() {
KeyBindings application = new KeyBindings();
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Key Bindings");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(application.getMenuBar());
frame.getContentPane().add(application.getContentPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
/*try {
SynthLookAndFeel laf = new SynthLookAndFeel();
UIManager.setLookAndFeel(laf);
KeyBindings bindings = new KeyBindings();
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(KeyBindings.class.getName()).log(Level.SEVERE, null, ex);
} */
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
without selection
Delete Action from JTable
Insert Action from JTable
Space Action from JTable
I Action from JTable
after cell is selected
Delete Action from JTable
Insert Action from JTable
Space Action from JTable
I Action from JTable
from code, for correctness is required (otherwise there is bunch of unfilteres events, but completed for testing purposes) to test for CTRL && Whatever is Pressed insideAWTEventListener
import java.awt.AWTEvent;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Toolkit;
import java.awt.event.AWTEventListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class NewClass {
private JFrame frame = new JFrame();
private DefaultTableModel tmodel = new DefaultTableModel(3, 5);
private JTable table = new JTable(tmodel);
public NewClass() {
frame.add(new JScrollPane(createTable()), BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocation(150, 150);
frame.setVisible(true);
Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
#Override
public void eventDispatched(AWTEvent event) {
if (event instanceof KeyEvent) {
KeyEvent ke = (KeyEvent) event;
Component comp = ke.getComponent();
if (comp instanceof JTable) {
System.out.println(comp);
} else if (comp instanceof JScrollPane) {
System.out.println(comp);
} else if (comp instanceof JViewport) {
System.out.println(comp);
} else if (comp instanceof JFrame) {
System.out.println(comp);
} else {
System.out.println(comp);
}
}
}
}, AWTEvent.KEY_EVENT_MASK);
}
public JTable createTable() {
table.setPreferredScrollableViewportSize(table.getPreferredSize());
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, KeyEvent.CTRL_MASK), "Delete");
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, KeyEvent.CTRL_MASK), "Insert");
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, KeyEvent.CTRL_MASK), "Space");
table.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(
KeyStroke.getKeyStroke(KeyEvent.VK_I, KeyEvent.CTRL_MASK), "I");
table.getActionMap().put("Delete", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Delete Action from JTable");
}
});
table.getActionMap().put("Insert", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Insert Action from JTable");
}
});
table.getActionMap().put("Space", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Space Action from JTable");
}
});
table.getActionMap().put("I", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("I Action from JTable");
}
});
return table;
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info
: javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Windows".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException |
IllegalAccessException |
javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(
NewClass.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new NewClass();
}
});
}
}
how can I refresh the highlighter in my JTable after changing the search value in the JTextField? It works fine with the JTextArea under the JTextfield, but I the JTable won't refresh the highlighter. Any Suggestions??
This is my Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.text.*;
import javax.swing.text.DefaultHighlighter.DefaultHighlightPainter;
public class BeispielTabelle {
JTextField field;
JTextArea textFeld = new JTextArea("Hello World!");
String input="Stefan";
//Titel der Tabelle
String[] title = {"EINS", "ZWEI", "DREI"};
//Tabellendaten
Object[][] playerdata = {
{"34", "Stefan", "Mein Name ist Stefan"},
{"32", "Dirk", "Ich bin der Dirk"},
{"99", "Patrick", "Ich heisse Patrick"},
{"100", "Anna", "Ich bin die Anna"},};
//TableModel
DefaultTableModel model = new DefaultTableModel(playerdata,title);
//Tabelle erstellen
JTable textTable = new JTable(model);
public JPanel erstelleTabelle() {
JPanel totalGUI = new JPanel();
//CellRenderer
SearchRenderer cellRenderer = new SearchRenderer();
//Spaltenbreiten festlegen
textTable.setDefaultRenderer(String.class, cellRenderer);
textTable.getColumnModel().getColumn(0).setCellRenderer(cellRenderer);
textTable.getColumnModel().getColumn(1).setCellRenderer(cellRenderer);
textTable.getColumnModel().getColumn(2).setCellRenderer(cellRenderer);
textTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); // Autoresizing abschalten, sonst sind alle Spalten gleich breit:
textTable.getColumnModel().getColumn(0).setPreferredWidth(60);
textTable.getColumnModel().getColumn(1).setPreferredWidth(60);
textTable.getColumnModel().getColumn(2).setPreferredWidth(180);
//das Ganze scrollbar machen
JScrollPane scrollPane = new JScrollPane(textTable);
//TextFeld erstellen
field = new JTextField();
field.addActionListener(new ActionListener () {
#Override
public void actionPerformed(ActionEvent e) {
input = field.getText();
System.out.println(input);
//updateRowHeights();
highlightText();
}
});
totalGUI.add(scrollPane);
totalGUI.add(field);
totalGUI.add(textFeld);
return totalGUI;
}
void highlightText() {
DefaultHighlightPainter yellowPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW);
Highlighter highlighter = textFeld.getHighlighter();
highlighter.removeAllHighlights();
String text = textFeld.getText();
String pattern = input;
int index = text.indexOf(pattern);
while ( index >= 0 ) {
int len = pattern.length();
try {
highlighter.addHighlight(index, index+len, yellowPainter);
} catch (BadLocationException e) {
e.printStackTrace();
}
index = text.indexOf(pattern, index+len);
}
}
private static void createAndShowGUI() {
//create main frame
JFrame mainFrame = new JFrame("");
BeispielTabelle test = new BeispielTabelle();
JPanel totalGUI = new JPanel();
totalGUI = test.erstelleTabelle();
totalGUI.setLayout(new BoxLayout(totalGUI, BoxLayout.Y_AXIS));
//visible mode
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.add(totalGUI); //integrate main panel to main frame
mainFrame.pack();
mainFrame.setVisible(true);
}
public static void main (String[] args) {
createAndShowGUI();
}//main
}//GUI_main
And this is my SearchRenderer
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.text.BadLocationException;
import java.awt.*;
public class SearchRenderer extends JTextArea implements TableCellRenderer {
/**
*
*/
private static final long serialVersionUID = 1L;
public SearchRenderer() {}//constructor
BeispielTabelle tabelle = new BeispielTabelle();
String textForSearch=tabelle.input;
#Override
public Component getTableCellRendererComponent (JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column ) {
this.setText((String) value);
if(value != null) {
String string = value.toString();
if(string.contains(textForSearch)){
int indexOf = string.indexOf(textForSearch);
while(indexOf >=0) {
try {
this.getHighlighter().addHighlight(indexOf,indexOf+textForSearch.length(),new javax.swing.text.DefaultHighlighter.DefaultHighlightPainter(Color.GREEN));
} catch (BadLocationException e) {
e.printStackTrace();
}
indexOf = string.indexOf(textForSearch, indexOf+textForSearch.length());
}
}
} else {
this.setText("");
this.getHighlighter().removeAllHighlights();
}
return this;
}
}
Maybe you can use JTable#repaint()
import java.awt.*;
import java.util.Objects;
import java.util.regex.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import javax.swing.text.*;
public final class SearchRendererTest {
private final JTextField field = new JTextField("Stefan");
private final SearchRenderer renderer = new SearchRenderer();
//Titel der Tabelle
private final String[] title = {"EINS", "ZWEI", "DREI"};
//Tabellendaten
private final Object[][] playerdata = {
{"34", "Stefan", "Mein Name ist Stefan"},
{"32", "Dirk", "Ich bin der Dirk"},
{"99", "Patrick", "Ich heisse Patrick"},
{"100", "Anna", "Ich bin die Anna"},
};
private final TableModel model = new DefaultTableModel(playerdata, title);
private final JTable table = new JTable(model);
public JComponent makeUI() {
table.setDefaultRenderer(Object.class, renderer);
field.getDocument().addDocumentListener(new DocumentListener() {
#Override public void insertUpdate(DocumentEvent e) {
fireDocumentChangeEvent();
}
#Override public void removeUpdate(DocumentEvent e) {
fireDocumentChangeEvent();
}
#Override public void changedUpdate(DocumentEvent e) {
/* not needed */
}
});
fireDocumentChangeEvent();
JPanel sp = new JPanel(new BorderLayout(5, 5));
sp.add(new JLabel("regex pattern:"), BorderLayout.WEST);
sp.add(field);
sp.add(Box.createVerticalStrut(2), BorderLayout.SOUTH);
sp.setBorder(BorderFactory.createTitledBorder("Search"));
JPanel p = new JPanel(new BorderLayout(5, 5));
p.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
p.add(sp, BorderLayout.NORTH);
p.add(new JScrollPane(table));
return p;
}
private void fireDocumentChangeEvent() {
String pattern = field.getText().trim();
renderer.setPattern(pattern);
table.repaint();
}
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 SearchRendererTest().makeUI());
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
class SearchRenderer implements TableCellRenderer {
private static final Color BACKGROUND_SELECTION_COLOR = new Color(220, 240, 255);
private final transient Highlighter.HighlightPainter highlightPainter
= new DefaultHighlighter.DefaultHighlightPainter(Color.YELLOW);
private final JTextField field = new JTextField();
private String pattern = "";
private String prev;
public boolean setPattern(String str) {
if (str == null || str.equals(pattern)) {
return false;
} else {
prev = pattern;
pattern = str;
return true;
}
}
public SearchRenderer() {
super();
field.setOpaque(true);
field.setBorder(BorderFactory.createEmptyBorder());
field.setForeground(Color.BLACK);
field.setBackground(Color.WHITE);
field.setEditable(false);
}
#Override public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
String txt = Objects.toString(value, "");
Highlighter highlighter = field.getHighlighter();
highlighter.removeAllHighlights();
field.setText(txt);
field.setBackground(isSelected ? BACKGROUND_SELECTION_COLOR : Color.WHITE);
if (pattern != null && !pattern.isEmpty() && !pattern.equals(prev)) {
Matcher matcher = Pattern.compile(pattern).matcher(txt);
if (matcher.find()) {
int start = matcher.start();
int end = matcher.end();
try {
highlighter.addHighlight(start, end, highlightPainter);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
}
return field;
}
}