For my project i just want to show a dialogue box with JTable. On that i want to show a JCombobox with available staff based on row index. I tried the following coding,
for(int i=0;i<n;i++)
{
Object obj[] = new Object[4];
obj[0]=2,
obj[1]=3;
obj[2]=""; //Here combo appear.
obj[3]=3;
JComboBox aa = new JComboBox();
for(int j=0;j<m;j++)
{
aa.addItem(rs.getString(1));
aa.addItem(rs.getString(2));
}
table.getcolumnModel.getcolumn(2).setcellEditor(new DefaultCellEditor(aa));
model.addRow(obj);
}
if i use this output generated. But last rows combo value is present in all previous rows combo. Those different values are not in that. its totally same. But all other text fields are correctly displayed. What should i do here. thanking you...
Note: Here
aa.addItem(rs.getString(1));
aa.addItem(rs.getString(2));
is just for example. Actually it will return many number of values based on id.
You try to set editor to each row, but it's wrong, editor can be set to whole column. Read Concepts: Editors and Renderers. Instead of that implement your logic in getTableCellEditorComponent() method of TableCellEditor.
Simple example with different values for each row:
import java.awt.Component;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
public class TestFrame extends JFrame {
private DefaultComboBoxModel<String> model;
private Map<String, List<String>> keyVal;
public TestFrame() {
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private void init() {
keyVal = new HashMap<>();
keyVal.put("1", Arrays.asList(new String[]{"a","b"}));
keyVal.put("0", Arrays.asList(new String[]{"c","d"}));
keyVal.put("2", Arrays.asList(new String[]{"e","f","g"}));
JTable t = new JTable(3,3);
t.getColumnModel().getColumn(0).setCellEditor(getEditor());
add(new JScrollPane(t));
}
private TableCellEditor getEditor() {
return new DefaultCellEditor(new JComboBox<String>(model = new DefaultComboBoxModel<String>())){
#Override
public Component getTableCellEditorComponent(JTable table,Object value, boolean isSelected, int row, int column) {
model.removeAllElements();
if(keyVal.containsKey(row+"")){
List<String> list = keyVal.get(row+"");
for(String s : list)
model.addElement(s);
}
return super.getTableCellEditorComponent(table, value, isSelected, row, column);
}
};
}
public static void main(String args[]) {
new TestFrame();
}
}
Related
I customized a Jtable headers with a TableCellRenderer so filter icon would appear, and as the user clicks on the filter icon, a pop-up filter like excel's appears (picture 1). However, if the user clicks on the text of the header, a row sorter is appliead. When the row sorter is applied (picture 2), it override the customization and filter icon disappears. Is there a way to avoid this behavior while keeping the row sorter on the table header?
You can do this by decorating the original renderer of the table header with a custom one which will add the desired icon of filtering.
For example, follows some code to preserve the sort icons while adding your own label next to the original column header:
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.util.Objects;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
public class Main {
private static class MyTableCellRenderer extends DefaultTableCellRenderer {
private final TableCellRenderer originalRenderer;
public MyTableCellRenderer(final TableCellRenderer originalRenderer) {
this.originalRenderer = Objects.requireNonNull(originalRenderer);
}
#Override
public Component getTableCellRendererComponent(final JTable table,
final Object value,
final boolean isSelected,
final boolean hasFocus,
final int row,
final int column) {
final Component original = originalRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (row >= 0) //The header will have a row equal to -1.
return original;
final JPanel container = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 0));
final JLabel filtering = new JLabel("Filter", JLabel.CENTER); //Your icon should go in this label...
//Put some fancy background to make the positioning of the label clear:
filtering.setOpaque(true);
filtering.setBackground(Color.CYAN);
//The default renderer comes with a border... Let's apply the border to the whole new container:
if (original instanceof JComponent) {
container.setBorder(((JComponent) original).getBorder());
((JComponent) original).setBorder(null);
}
container.add(filtering);
container.add(original);
return container;
}
}
private static void createAndShowGUI() {
final JTable table = new JTable(new Object[][] {
new Object[]{"Data001", "Data002", "Data003"},
new Object[]{"Data011", "Data012", "Data013"},
new Object[]{"Data021", "Data022", "Data023"},
new Object[]{"Data031", "Data032", "Data033"},
new Object[]{"Data041", "Data042", "Data043"}
}, new Object[] {"Column1", "Column2", "Column3"});
table.setAutoCreateRowSorter(true);
final JTableHeader header = table.getTableHeader();
header.setDefaultRenderer(new MyTableCellRenderer(header.getDefaultRenderer()));
final JFrame frame = new JFrame("Table header");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(final String[] args) {
SwingUtilities.invokeLater(Main::createAndShowGUI);
}
}
Instead of the word Filter (which appears on each column header) you can use your icons on the created label instead.
References:
Source (see the section: 3. Keeping sort icons).
How can I put a control in the JTableHeader of a JTable?
I want to have a JCombobox in my Swing application, which shows the title when nothing is selected. Something like this:
COUNTRY ▼
Spain
Germany
Ireland
I want "COUNTRY" to show when the selected index is -1 and thus, the user wouldn't be able to select it. I tried to put it on the first slot and then overriding the ListCellRenderer so the first element appears greyed out, and handling the events so when trying to select the "title", it selects the first actual element, but I think this is a dirty approach.
Could you lend me a hand?
Overriding the ListCellRenderer is a good approach, but you tried something overly complicated. Just display a certain string if you are rendering the cell -1 and there is no selection (value is null). You are not limited to display elements on the list.
The following is an example program that demonstrates it:
Full Code:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import javax.swing.SwingUtilities;
public class ComboBoxTitleTest
{
public static final void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
new ComboBoxTitleTest().createAndShowGUI();
}
});
}
public void createAndShowGUI()
{
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
JPanel buttonsPanel = new JPanel();
frame.add(mainPanel);
frame.add(buttonsPanel, BorderLayout.SOUTH);
String[] options = { "Spain", "Germany", "Ireland", "The kingdom of far far away" };
final JComboBox comboBox = new JComboBox(options);
comboBox.setRenderer(new MyComboBoxRenderer("COUNTRY"));
comboBox.setSelectedIndex(-1); //By default it selects first item, we don't want any selection
mainPanel.add(comboBox);
JButton clearSelectionButton = new JButton("Clear selection");
clearSelectionButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
comboBox.setSelectedIndex(-1);
}
});
buttonsPanel.add(clearSelectionButton);
frame.pack();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
class MyComboBoxRenderer extends JLabel implements ListCellRenderer
{
private String _title;
public MyComboBoxRenderer(String title)
{
_title = title;
}
#Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean hasFocus)
{
if (index == -1 && value == null) setText(_title);
else setText(value.toString());
return this;
}
}
}
index == -1 in the renderer is the head component that, by default, displays the selected item and where we want to put our title when there's no selection.
The renderer knows that there's nothing selected because the value passed to it is null, which is usually the case. However if for some weird reasons you had selectable null values in your list, you can just let the renderer consult which is the explicit current selected index by passing it a reference to the comboBox, but that is totally unrealistic.
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComponent;
import javax.swing.SwingUtilities;
import net.java.dev.designgridlayout.DesignGridLayout;
import java.io.*;
import net.java.dev.designgridlayout.Tag;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import java.sql.*;
class table1
{
JFrame JF;
Container C;
JPanel JP;
JLabel creditLabel;
JComboBox credit;
String[] Credit = {"Vasan Phalke", "Pansare", "Anil Kg", "Suresh"};
String[] Names = {"Name", "Qty", "Rate/ Kg", "Rate/Dzn.", "Total Amt."};
JTable table;
DefaultTableModel model;
JScrollPane scrollPane;
public table1()
{
JF = new JFrame();
JP = new JPanel();
C= JF.getContentPane();
JF.pack();
JF.setLocationRelativeTo(null);
JF.setVisible(true);
DesignGridLayout layout = new DesignGridLayout(C);
creditLabel = new JLabel("Credit");
credit = new JComboBox<String>(Credit);
model = new DefaultTableModel(Names,5);
table =new JTable(model){#Override
public boolean isCellEditable(int arg0, int arg1)
{
return true;
}
};
scrollPane= new JScrollPane(table);
layout.row().grid(creditLabel).add(credit);
layout.emptyRow();
layout.row().grid().add(table);
C.add(JP);
}
public static void main(String args[])
{
new table1();
}
}
By clicking on the value of combobox, it should appear in the name column of the table, and what changes should be made to the table for automatic calculation, ie, when i enter qty and rate, total amount should automatically be calculated.
How all these things can be done, please help.
Thanks in advance.
Read the section from the Swing tutorial on How to Use Tables
The tutorial shows you how to use a combo box as an editor for a column in a table. This is what you should be doing instead of having a separate combo box.
To calculate the amount, you need to create a custom TableModel and override the setValueAt() method. Whenever the quantity or rate changes you recalculate the amount.
Here's the idea: Let's say I have a class extending TableModel, with something like a List<List<String>> collection field. On an event, I want to clear out a JTable and re-add rows where one specific column is a combo box; the items in combo box n are the items in the List<String> from collection.get(n) in my list. So I'm iterating over collection adding rows, and I'm iterating over each collection.get(n) adding combo box items.
There are no event listeners. When a separate button is clicked I can work out what needs to happen as long as I can getSelectedIndex on each combo box.
I have spent two and a half hours turning my GUI into code spaghetti where I've extended virtually everything and I have maximum coupling on practically everything. I think I might even have two disjoint collections of JComboBox instances. I say this to stress that it would do absolutely no good for me to post any code I currently have.
I have read the oracle tutorial on JTable, all of these that strangely don't have an explanation I can understand.
So basically I just need an idea of what I need, because I'm not getting anywhere with the resources I've found.
So, basically, you need a TableCelLEditor that is capable of seeding a JComboBox with the rows from the available list, for example...
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
public class TableCellEditor {
public static void main(String[] args) {
new TableCellEditor();
}
public TableCellEditor() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
List<List<String>> values = new ArrayList<>(25);
for (int row = 0; row < 10; row++) {
List<String> rowValues = new ArrayList<>(25);
for (int index = 0; index < 10; index++) {
rowValues.add("Value " + index + " for row " + row);
}
values.add(rowValues);
}
DefaultTableModel model = new DefaultTableModel(new Object[]{"Data"}, 10);
JTable table = new JTable(model);
table.setShowGrid(true);
table.setGridColor(Color.GRAY);
table.getColumnModel().getColumn(0).setCellEditor(new MyEditor(values));
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(table));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MyEditor extends DefaultCellEditor {
private List<List<String>> rowValues;
public MyEditor(List<List<String>> rowValues) {
super(new JComboBox());
this.rowValues = rowValues;
}
#Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
JComboBox cb = (JComboBox) getComponent();
List<String> values = rowValues.get(row);
DefaultComboBoxModel model = new DefaultComboBoxModel(values.toArray(new String[values.size()]));
cb.setModel(model);
return super.getTableCellEditorComponent(table, value, isSelected, row, column);
}
}
}
I have read through the majority of the JTable/JComboBox responses to other questions of this ilk, but haven't yet found a solution to my problem.
I have created a table that has JComboBox TableHeader elements. None of the JComboBox elements will open to display a list of items. How do I get the item lists for the individual JComboBox elements to display?
Please note that a distinguishing element of this question is that the JComboBox is in the TableHeader, not embedded within a JTable cell.
Any help is appreciated.
SSCE
import java.awt.Component;
import java.awt.Dimension;
import java.util.Enumeration;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
public class ComboHeaderTest extends JScrollPane {
private static final Dimension DEFAULT_SIZE = new Dimension(200, 200);
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ComboHeaderTest().initComponents();
}
});
}
private ComboHeaderTest() {
final String[][] data = { {"Header 1", "Header 2", "Header 3"},
{"A", "B", "C"},
{"D", "E", "F"},
{"G", "H", "I"}};
setViewportView(getTable(data));
setPreferredSize(DEFAULT_SIZE);
}
private void initComponents() {
JFrame frame = new JFrame("ComboHeaderTest");
frame.add(this);
frame.pack();
frame.setVisible(true);
}
private JTable getTable(final String[][] data) {
final String[] items = data[0];
final ComboHeaderRenderer[] columnHeaders = new ComboHeaderRenderer[items.length];
for(int i = 0; items.length > i; ++i) {
columnHeaders[i] = new ComboHeaderRenderer(items);
}
final JTable table = new JTable(data, columnHeaders);
final Enumeration<TableColumn> tableEnum = table.getColumnModel().getColumns();
for (int columnIndex = 0; tableEnum.hasMoreElements(); ++columnIndex) {
final TableColumn column = tableEnum.nextElement();
final ComboHeaderRenderer combo = columnHeaders[columnIndex];
column.setHeaderValue(combo.getItemAt(columnIndex));
column.setHeaderRenderer(combo);
}
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setRowSelectionAllowed(true);
table.setColumnSelectionAllowed(false);
table.setCellSelectionEnabled(false);
table.setFillsViewportHeight(true);
table.setSize(DEFAULT_SIZE);
table.validate();
return table;
}
private static class ComboHeaderRenderer extends JComboBox implements TableCellRenderer{
public ComboHeaderRenderer(final String[] entries) {
for (int i = 0; entries.length > i; ++i) {
addItem(entries[i]);
}
}
#Override
public Component getTableCellRendererComponent(final JTable table, final Object value,
final boolean isSelected, final boolean hasFocus, final int row, final int column) {
setSelectedItem(value);
return this;
}
}
}
This actually works exactly as expected. I think the clue is TableCellRenderer.
Renderer's are typically non-interactive components. They are usually just a "snap-shot" of the component painted on to a surface and there is typically no way for a user to interact with them.
This is the expected behavior.
In order to supply editable functionality to the table header, you're going to need to supply your implementation of a JTableHeader
Have a look at this example for some ideas
Here is an example that uses a JComboBox in a JTable TableHeader.
For other types of components is easier, have a look here.