If a cell value is same, changing a cell background in JTable - java

I have a question for JTable.
When I select a cell and then there are same value cell in JTable which I chose, that cells highlight background red color.
I don't know what to do....
P.S: I am sorry, I do not know how to enter the code in here...;;

You can implement ListSelectionListener to track selection changes in a table. Then implement TableCellRenderer that would change background of a cell with the same value of a selected object. Check out How to Use Tables for more details on JTable, renderers and selection.
Here is a very simple example that demonstrates this idea:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import java.awt.Color;
import java.awt.Component;
public class TableDemo {
private static void createAndShowGUI() {
JFrame frame = new JFrame("TableDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPanel = new JPanel();
String[] columnNames = { "Column1", "Column2" };
Object[][] data = { { "1", "3" }, { "2", "5" }, { "7", "1" },
{ "5", "3" } };
JTable table = new JTable();
MyModel model = new MyModel(Color.RED, table.getBackground());
model.setDataVector(data, columnNames);
table.setModel(model);
table.setColumnSelectionAllowed(true);
table.setDefaultRenderer(Object.class, new TestCellRenderer());
SelectionListener listener = new SelectionListener(table);
table.getSelectionModel().addListSelectionListener(listener);
table.getColumnModel().getSelectionModel()
.addListSelectionListener(listener);
JScrollPane scrollPane = new JScrollPane(table);
contentPanel.add(scrollPane);
contentPanel.setOpaque(true);
frame.add(contentPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
static class TestCellRenderer extends DefaultTableCellRenderer {
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
Component c = super.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, column);
MyModel model = (MyModel) table.getModel();
c.setBackground(model.getCellColor(row, column));
return c;
}
}
static class MyModel extends DefaultTableModel {
private Object selectedObject;
private Color selectedColor;
private Color normalColor;
public MyModel(Color selectedColor, Color normalColor) {
this.selectedColor = selectedColor;
this.normalColor = normalColor;
}
public Color getCellColor(int row, int column) {
if (getValueAt(row, column).equals(selectedObject))
return selectedColor;
return normalColor;
}
public void setSelectedObject(Object selectedObject) {
this.selectedObject = selectedObject;
fireTableRowsUpdated(0, getRowCount());
}
}
static class SelectionListener implements ListSelectionListener {
private JTable table;
SelectionListener(JTable table) {
this.table = table;
}
public void valueChanged(ListSelectionEvent e) {
int rowIndex = table.getSelectedRow();
int colIndex = table.getSelectedColumn();
if (!e.getValueIsAdjusting() && colIndex != -1 && rowIndex != -1) {
((MyModel) table.getModel()).setSelectedObject(table
.getValueAt(rowIndex, colIndex));
}
}
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Here is a result:
EDIT: solution using renderer only, without table model
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import java.awt.Color;
import java.awt.Component;
public class TableDemo {
private static void createAndShowGUI() {
JFrame frame = new JFrame("TableDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPanel = new JPanel();
String[] columnNames = { "Column1", "Column2" };
Object[][] data = { { "1", "3" }, { "2", "5" }, { "7", "1" },
{ "5", "3" } };
JTable table = new JTable(new DefaultTableModel(data, columnNames));
table.setColumnSelectionAllowed(true);
TestCellRenderer renderer = new TestCellRenderer();
table.setDefaultRenderer(Object.class, renderer);
SelectionListener listener = new SelectionListener(table);
table.getSelectionModel().addListSelectionListener(listener);
table.getColumnModel().getSelectionModel()
.addListSelectionListener(listener);
JScrollPane scrollPane = new JScrollPane(table);
contentPanel.add(scrollPane);
contentPanel.setOpaque(true);
frame.add(contentPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
static class TestCellRenderer extends DefaultTableCellRenderer {
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
Component c = super.getTableCellRendererComponent(table, value,
isSelected, hasFocus, row, column);
int columnIndex = table.getSelectedColumn();
int rowIndex = table.getSelectedRow();
if (columnIndex != -1 && rowIndex != -1){
Object selectedValue = table.getValueAt(rowIndex, columnIndex);
if (value.equals(selectedValue)) {
c.setBackground(Color.RED);
} else {
c.setBackground(table.getBackground());
}
}
return c;
}
}
static class SelectionListener implements ListSelectionListener {
private JTable table;
SelectionListener(JTable table) {
this.table = table;
}
public void valueChanged(ListSelectionEvent e) {
int rowIndex = table.getSelectedRow();
int colIndex = table.getSelectedColumn();
if (!e.getValueIsAdjusting() && colIndex != -1 && rowIndex != -1){
table.repaint();
}
}
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

Related

How to get jComboBox on certain cell in jTable?

I'm trying to create a jComboBox in a certain cell from a jTable. If on the same line in column 4 you have the value "FN", you will have on the column 5 a jComboBox with 3 options ("SSAA-MM-JJ", "SSAA/MM/JJ", "SAAMMJJ"), but all the other cells on column 5 must remain untouched if the value from the cell on column 4 on the same row is not "FN".
What do I do wrong?
Here is what i've tried:
package rdjcsv;
import java.awt.Component;
import javax.swing.AbstractCellEditor;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.TableCellEditor;
/**
*
* #author acucu
*/
class MyCellEditor extends AbstractCellEditor implements TableCellEditor {
DefaultCellEditor other = new DefaultCellEditor(new JTextField());
DefaultCellEditor checkbox = new DefaultCellEditor(new JComboBox(new Object[] {"abc"}));
private DefaultCellEditor lastSelected;
#Override
public Object getCellEditorValue() {
return lastSelected.getCellEditorValue();
}
#Override
public Component getTableCellEditorComponent(JTable table,
Object value, boolean isSelected, int row, int column) {
if(column == 4 && table.getValueAt(row, column-1).toString().contains("FN")){
if(row == 0) {
lastSelected = checkbox;
return checkbox.getTableCellEditorComponent(table, value, isSelected, row, column);
}
lastSelected = other;
return other.getTableCellEditorComponent(table, value, isSelected, row, column);
}
return other.getTableCellEditorComponent(table, value, isSelected, row, column);
}
}
And the call:
String[] values = new String[] {"SSAA-MM-JJ", "SSAA/MM/JJ", "SAAMMJJ"};
TableColumn col = jTable1.getColumnModel().getColumn(4);
col.setCellEditor(new MyComboBoxEditor(values));
col.setCellRenderer(new MyComboBoxRenderer(values));
The output:
jComboBox es on every cell from the 5th column.
Your image is showing the output from the cell renderer, not the cell editor, since only one cell editor should be visible at any time. You don't want the renderer to look like a JComboBox but rather to display as text, as a label. This suggests other problems with your program.
Other issues:
Your code above risks a NPE since lastSelected can be null when it starts out.
Why are you checking that row == 0? Do you to use the JComboBox editor for the first row only?
Post your minimal example program if still stuck,
for example, mine:
import java.awt.BorderLayout;
import java.awt.Component;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
#SuppressWarnings("serial")
public class ComboEditorEg extends JPanel {
private MyTableModel model = new MyTableModel();
private JTable table = new JTable(model);
public ComboEditorEg() {
for (int i = 0; i < 10; i++) {
String textA = i % 2 == 0 ? "SA" : "FN";
String textB = i % 2 == 0 ? "A" : "B";
Object[] row = new String[] { textA, textB };
model.addRow(row);
}
table.getColumnModel().getColumn(1).setCellEditor(new MyCellEditor());
setLayout(new BorderLayout());
add(new JScrollPane(table));
}
private static void createAndShowGui() {
ComboEditorEg mainPanel = new ComboEditorEg();
JFrame frame = new JFrame("ComboEditorEg");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
}
#SuppressWarnings("serial")
class MyTableModel extends DefaultTableModel {
public static final String[] COL_NAMES = { "Foo 1", "Foo 2" };
public MyTableModel() {
super(COL_NAMES, 0);
}
#Override
public Class<?> getColumnClass(int columnIndex) {
return String.class;
}
}
#SuppressWarnings("serial")
class MyCellEditor extends AbstractCellEditor implements TableCellEditor {
DefaultCellEditor other = new DefaultCellEditor(new JTextField());
DefaultCellEditor checkbox = new DefaultCellEditor(new JComboBox<String>(new String[] { "abc",
"def", "ghi" }));
private DefaultCellEditor lastSelected = other; // so it's not null
#Override
public Object getCellEditorValue() {
return lastSelected.getCellEditorValue();
}
#Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,
int row, int column) {
if (table.getValueAt(row, column - 1).toString().contains("FN")) {
lastSelected = checkbox;
return checkbox.getTableCellEditorComponent(table, value, isSelected, row, column);
}
return other.getTableCellEditorComponent(table, value, isSelected, row, column);
}
}

JTable copy value from view of cellrenderer

I have a JTable with a cellrenderer and my table is non-editable. When i select a cell and copy (ctrl-c) the value, its copying not the shown in the cell, it is copying the value which store in model. How could I copy cell value which shown in table.
public class TableDemo {
public static void main(String[] args) {
Vector<String> values = new Vector<String>();
values.add("Val1");
values.add("Val2");
JTable table = new JTable(new Object[][] { { "key", values },
{ "key2", values } }, new String[] { "Col1", "Col2" });
table.getColumnModel().getColumn(1).setCellRenderer(new MyTableCellRenderer());
table.setCellSelectionEnabled(true);
JFrame jf = new JFrame();
jf.getContentPane().add(table);
jf.setSize(500, 500);
jf.setVisible(true);
}
}
class MyTableCellRenderer extends DefaultTableCellRenderer {
#Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus,
row, column);
#SuppressWarnings("unchecked")
Vector<String> values = (Vector<String>) value;
setText(values.get(row));
return this;
}
}
You need to implement your own copy command. Here is the solution.
import java.awt.Component;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
public class TableDemo {
public static void main(String[] args) {
final Vector<String> values = new Vector<String>();
values.add("Val1");
values.add("Val2");
final JTable table = new JTable(new Object[][] { { "key", values },
{ "key2", values } }, new String[] { "Col1", "Col2" });
table.getColumnModel().getColumn(1).setCellRenderer(new MyTableCellRenderer());
table.registerKeyboardAction(new CopyAction(), KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_DOWN_MASK), JComponent.WHEN_FOCUSED);
table.setCellSelectionEnabled(true);
final JFrame jf = new JFrame();
jf.getContentPane().add(table);
jf.setSize(500, 500);
jf.setVisible(true);
}
private static class CopyAction extends AbstractAction {
/**
* {#inheritDoc}
*/
#Override
public void actionPerformed(ActionEvent e) {
final JTable tbl = (JTable) e.getSource();
final int row = tbl.getSelectedRow();
final int col = tbl.getSelectedColumn();
if (row >= 0 && col >= 0) {
final TableCellRenderer renderer = tbl.getCellRenderer(row, col);
final Component comp = tbl.prepareRenderer(renderer, row, col);
if (comp instanceof JLabel) {
final String toCopy = ((JLabel) comp).getText();
final StringSelection selection = new StringSelection(toCopy);
final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, selection);
}
}
}
}
}
#SuppressWarnings("serial")
class MyTableCellRenderer extends DefaultTableCellRenderer {
#Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus,
row, column);
#SuppressWarnings("unchecked")
final
Vector<String> values = (Vector<String>) value;
setText(values.get(row));
return this;
}
}

How to delete a row from jtable

I want to change the action of the button to delete. I have this code:
package buttonexample;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
public class ButtonExample {
public JTable table;
public static void main(String[] args) {
final ButtonExample example = new ButtonExample();
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
example.createAndShowGUI();
}
});
}
private void createAndShowGUI() {
JFrame frame = new JFrame("Button Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
table = new JTable(new JTableModel());
JScrollPane scrollPane = new JScrollPane(table);
table.setFillsViewportHeight(true);
TableCellRenderer buttonRenderer = new JTableButtonRenderer();
//table.getColumn("Button1").setCellRenderer(buttonRenderer);
table.getColumn("Button2").setCellRenderer(buttonRenderer);
table.addMouseListener(new JTableButtonMouseListener(table));
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
frame.getContentPane().setPreferredSize(new Dimension(500, 200));
frame.pack();
frame.setVisible(true);
}
public static class JTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private static final String[] COLUMN_NAMES = new String[] {"Id", "Stuff", "Asdfsdf", "Button2"};
private static final Class<?>[] COLUMN_TYPES = new Class<?>[] {Integer.class, String.class, String.class, JButton.class};
#Override public int getColumnCount() {
return COLUMN_NAMES.length;
}
#Override public int getRowCount() {
return 4;
}
#Override public String getColumnName(int columnIndex) {
return COLUMN_NAMES[columnIndex];
}
#Override public Class<?> getColumnClass(int columnIndex) {
return COLUMN_TYPES[columnIndex];
}
#Override public Object getValueAt(final int rowIndex, final int columnIndex) {
switch (columnIndex) {
case 0: return rowIndex;
case 1: return "Text for "+rowIndex;
case 2: return "Column for "+rowIndex;
case 3: final JButton button = new JButton(COLUMN_NAMES[columnIndex]);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// When this is clicked the whole row will be deleted.
JOptionPane.showMessageDialog(JOptionPane.getFrameForComponent(button),
"Button clicked for row "+rowIndex);
}
});
return button;
default: return "Error";
}
}
}
private static class JTableButtonRenderer implements TableCellRenderer {
#Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JButton button = (JButton)value;
if (isSelected) {
button.setForeground(table.getSelectionForeground());
button.setBackground(table.getSelectionBackground());
} else {
button.setForeground(table.getForeground());
button.setBackground(UIManager.getColor("Button.background"));
}
return button;
}
}
private static class JTableButtonMouseListener extends MouseAdapter {
private final JTable table;
public JTableButtonMouseListener(JTable table) {
this.table = table;
}
public void mouseClicked(MouseEvent e) {
int column = table.getColumnModel().getColumnIndexAtX(e.getX());
int row = e.getY()/table.getRowHeight();
if (row < table.getRowCount() && row >= 0 && column < table.getColumnCount() &&
column >= 0) {
Object value = table.getValueAt(row, column);
if (value instanceof JButton) {
((JButton)value).doClick();
}
}
}
}
}
But the (DefaultTableModel)someTable.getModel(); model.removeRow(row); I can't make it work because the table model does not have any name and I don't know what to name it. I have tried initializing a table model and I get error saying non-static variable model cannot be reference to a static context. Is there a way to delete the row in a static context?
The example by camickr is probably a more reusable solution, but for the sake of education...
Rendering of cells is the domain of the view
Model's should never contain components, especially if you're thinking about rendering them to the screen, this is simply the wrong approach to take...
You need to set up a TableCellEditor which will act as the means by which you can retrieve notification of the edit actions (mouse click or keypress)
This is a basic example, for simplicity, I've used a DefaultTableModel as it has a nice removeRow method, but conceivably, you could use any TableModel, so long as you provided the means to remove a row and modified by the editor to support it...
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.EventObject;
import javax.swing.AbstractCellEditor;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.event.CellEditorListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
public class ButtonExample {
public JTable table;
public static void main(String[] args) {
final ButtonExample example = new ButtonExample();
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
example.createAndShowGUI();
}
});
}
private void createAndShowGUI() {
JFrame frame = new JFrame("Button Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
table = new JTable(new ExampleTableModel());
JScrollPane scrollPane = new JScrollPane(table);
table.setFillsViewportHeight(true);
table.getColumn("action").setCellRenderer(new ButtonCellRenderer());
table.getColumn("action").setCellEditor(new ButtonCellEditor());
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public static class ExampleTableModel extends DefaultTableModel {
public ExampleTableModel() {
super(new Object[]{"id", "stuff", "blah", "action"}, 0);
for (int index = 0; index < 10; index++) {
addRow(new Object[]{index, "Text for " + index, "Na na", index});
}
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return columnIndex == 3;
}
}
public static class ButtonCellRenderer extends JButton implements TableCellRenderer {
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (value != null) {
setText("Delete row " + value.toString());
} else {
setText("Delete Me");
}
if (isSelected) {
setForeground(table.getSelectionForeground());
setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(UIManager.getColor("Button.background"));
}
return this;
}
}
public static class ButtonCellEditor extends AbstractCellEditor implements TableCellEditor {
private JButton editor;
private Object value;
private int row;
private JTable table;
public ButtonCellEditor() {
editor = new JButton();
editor.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (table != null) {
fireEditingStopped();
TableModel model = table.getModel();
if (model instanceof DefaultTableModel) {
((DefaultTableModel) model).removeRow(row);
}
}
}
});
}
#Override
public boolean isCellEditable(EventObject e) {
return true;
}
#Override
public Object getCellEditorValue() {
return value;
}
#Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
this.table = table;
this.row = row;
this.value = value;
if (value != null) {
editor.setText("Delete row " + value.toString());
} else {
editor.setText("Delete Me");
}
if (isSelected) {
editor.setForeground(table.getSelectionForeground());
editor.setBackground(table.getSelectionBackground());
} else {
editor.setForeground(table.getForeground());
editor.setBackground(UIManager.getColor("Button.background"));
}
return editor;
}
}
}
Take a closer look at How to Use Tables for more details
This is just a personal preference, but I prefer to use a toolbar or menu item and key bindings to provide this support. Buttons in a table just seem so...dated - IMHO

JTable with different JComboBox-es for each row

I created JTable that contains information about employees. In this JTable I added the column called "Qualifications". This column is represented by JComboBox (different content at each row). For instance:
Row 1 | JComboBox(){"Programmer","Web"}
Row 2 | JComboBox(){"Writer","Editor"}
The JComboBox content is taken from the List<String> employees[row].getQualification().
The problem is that the selected item in Row 1 and Row 2 is "Programmer", however "Programmer" should not appear in Row 2. Only when I click on JComboBox, the correct list appears, i.e. Row 2 - {"Writer","Editor"}.
TableColumn column = table.getColumnModel().getColumn(5);
column.setCellRenderer(getRenderer());
private TableCellRenderer getRenderer() {
return new TableCellRenderer() {
private JComboBox<String> box = new JComboBox<String>();
#Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
for (String q : employees[row].getQualification())
box.addItem(q);
box.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
box.setForeground(isSelected ? table.getSelectionForeground() : table.getForeground());
return box;
}
};
}
Override the getCellEditor() method of the JTable. Something like:
import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
public class TableComboBoxByRow extends JPanel
{
List<TableCellEditor> editors = new ArrayList<TableCellEditor>(3);
public TableComboBoxByRow()
{
setLayout( new BorderLayout() );
// Create the editors to be used for each row
String[] items1 = { "Red", "Blue", "Green" };
JComboBox<String> comboBox1 = new JComboBox<String>( items1 );
DefaultCellEditor dce1 = new DefaultCellEditor( comboBox1 );
editors.add( dce1 );
String[] items2 = { "Circle", "Square", "Triangle" };
JComboBox<String> comboBox2 = new JComboBox<String>( items2 );
DefaultCellEditor dce2 = new DefaultCellEditor( comboBox2 );
editors.add( dce2 );
String[] items3 = { "Apple", "Orange", "Banana" };
JComboBox<String> comboBox3 = new JComboBox<String>( items3 );
DefaultCellEditor dce3 = new DefaultCellEditor( comboBox3 );
editors.add( dce3 );
// Create the table with default data
Object[][] data =
{
{"Color", "Red"},
{"Shape", "Square"},
{"Fruit", "Banana"},
{"Plain", "Text"}
};
String[] columnNames = {"Type","Value"};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable(model)
{
// Determine editor to be used by row
public TableCellEditor getCellEditor(int row, int column)
{
int modelColumn = convertColumnIndexToModel( column );
if (modelColumn == 1 && row < 3)
return editors.get(row);
else
return super.getCellEditor(row, column);
}
};
JScrollPane scrollPane = new JScrollPane( table );
add( scrollPane );
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("Table Combo Box by Row");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new TableComboBoxByRow() );
frame.setSize(200, 200);
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
JComboBox-es appear only on a click
because you use them as CellEditor, which apper only when you edit cells. If you want to display your column cells as JComboBox everytime, you need to use TableCellRenderer, read about that. Here is simple example of JComboBox as renderer :
import java.awt.Component;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
public class TestFrame extends JFrame{
public TestFrame(){
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
private void init() {
JTable t = new JTable(3,3);
TableColumn column = t.getColumnModel().getColumn(2);
column.setCellRenderer(getRenderer());
add(new JScrollPane(t));
}
private TableCellRenderer getRenderer() {
return new TableCellRenderer() {
private JComboBox<String> box = new JComboBox<String>(new String[]{"1","2"});
#Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
box.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
box.setForeground(isSelected ? table.getSelectionForeground() : table.getForeground());
return box;
}
};
}
public static void main(String... s){
new TestFrame();
}
}
Thanks to #alex2410, I cleaned up the code and wrapped it into a ComboTable class which should do the job for you. instantiate ComboTable class with a hashmap of each row values (the demo assumes 2 columns, but you can add more). Note MyMap.of is just a wrapper for java 9 Map.of since I was using Java 8 at that time. same for MyList.of
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.EventObject;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.CellEditorListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import rs.code.utils.MyList;
import rs.code.utils.MyMap;
public class Test extends JFrame
{
private static final long serialVersionUID = 1L;
public ComboTable table = new ComboTable(MyMap.of("Gender", MyList.of("male", "female"), "City", MyList.of("london", "bedord"), "orientation", MyList.of("left", "right")));
public Test()
{
super("EachRow Editor Example");
JScrollPane scroll = new JScrollPane(table);
getContentPane().add(scroll, BorderLayout.CENTER);
setPreferredSize(new Dimension(400, 120));
setLocation(150, 100);
pack();
setVisible(true);
}
public static void main(String[] args)
{
Test frame = new Test();
frame.addWindowListener(new WindowAdapter()
{
#Override
public void windowClosing(WindowEvent e)
{
System.out.println(frame.table.getSelectedValues().toString());
System.exit(0);
}
});
}
}
class ComboTable extends JTable
{
private static final long serialVersionUID = 1L;
protected Map<Integer, ComboCellEditor> editors = new LinkedHashMap<>();
public ComboTable(Map<String, List<String>> rows)
{
setModel(new DefaultTableModel(new String[] {"Attribute", "Value"}, rows.size()));
setRowHeight(20);
EachRowEditor rowEditor = new EachRowEditor(this);
int i = 0;
for(String key : rows.keySet())
{
getModel().setValueAt(key, i, 0);
editors.put(i++, new ComboCellEditor(createComboBox(rows.get(key))));
}
getColumn("Value").setCellEditor(rowEditor);
getColumn("Value").setCellRenderer(getRenderer());
}
public Map<Integer, ComboCellEditor> getEditors()
{
return editors;
}
public Map<String, String> getSelectedValues()
{
Map<String, String> values = new LinkedHashMap<>();
for(int i=0;i<getModel().getRowCount();i++)
{
values.put(getModel().getValueAt(i, 0).toString(), editors.get(i).getComboBox().getSelectedItem().toString());
}
return values;
}
private JComboBox<String> createComboBox(List<String> elements)
{
JComboBox<String> comboBox = new JComboBox<>();
for (String element : elements)
{
comboBox.addItem(element);
}
comboBox.setSelectedIndex(0);
comboBox.addComponentListener(new ComponentAdapter()
{
#Override
public void componentShown(ComponentEvent e)
{
final JComponent c = (JComponent) e.getSource();
SwingUtilities.invokeLater(new Runnable()
{
#SuppressWarnings("rawtypes")
#Override
public void run()
{
c.requestFocus();
System.out.println(c);
if (c instanceof JComboBox)
{
System.out.println(((JComboBox) c).getSelectedItem());
}
}
});
}
});
return comboBox;
}
private TableCellRenderer getRenderer()
{
return new TableCellRenderer()
{
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
editors.get(row).getComboBox().setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
editors.get(row).getComboBox().setForeground(isSelected ? table.getSelectionForeground() : table.getForeground());
return editors.get(row).getComboBox();
}
};
}
}
class ComboCellEditor extends DefaultCellEditor
{
private static final long serialVersionUID = 1L;
private final JComboBox<String> comboBox;
public ComboCellEditor(JComboBox<String> comboBox)
{
super(comboBox);
this.comboBox = comboBox;
}
public JComboBox<String> getComboBox()
{
return comboBox;
}
}
class EachRowEditor implements TableCellEditor
{
private TableCellEditor editor;
private final TableCellEditor defaultEditor;
private final ComboTable table;
public EachRowEditor(ComboTable table)
{
this.table = table;
defaultEditor = new DefaultCellEditor(new JTextField());
}
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
{
return editor.getTableCellEditorComponent(table, value, isSelected, row, column);
}
public Object getCellEditorValue()
{
return editor.getCellEditorValue();
}
public boolean stopCellEditing()
{
return editor.stopCellEditing();
}
public void cancelCellEditing()
{
editor.cancelCellEditing();
}
public boolean isCellEditable(EventObject anEvent)
{
selectEditor((MouseEvent) anEvent);
return editor.isCellEditable(anEvent);
}
public void addCellEditorListener(CellEditorListener l)
{
editor.addCellEditorListener(l);
}
public void removeCellEditorListener(CellEditorListener l)
{
editor.removeCellEditorListener(l);
}
public boolean shouldSelectCell(EventObject anEvent)
{
selectEditor((MouseEvent) anEvent);
return editor.shouldSelectCell(anEvent);
}
protected void selectEditor(MouseEvent e)
{
int row;
if (e == null)
{
row = table.getSelectionModel().getAnchorSelectionIndex();
}
else
{
row = table.rowAtPoint(e.getPoint());
}
editor = table.getEditors().get(row);
if (editor == null)
{
editor = defaultEditor;
}
}
}

JTable color row and cell dynamically

I want to make a search functionality for JTable object.
I have a JTextFiled where i put my text to search.
I want to change colors rows and cells which contains this text.
Now i'm stuck because i have no idea how to change color dynamically.
public class TableSearchCellRenderer extends DefaultTableCellRenderer {
String search = "";
public void setSearch(String search) {
this.search = search;
}
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (table.getValueAt(row, column).equals(search)) {
setBackground(Color.green);
}
return this;
}
}
I've tried with something like this but it doesn't work.
I tried to call rerender table like this way
String selectedTitle = tabbed.getTitleAt(tabbed.getSelectedIndex());
JTable table = tabels.get(selectedTitle);
((TableSearchCellRenderer)table.getDefaultRenderer(String.class)).setSearch(searchField.getText());
table.repaint();
((AbstractTableModel) table.getModel()).fireTableDataChanged();
but with no success :(
Could you help me?
Here is a working version of your search feature based on the TableCellRenderer. One of the issue you may have hit, is that, although your TableModel contains String, if you use the DefaultTableModel, it always returns Object.class for all data and the JTable will therefore use the DefaultTableCellRenderer instead of your TableSearchCellRenderer.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.util.Random;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
public class TestTable2 {
private String search;
public String getSearch() {
return search;
}
public void setSearch(String search) {
this.search = search;
}
private class TableSearchRenderer extends DefaultTableCellRenderer {
#Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
setBackground(null);
Component tableCellRendererComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (getSearch() != null && getSearch().length() > 0 && value.toString().contains(getSearch())) {
setBackground(Color.RED);
}
return tableCellRendererComponent;
}
}
protected void initUI() {
DefaultTableModel model = new DefaultTableModel();
for (int i = 0; i < 5; i++) {
model.addColumn("Column " + (i + 1));
}
Random random = new Random();
for (int i = 0; i < 200; i++) {
Vector<Object> row = new Vector<Object>();
for (int j = 0; j < 40; j++) {
row.add(WORDS[random.nextInt(WORDS.length)]);
}
model.addRow(row);
}
table = new JTable(model);
TableSearchRenderer renderer = new TableSearchRenderer();
table.setDefaultRenderer(Object.class, renderer);
textField = new JTextField(30);
textField.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent e) {
updateSearch();
}
#Override
public void insertUpdate(DocumentEvent e) {
updateSearch();
}
#Override
public void changedUpdate(DocumentEvent e) {
updateSearch();
}
});
JFrame frame = new JFrame(TestTable2.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollpane = new JScrollPane(table);
scrollpane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
frame.add(scrollpane, BorderLayout.CENTER);
frame.add(textField, BorderLayout.NORTH);
frame.setSize(1000, 800);
frame.setVisible(true);
}
protected void updateSearch() {
setSearch(textField.getText());
table.repaint();
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestTable2().initUI();
}
});
}
private static final String[] WORDS = { "art", "australia", "baby", "beach", "birthday", "blue", "bw", "california", "canada", "canon",
"cat", "chicago", "china", "christmas", "city", "dog", "england", "europe", "family", "festival", "flower", "flowers", "food",
"france", "friends", "fun", "germany", "holiday", "india", "italy", "japan", "london", "me", "mexico", "music", "nature",
"new", "newyork", "night", "nikon", "nyc", "paris", "park", "party", "people", "portrait", "sanfrancisco", "sky", "snow",
"spain", "summer", "sunset", "taiwan", "tokyo", "travel", "trip", "uk", "usa", "vacation", "water", "wedding" };
private JTable table;
private JTextField textField;
}
See Table Row Rendering. The example does row level highlighting on a fixed word. You would need to modify the code to do the highlighting on your search word.
Another approach is to filter the table to see only the rows that contain the text you are searching for. See Sorting and Filtering for a working example.
It works. I change prepare renderer.
JTable table = new JTable() {
private static final long serialVersionUID = 1L;
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component c = super.prepareRenderer(renderer, row, column);
**if (column == 0) {
for (int i = 0; i < getModel().getColumnCount(); i++) {
if (((TableSearchRenderer) getDefaultRenderer(String.class)).getSearch().length() > 0 && ((TableSearchRenderer) getDefaultRenderer(String.class)).getSearch().toLowerCase().equals(getModel().getValueAt(row, i).toString().toLowerCase()))
((TableSearchRenderer) getDefaultRenderer(String.class)).getRows().add(row);
}
}**
if (((TableSearchRenderer) getDefaultRenderer(String.class)).getRows().contains(row) && c.getBackground() != Color.RED) {
c.setBackground(Color.GREEN);
}
return c;
}
};

Categories