I'm new to GUI design and I'm trying to plan this out before I go too far the wrong way, any help would be nice. I'm trying to display a JTable with rows of Employee, which itself has datatypes of String and ArrayList<Cert>. Cert contains a String.
I'd like to have the table present the data for editing, but for a few of the columns I'd like to implement a JComboBox for selection of a String from a set of valid strings, as well as color each option differently (different background colors in the JComboBox).
Also, the ArrayList<Cert> currently displays in a cell as [xxx, xxx, ...] where XXX is the return from the toString() function for each item in the ArrayList. I think I'd like to display that ArrayList<Cert> as a read-only JComboBox, but I'm not as concerned with this item.
I'm questioning how many classes I need to create to make this happen. I already have a custom model for the JTable extending AbstractTableModel. Do I need to write an extension of JComboBox or do I just need to extend the appropriate renderer for a JComboBox as a cell and do the magic there, then assign that custom renderer to the cell renderer for the String cell?
Here's what I have so far, lightly abridged:
public class EmployeeTableModel extends AbstractTableModel {
...
private ArrayList<Employee> myDataObjects = new ArrayList<Employee>();
...
#Override
public Object getValueAt(int row, int column) {
Employee emp = myDataObjects.get(row);
switch (column) {
case 0:
return emp.getName();
case 1:
return emp.getShift();
case 2:
return emp.getCertifications();
default:
return "";
}
}
}
Employees:
public class Employee {
private String name;
private String shift;
private ArrayList<Cert> certs;
...
public String getName() {
return name;
}
public String getShift() {
return shift;
}
public ArrayList<Cert> getCerts() {
return certs;
}
...
}
And the initializations:
EmployeeTableModel etm = new EmployeeTableModel();
JTable employeeTable = new JTable();
employeeTable.setModel( etm );
you can to start with, simplest code as is possible, maybe depends if you want to see JComboBox as Renderer too by #aterai
import java.awt.BorderLayout;
import javax.swing.DefaultCellEditor;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.plaf.basic.BasicComboBoxRenderer;
public class TableRenderDemo extends JPanel {
private static final long serialVersionUID = 1L;
public TableRenderDemo() {
super(new BorderLayout(5, 5));
final JTable table = new JTable(new MyTableModel());
table.setPreferredScrollableViewportSize(table.getPreferredSize());
table.setFillsViewportHeight(true);
table.setRowHeight(20);
JScrollPane scrollPane = new JScrollPane(table);
initColumnSizes(table);
setUpSportColumn(table, table.getColumnModel().getColumn(2));
add(scrollPane, BorderLayout.CENTER);
JButton resetButton = new JButton("Reset to default");
resetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < table.getRowCount(); i++) {
table.getModel().setValueAt("None of the above", i, 2);
}
}
});
add(resetButton, BorderLayout.SOUTH);
}
private void initColumnSizes(JTable table) {
MyTableModel model = (MyTableModel) table.getModel();
TableColumn column = null;
Component comp = null;
int headerWidth = 0;
int cellWidth = 0;
Object[] longValues = model.longValues;
TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();
for (int i = 0; i < 5; i++) {
column = table.getColumnModel().getColumn(i);
comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
headerWidth = comp.getPreferredSize().width;
comp = table.getDefaultRenderer(model.getColumnClass(i)).getTableCellRendererComponent(table, longValues[i], false, false, 0, i);
cellWidth = comp.getPreferredSize().width;
column.setPreferredWidth(Math.max(headerWidth, cellWidth));
}
}
private void setUpSportColumn(JTable table, TableColumn sportColumn) {
ArrayList<String> listSomeString = new ArrayList<String>();
listSomeString.add("Snowboarding");
listSomeString.add("Rowing");
listSomeString.add("Knitting");
listSomeString.add("Speed reading");
listSomeString.add("Pool");
listSomeString.add("None of the above");
JComboBox comboBox = new JComboBox();
comboBox.addItem(new Item(1, "-"));
comboBox.addItem(new Item(2, "Snowboarding"));
comboBox.addItem(new Item(3, "Rowing"));
comboBox.addItem(new Item(4, "Knitting"));
comboBox.addItem(new Item(5, "Speed reading"));
comboBox.addItem(new Item(6, "Pool"));
comboBox.addItem(new Item(7, "None of the above"));
comboBox.setMaximumRowCount(3);
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox comboBox = (JComboBox) e.getSource();
Item item = (Item) comboBox.getSelectedItem();
System.out.println(item.getId() + " : " + item.getDescription());
}
});
comboBox.setRenderer(new ItemRenderer());
sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
sportColumn.setCellRenderer(renderer);
}
class ItemRenderer extends BasicComboBoxRenderer {
#Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value != null) {
Item item = (Item) value;
setText(item.getDescription().toUpperCase());
}
if (index == -1) {
Item item = (Item) value;
setText("" + item.getId());
}
return this;
}
}
class Item {
private int id;
private String description;
public Item(int id, String description) {
this.id = id;
this.description = description;
}
public int getId() {
return id;
}
public String getDescription() {
return description;
}
#Override
public String toString() {
return description;
}
}
class MyTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private String[] columnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
private Object[][] data = {{"Kathy", "Smith", "Snowboarding", new Integer(5), false},
{"John", "Doe", "Rowing", new Integer(3), true}, {"Sue", "Black", "Knitting", new Integer(2), false},
{"Jane", "White", "Speed reading", new Integer(20), true}, {"Joe", "Brown", "Pool", new Integer(10), false}};
public final Object[] longValues = {"Jane", "Kathy", "None of the above", new Integer(20), Boolean.TRUE};
#Override
public int getColumnCount() {
return columnNames.length;
}
#Override
public int getRowCount() {
return data.length;
}
#Override
public String getColumnName(int col) {
return columnNames[col];
}
#Override
public Object getValueAt(int row, int col) {
return data[row][col];
}
#Override
public Class<?> getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
#Override
public boolean isCellEditable(int row, int col) {
if (col < 2) {
return false;
} else {
return true;
}
}
#Override
public void setValueAt(Object value, int row, int col) {
data[row][col] = value;
fireTableCellUpdated(row, col);
System.out.println("New value of data: " + getValueAt(row, col));
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("TableRenderDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TableRenderDemo newContentPane = new TableRenderDemo();
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
Related
I have a table that I'm loading with rows at run time. Once loaded the user needs to choose an item from a JComboBox in the first column for each line. Then he needs to chose an item from another JComboBoxon the same line in every rows. The content of the second JComboBox depends on the selection of the first JComboBox.
The way I coded it now is changing the combobox content for the whole second column.
columnProfile.setCellEditor(new DefaultCellEditor(comboBoxProf))
Is there a way to have a combobox object different on every row so I can work on it everytime I select a value in the first combobox?
The number of rows is not fixed until the user hits submit. He can add and delete rows.
I've used the basic Table example from Oracle and made the changes to reflect what I'm currently doing
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
public class TableRenderDemo extends JPanel {
private boolean DEBUG = false;
JComboBox comboBox2;
JComboBox comboBox1;
public TableRenderDemo() {
super(new GridLayout(1,0));
JTable table = new JTable(new MyTableModel());
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
initColumnSizes(table);
setUpSportColumn(table, table.getColumnModel().getColumn(2));
setUpYearsColumn(table, table.getColumnModel().getColumn(3));
add(scrollPane);
table.getModel().addTableModelListener(new TableModelListener() {
public void tableChanged(TableModelEvent e) {
if (e.getColumn() == 2){
comboBox2.removeAllItems();
/*REFILL COMBOBOX WITH WHAT I NEED FOR THIS ROW ONLY*/
}
}
});
}
private void initColumnSizes(JTable table) {
MyTableModel model = (MyTableModel)table.getModel();
TableColumn column = null;
Component comp = null;
int headerWidth = 0;
int cellWidth = 0;
Object[] longValues = model.longValues;
TableCellRenderer headerRenderer =
table.getTableHeader().getDefaultRenderer();
for (int i = 0; i < 5; i++) {
column = table.getColumnModel().getColumn(i);
comp = headerRenderer.getTableCellRendererComponent(
null, column.getHeaderValue(),
false, false, 0, 0);
headerWidth = comp.getPreferredSize().width;
comp = table.getDefaultRenderer(model.getColumnClass(i)).
getTableCellRendererComponent(
table, longValues[i],
false, false, 0, i);
cellWidth = comp.getPreferredSize().width;
if (DEBUG) {
System.out.println("Initializing width of column "
+ i + ". "
+ "headerWidth = " + headerWidth
+ "; cellWidth = " + cellWidth);
}
column.setPreferredWidth(Math.max(headerWidth, cellWidth));
}
}
public void setUpSportColumn(JTable table,
TableColumn sportColumn) {
//Set up the editor for the sport cells.
comboBox1 = new JComboBox();
comboBox1.addItem("Snowboarding");
comboBox1.addItem("Rowing");
comboBox1.addItem("Knitting");
comboBox1.addItem("Speed reading");
comboBox1.addItem("Pool");
comboBox1.addItem("None of the above");
sportColumn.setCellEditor(new DefaultCellEditor(comboBox1));
DefaultTableCellRenderer renderer =
new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
sportColumn.setCellRenderer(renderer);
}
public void setUpYearsColumn(JTable table,
TableColumn yearColumn) {
comboBox2 = new JComboBox();
comboBox2.addItem("1");
comboBox2.addItem("2");
comboBox2.addItem("3");
comboBox2.addItem("4");
comboBox2.addItem("5");
comboBox2.addItem("6");
yearColumn.setCellEditor(new DefaultCellEditor(comboBox2));
//Set up tool tips for the sport cells.
DefaultTableCellRenderer renderer =
new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
yearColumn.setCellRenderer(renderer);
}
class MyTableModel extends AbstractTableModel {
private String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
private Object[][] data = {
{"Kathy", "Smith",
"Snowboarding", "1", new Boolean(false)},
{"John", "Doe",
"Rowing", "1", new Boolean(true)},
{"Sue", "Black",
"Knitting", "1", new Boolean(false)},
{"Jane", "White",
"Speed reading", "1", new Boolean(true)},
{"Joe", "Brown",
"Pool", "1", new Boolean(false)}
};
public final Object[] longValues = {"Jane", "Kathy",
"None of the above",
new Integer(20), Boolean.TRUE};
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return data.length;
}
public String getColumnName(int col) {
return columnNames[col];
}
public Object getValueAt(int row, int col) {
return data[row][col];
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public boolean isCellEditable(int row, int col) {
if (col < 2) {
return false;
} else {
return true;
}
}
public void setValueAt(Object value, int row, int col) {
if (DEBUG) {
System.out.println("Setting value at " + row + "," + col
+ " to " + value
+ " (an instance of "
+ value.getClass() + ")");
}
data[row][col] = value;
fireTableCellUpdated(row, col);
if (DEBUG) {
System.out.println("New value of data:");
printDebugData();
}
}
private void printDebugData() {
int numRows = getRowCount();
int numCols = getColumnCount();
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + data[i][j]);
}
System.out.println();
}
System.out.println("--------------------------");
}
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("TableRenderDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TableRenderDemo newContentPane = new TableRenderDemo();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
Say you had your data held in a Map<String, List<String>> with the Map's keys representing the values held by the first JComboBox, and the Map's values representing the changing values held by the 2nd column's JComboBox (the data does not need to be set up this way, but it's easy for MCVE/demonstration purposes), and call this map dataMap, then your column editor could look something like:
column1.setCellEditor(new DefaultCellEditor(combo1) {
#SuppressWarnings("unchecked")
#Override
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
// the items that will fill our JComboBox. Initially its empty
Object[] items = new Object[]{};
// get the value in the column to the left
Object column0Value = table.getValueAt(row, column - 1);
if (column0Value != null) {
// if the value is not null, then get the map's values
// and use it to fill our items array
items = dataMap.get(column0Value).toArray();
}
// get the super component, the JComboBox that is being used
// as an editor:
JComboBox<Object> superCombo = (JComboBox<Object>) super.getTableCellEditorComponent(table, value, isSelected,
row, column);
// create a model and fill with items
DefaultComboBoxModel<Object> comboModel = new DefaultComboBoxModel<>(items);
// set the cell editor's model and return
superCombo.setModel(comboModel);
return superCombo;
}
});
For example please check this MCVE as an example that uses the above cell editor and as an example of a MCVE that would work well in your future questions
import java.awt.Component;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
#SuppressWarnings("serial")
public class TableWithMultCombos extends JPanel {
private static final String[] COLUMN_NAMES = { "Day of Week", "Number" };
private Map<String, List<String>> dataMap = new LinkedHashMap<>();
private DefaultTableModel tblModel = new DefaultTableModel(COLUMN_NAMES, 5);
private JTable table = new JTable(tblModel);
private DefaultComboBoxModel<Object> combo2Model = new DefaultComboBoxModel<>();
private JComboBox<Object> combo0 = null;
private JComboBox<Object> combo1 = new JComboBox<>(combo2Model);
public TableWithMultCombos() {
dataMap.put("Monday", Arrays.asList(new String[] { "Mon - 1", "Mon - 2", "Mon - 3", "Mon - 4" }));
dataMap.put("Tuesday", Arrays.asList(new String[] { "Tues - 1", "Tues - 2", "Tues - 3", "Tues - 4" }));
dataMap.put("Wednesday", Arrays.asList(new String[] { "Wed - 1", "Wed - 2", "Wed - 3", "Wed - 4" }));
dataMap.put("Thursday", Arrays.asList(new String[] { "Thurs - 1", "Thurs - 2", "Thurs - 3", "Thurs - 4" }));
dataMap.put("Friday", Arrays.asList(new String[] { "Fri - 1", "Fri - 2", "Fri - 3", "Fri - 4" }));
combo0 = new JComboBox<>(dataMap.keySet().toArray());
TableColumn column0 = table.getColumnModel().getColumn(0);
column0.setCellEditor(new DefaultCellEditor(combo0));
TableColumn column1 = table.getColumnModel().getColumn(1);
column1.setCellEditor(new DefaultCellEditor(combo1) {
#SuppressWarnings("unchecked")
#Override
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
// the items that will fill our JComboBox. Initially its empty
Object[] items = new Object[]{};
// get the value in the column to the left
Object column0Value = table.getValueAt(row, column - 1);
if (column0Value != null) {
// if the value is not null, then get the map's values
// and use it to fill our items array
items = dataMap.get(column0Value).toArray();
}
// get the super component, the JComboBox that is being used
// as an editor:
JComboBox<Object> superCombo = (JComboBox<Object>) super.getTableCellEditorComponent(table, value, isSelected,
row, column);
// create a model and fill with items
DefaultComboBoxModel<Object> comboModel = new DefaultComboBoxModel<>(items);
// set the cell editor's model and return
superCombo.setModel(comboModel);
return superCombo;
}
});
table.setFillsViewportHeight(true);
add(new JScrollPane(table));
}
private static void createAndShowGui() {
TableWithMultCombos mainPanel = new TableWithMultCombos();
JFrame frame = new JFrame("TableWithMultCombos");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
With refrence To The Question! By abg and answer By mKorBel.
And Using J2s Auto Complete Combo Box!
The Code in the Answer By mKorBel For My Case Is Not Working When I use Item Class instead of String for ArrayList items.
Vector<Vector<String>> comboData=util.GetComboData();
ArrayList<String> listSomeString = util.GetListForComboBox(comboData);
Java2sAutoComboBox comboBox = new Java2sAutoComboBox(listSomeString);
comboBox.setDataList(listSomeString);
column.setCellEditor(new DefaultCellEditor(comboBox));
The Code For Function GetListForComboBox is as follows
public ArrayList GetListForComboBox(Vector<Vector<String>> comboData) {
//Vector model = new Vector();
ArrayList<Item_> listSomeString = new ArrayList<Item_>();
try {
String strdata;
for (int i = 0; i < comboData.size(); i++) {
String id = comboData.get(i).elementAt(0).toString();
if (comboData.get(i).elementAt(1) != null) {
strdata = comboData.get(i).elementAt(1).toString();
} else {
strdata = "";
}
Item_ it = new Item_(id, strdata);
//model.addElement(it);
listSomeString.add(it);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return listSomeString;
}
The Code for Item_ class is as follows
public class Item_
{
private String description;
private String id;
public Item_( String id,String description)
{
this.description = description;
this.id = id;
}
public String getId()
{ return id;
}
public String getDescription()
{ return description;
}
public String toString()
{ return description;
}
public void setDescription(String desc)
{ description=desc;
}
}
no idea, have to create an HashMap or MutableComboBoxModel, because AutoComplete is strictly based on Array, have to change constructor
my curiosity about Bug (I can't be able to simulating this issue), is presented from this code too (disable comboBox.setRenderer(new ItemRenderer());)
import java.awt.BorderLayout;
import javax.swing.DefaultCellEditor;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.plaf.basic.BasicComboBoxRenderer;
public class TableRenderDemo extends JPanel {
private static final long serialVersionUID = 1L;
public TableRenderDemo() {
super(new BorderLayout(5, 5));
final JTable table = new JTable(new MyTableModel());
table.setPreferredScrollableViewportSize(table.getPreferredSize());
table.setFillsViewportHeight(true);
table.setRowHeight(20);
JScrollPane scrollPane = new JScrollPane(table);
initColumnSizes(table);
setUpSportColumn(table, table.getColumnModel().getColumn(2));
add(scrollPane, BorderLayout.CENTER);
JButton resetButton = new JButton("Reset to default");
resetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < table.getRowCount(); i++) {
table.getModel().setValueAt("None of the above", i, 2);
}
}
});
add(resetButton, BorderLayout.SOUTH);
}
private void initColumnSizes(JTable table) {
MyTableModel model = (MyTableModel) table.getModel();
TableColumn column = null;
Component comp = null;
int headerWidth = 0;
int cellWidth = 0;
Object[] longValues = model.longValues;
TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();
for (int i = 0; i < 5; i++) {
column = table.getColumnModel().getColumn(i);
comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
headerWidth = comp.getPreferredSize().width;
comp = table.getDefaultRenderer(model.getColumnClass(i)).getTableCellRendererComponent(table, longValues[i], false, false, 0, i);
cellWidth = comp.getPreferredSize().width;
column.setPreferredWidth(Math.max(headerWidth, cellWidth));
}
}
private void setUpSportColumn(JTable table, TableColumn sportColumn) {
ArrayList<String> listSomeString = new ArrayList<String>();
listSomeString.add("Snowboarding");
listSomeString.add("Rowing");
listSomeString.add("Knitting");
listSomeString.add("Speed reading");
listSomeString.add("Pool");
listSomeString.add("None of the above");
JComboBox comboBox = new JComboBox();
comboBox.addItem(new Item(1, "-"));
comboBox.addItem(new Item(2, "Snowboarding"));
comboBox.addItem(new Item(3, "Rowing"));
comboBox.addItem(new Item(4, "Knitting"));
comboBox.addItem(new Item(5, "Speed reading"));
comboBox.addItem(new Item(6, "Pool"));
comboBox.addItem(new Item(7, "None of the above"));
comboBox.setMaximumRowCount(3);
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox comboBox = (JComboBox) e.getSource();
Item item = (Item) comboBox.getSelectedItem();
System.out.println(item.getId() + " : " + item.getDescription());
}
});
comboBox.setRenderer(new ItemRenderer());
sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
sportColumn.setCellRenderer(renderer);
}
class ItemRenderer extends BasicComboBoxRenderer {
#Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value != null) {
Item item = (Item) value;
setText(item.getDescription().toUpperCase());
}
if (index == -1) {
Item item = (Item) value;
setText("" + item.getId());
}
return this;
}
}
class Item {
private int id;
private String description;
public Item(int id, String description) {
this.id = id;
this.description = description;
}
public int getId() {
return id;
}
public String getDescription() {
return description;
}
#Override
public String toString() {
return description;
}
}
class MyTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private String[] columnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
private Object[][] data = {{"Kathy", "Smith", "Snowboarding", new Integer(5), false},
{"John", "Doe", "Rowing", new Integer(3), true}, {"Sue", "Black", "Knitting", new Integer(2), false},
{"Jane", "White", "Speed reading", new Integer(20), true}, {"Joe", "Brown", "Pool", new Integer(10), false}};
public final Object[] longValues = {"Jane", "Kathy", "None of the above", new Integer(20), Boolean.TRUE};
#Override
public int getColumnCount() {
return columnNames.length;
}
#Override
public int getRowCount() {
return data.length;
}
#Override
public String getColumnName(int col) {
return columnNames[col];
}
#Override
public Object getValueAt(int row, int col) {
return data[row][col];
}
#Override
public Class<?> getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
#Override
public boolean isCellEditable(int row, int col) {
if (col < 2) {
return false;
} else {
return true;
}
}
#Override
public void setValueAt(Object value, int row, int col) {
data[row][col] = value;
fireTableCellUpdated(row, col);
System.out.println("New value of data: " + getValueAt(row, col));
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("TableRenderDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TableRenderDemo newContentPane = new TableRenderDemo();
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
have to play with Caret (quick implementations for Caret, sorry too lazy, without any idea), otherwise all editor is selected, backspace selected 1st Item by default
import java.awt.BorderLayout;
import javax.swing.DefaultCellEditor;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;
import javax.swing.JList;
import javax.swing.JTextField;
import javax.swing.plaf.basic.BasicComboBoxRenderer;
import javax.swing.text.JTextComponent;
public class TableRenderDemo extends JPanel {
private static final long serialVersionUID = 1L;
public TableRenderDemo() {
super(new BorderLayout(5, 5));
final JTable table = new JTable(new MyTableModel());
table.setPreferredScrollableViewportSize(table.getPreferredSize());
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
initColumnSizes(table);
setUpSportColumn(table, table.getColumnModel().getColumn(2));
add(scrollPane, BorderLayout.CENTER);
JButton resetButton = new JButton("Reset to default");
resetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < table.getRowCount(); i++) {
table.getModel().setValueAt("None of the above", i, 2);
}
}
});
add(resetButton, BorderLayout.SOUTH);
}
private void initColumnSizes(JTable table) {
MyTableModel model = (MyTableModel) table.getModel();
TableColumn column = null;
Component comp = null;
int headerWidth = 0;
int cellWidth = 0;
Object[] longValues = model.longValues;
TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();
for (int i = 0; i < 5; i++) {
column = table.getColumnModel().getColumn(i);
comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
headerWidth = comp.getPreferredSize().width;
comp = table.getDefaultRenderer(model.getColumnClass(i)).getTableCellRendererComponent(table, longValues[i], false, false, 0, i);
cellWidth = comp.getPreferredSize().width;
column.setPreferredWidth(Math.max(headerWidth, cellWidth));
}
}
private void setUpSportColumn(JTable table, TableColumn sportColumn) {
ArrayList<String> listSomeString = new ArrayList<String>();
listSomeString.add("-");
listSomeString.add("Snowboarding");
listSomeString.add("Rowing");
listSomeString.add("Knitting");
listSomeString.add("Speed reading");
listSomeString.add("Pool");
listSomeString.add("None of the above");
AutoComboBox comboBox = new AutoComboBox(listSomeString);
comboBox.setDataList(listSomeString);
comboBox.setMaximumRowCount(3);
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox comboBox = (JComboBox) e.getSource();
System.out.println(comboBox.getSelectedItem());
}
});
JTextComponent editor = ((JTextField) comboBox.getEditor().getEditorComponent());
editor.setCaretPosition(editor.getCaretPosition());
editor.moveCaretPosition(0);
editor.addFocusListener(focsListener);
sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
sportColumn.setCellRenderer(renderer);
}
private FocusListener focsListener = new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
dumpInfo(e);
}
#Override
public void focusLost(FocusEvent e) {
//dumpInfo(e);
}
private void dumpInfo(FocusEvent e) {
//System.out.println("Source : " + name(e.getComponent()));
//System.out.println("Opposite : " + name(e.getOppositeComponent()));
//System.out.println("Temporary: " + e.isTemporary());
final Component c = e.getComponent();
if (c instanceof JFormattedTextField) {
EventQueue.invokeLater(new Runnable() {
public void run() {
((JFormattedTextField) c).requestFocus();
((JFormattedTextField) c).setText(((JFormattedTextField) c).getText());
((JFormattedTextField) c).selectAll();
}
});
} else if (c instanceof JTextField) {
EventQueue.invokeLater(new Runnable() {
public void run() {
((JTextField) c).requestFocus();
((JTextField) c).setText(((JTextField) c).getText());
((JTextField) c).selectAll();
}
});
}
}
private String name(Component c) {
return (c == null) ? null : c.getName();
}
};
class ItemRenderer extends BasicComboBoxRenderer {
#Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value != null) {
}
if (index == -1) {
}
return this;
}
}
class MyTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private String[] columnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
private Object[][] data = {{"Kathy", "Smith", "Snowboarding", new Integer(5), false},
{"John", "Doe", "Rowing", new Integer(3), true}, {"Sue", "Black", "Knitting", new Integer(2), false},
{"Jane", "White", "Speed reading", new Integer(20), true}, {"Joe", "Brown", "Pool", new Integer(10), false}};
public final Object[] longValues = {"Jane", "Kathy", "None of the above", new Integer(20), Boolean.TRUE};
#Override
public int getColumnCount() {
return columnNames.length;
}
#Override
public int getRowCount() {
return data.length;
}
#Override
public String getColumnName(int col) {
return columnNames[col];
}
#Override
public Object getValueAt(int row, int col) {
return data[row][col];
}
#Override
public Class<?> getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
#Override
public boolean isCellEditable(int row, int col) {
if (col < 2) {
return false;
} else {
return true;
}
}
#Override
public void setValueAt(Object value, int row, int col) {
data[row][col] = value;
fireTableCellUpdated(row, col);
System.out.println("New value of data: " + getValueAt(row, col));
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("TableRenderDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TableRenderDemo newContentPane = new TableRenderDemo();
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
I know this is an old question but in case it can help someone out there, here is how to do what OP asked:
In Java2sAutoCombobox, replace the function setSelectedValue(Object obj) by this one instead:
void setSelectedValue(String str)
{
if(!isFired)
{
Object objectToSelect = null;
for(Object obj: getDataList())
{
if( obj.toString().equals(str) )
{
objectToSelect = obj;
break;
}
}
isFired = true;
setSelectedItem(objectToSelect);
fireItemStateChanged(new ItemEvent(this, 701, selectedItemReminder,
1));
isFired = false;
}
}
By doing this, JComboBox.setSelectedItem() will select the object from the datalist instead of its string representation.
I would like to set a tooltip value for the values in a custom combo box. Basically, my combobox contains a list of initials of people - when they hover over i want it to display the fullname of the person. My combo box is basically a cell/column of a JTable that has its own TableCellRenderer and DefaultCellEditor. The list is a JList (inner class within the model) - iv tried setting the 'setToolTipText' method directly but that doesnt seem to work.
Here is the code:
*Code within the JTable: *
public void setupUserCombo(Container container){
TableColumn col = getColumnModel().getColumn(3);
Set<ComboUser> values = new LinkedHashSet<ComboUser>();
ComboUser comboUser = new ComboUser(new User("Test User"));
values.add(comboUser);
col.setCellEditor(new MyComboBoxEditor((ComboUser[])values.toArray(new ComboUser[0])));
col.setCellRenderer(new MyComboBoxRenderer((ComboUser[])values.toArray(new ComboUser[0])));
repaint();
}
public class MyComboBoxRenderer extends JComboBox implements TableCellRenderer {
private static final long serialVersionUID = 1L;
public MyComboBoxRenderer(ComboUser[] items) {
super(items);
repaint();
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (value != null){
System.out.println("Setting tooltip");
((ComboUser)value).setToolTipText("TESTING!!");
}
setSelectedItem(value);
return this;
}
}
public class MyComboBoxEditor extends DefaultCellEditor {
private static final long serialVersionUID = 1L;
public MyComboBoxEditor(ComboUser[] items) {
super(new JComboBox(items));
}
}
*Subclass within the model: *
public class ComboUser extends JLabel{
private User user;
public ComboUser(User user){
if (user != null){
this.user = user;
} else {
this.user = new User("");
}
}
#Override
public String toString() {
return user.getInitials();
}
If you want tooltips in the editing combobox, you'll have to so in a custom renderer of that combobox. Below is a short example:
// some data
User[] users = new User[] {
new User("Clara Zetkin", "CZ"),
new User("Rosa Luxemburg", "RL"),
new User("Susan Sontag", "SS"),
};
// the renderer for use in the editor
ListCellRenderer comboRenderer = new DefaultListCellRenderer() {
#Override
public Component getListCellRendererComponent(JList<?> list,
Object value, int index, boolean isSelected,
boolean cellHasFocus) {
if (value instanceof User) {
setToolTipText(((User) value).getName());
value = ((User) value).getInitials();
} else {
setToolTipText(null);
}
return super.getListCellRendererComponent(list, value, index, isSelected,
cellHasFocus);
}
};
JComboBox editingCombo = new JComboBox(users);
editingCombo.setRenderer(comboRenderer);
JTable table = new JTable(3, 2);
// set up the editor for the first column
table.getColumnModel().getColumn(0).setCellEditor(new DefaultCellEditor(editingCombo));
// the renderer to use in the table
TableCellRenderer renderer = new DefaultTableCellRenderer() {
#Override
protected void setValue(Object value) {
if (value instanceof User) {
setToolTipText(((User) value).getInitials());
value = ((User) value).getName();
} else {
setToolTipText(null);
}
super.setValue(value);
}
};
table.getColumnModel().getColumn(0).setCellRenderer(renderer);
see JTable tutorial, test code examples, for example
import java.awt.BorderLayout;
import javax.swing.DefaultCellEditor;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.plaf.basic.BasicComboBoxRenderer;
public class TableRenderDemo extends JPanel {
private static final long serialVersionUID = 1L;
public TableRenderDemo() {
super(new BorderLayout(5, 5));
final JTable table = new JTable(new MyTableModel());
table.setPreferredScrollableViewportSize(table.getPreferredSize());
table.setFillsViewportHeight(true);
table.setRowHeight(20);
JScrollPane scrollPane = new JScrollPane(table);
initColumnSizes(table);
setUpSportColumn(table, table.getColumnModel().getColumn(2));
add(scrollPane, BorderLayout.CENTER);
JButton resetButton = new JButton("Reset to default");
resetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < table.getRowCount(); i++) {
table.getModel().setValueAt("None of the above", i, 2);
}
}
});
add(resetButton, BorderLayout.SOUTH);
}
private void initColumnSizes(JTable table) {
MyTableModel model = (MyTableModel) table.getModel();
TableColumn column = null;
Component comp = null;
int headerWidth = 0;
int cellWidth = 0;
Object[] longValues = model.longValues;
TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();
for (int i = 0; i < 5; i++) {
column = table.getColumnModel().getColumn(i);
comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
headerWidth = comp.getPreferredSize().width;
comp = table.getDefaultRenderer(model.getColumnClass(i)).getTableCellRendererComponent(table, longValues[i], false, false, 0, i);
cellWidth = comp.getPreferredSize().width;
column.setPreferredWidth(Math.max(headerWidth, cellWidth));
}
}
private void setUpSportColumn(JTable table, TableColumn sportColumn) {
ArrayList<String> listSomeString = new ArrayList<String>();
listSomeString.add("Snowboarding");
listSomeString.add("Rowing");
listSomeString.add("Knitting");
listSomeString.add("Speed reading");
listSomeString.add("Pool");
listSomeString.add("None of the above");
JComboBox comboBox = new JComboBox();
comboBox.addItem(new Item(1, "-"));
comboBox.addItem(new Item(2, "Snowboarding"));
comboBox.addItem(new Item(3, "Rowing"));
comboBox.addItem(new Item(4, "Knitting"));
comboBox.addItem(new Item(5, "Speed reading"));
comboBox.addItem(new Item(6, "Pool"));
comboBox.addItem(new Item(7, "None of the above"));
comboBox.setMaximumRowCount(3);
comboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox comboBox = (JComboBox) e.getSource();
Item item = (Item) comboBox.getSelectedItem();
System.out.println(item.getId() + " : " + item.getDescription());
}
});
//comboBox.setRenderer(new ItemRenderer());
sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
sportColumn.setCellRenderer(renderer);
}
class ItemRenderer extends BasicComboBoxRenderer {
#Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value != null) {
Item item = (Item) value;
setText(item.getDescription().toUpperCase());
}
if (index == -1) {
Item item = (Item) value;
setText("" + item.getId());
}
return this;
}
}
class Item {
private int id;
private String description;
public Item(int id, String description) {
this.id = id;
this.description = description;
}
public int getId() {
return id;
}
public String getDescription() {
return description;
}
#Override
public String toString() {
return description;
}
}
class MyTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private String[] columnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
private Object[][] data = {{"Kathy", "Smith", "Snowboarding", new Integer(5), false},
{"John", "Doe", "Rowing", new Integer(3), true}, {"Sue", "Black", "Knitting", new Integer(2), false},
{"Jane", "White", "Speed reading", new Integer(20), true}, {"Joe", "Brown", "Pool", new Integer(10), false}};
public final Object[] longValues = {"Jane", "Kathy", "None of the above", new Integer(20), Boolean.TRUE};
#Override
public int getColumnCount() {
return columnNames.length;
}
#Override
public int getRowCount() {
return data.length;
}
#Override
public String getColumnName(int col) {
return columnNames[col];
}
#Override
public Object getValueAt(int row, int col) {
return data[row][col];
}
#Override
public Class<?> getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
#Override
public boolean isCellEditable(int row, int col) {
if (col < 2) {
return false;
} else {
return true;
}
}
#Override
public void setValueAt(Object value, int row, int col) {
data[row][col] = value;
fireTableCellUpdated(row, col);
System.out.println("New value of data: " + getValueAt(row, col));
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("TableRenderDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TableRenderDemo newContentPane = new TableRenderDemo();
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
I'm working on a code in Java Swing. I have created a JComboBox in JTable. It's working :). But once I select a value and click on the save or cancel button, it has to reset to the default value (1st value in the combo box). I tried a lot of ways like combobox.setSelectedIndex(0). This isn't working.
Code:
String[] manTimeHr = { "00","01", "02", "03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23"};
String[] manTimeMin = {"00","01", "02", "03","04","05","06","07","08","09","10","11","12","13", "14", "15","16","17","18","19","20","21","22","23","24","25", "26", "27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","51","52","53","54","55","56","57","58","59"};
String[][] data = {{"-select-","-select-"}};
String[] cols = {"Hrs","Mins"};
String[][] data1 = {{"-select-","-select-"}};
String[] cols1 = {"Hrs","Mins"};
JLabel manTimeStart = new JLabel("Start From",JLabel.LEFT);
STimeTbl = new JTable(data,cols);
hrsColumn=STimeTbl.getColumnModel().getColumn(0);
minsColumn=STimeTbl.getColumnModel().getColumn(1);
manSiteStimeHrCBx = new JComboBox(manTimeHr);
manSiteStimeHrCBx.setSelectedIndex(0);
hrsColumn.setCellEditor(new DefaultCellEditor(manSiteStimeHrCBx));
manSiteStimeMinCBx = new JComboBox(manTimeMin);
manSiteStimeMinCBx.setSelectedIndex(0);
minsColumn.setCellEditor(new DefaultCellEditor(manSiteStimeMinCBx));
JLabel manTimeEnd = new JLabel("End To",JLabel.LEFT);
ETimeTbl = new JTable(data1,cols1);
hrsColumn1=ETimeTbl.getColumnModel().getColumn(0);
minsColumn1=ETimeTbl.getColumnModel().getColumn(1);
manSiteEtimeHrCBx = new JComboBox(manTimeHr);
manSiteEtimeHrCBx.setSelectedIndex(0);
hrsColumn1.setCellEditor(new DefaultCellEditor(manSiteEtimeHrCBx));
manSiteEtimeMinCBx = new JComboBox(manTimeMin);
manSiteEtimeMinCBx.setSelectedIndex(0);
minsColumn1.setCellEditor(new DefaultCellEditor(manSiteEtimeMinCBx));
.
.
.
.
if("Save".equals(e.getActionCommand())) {
try{
mSHr = Integer.parseInt((String)manSiteStimeHrCBx.getSelectedItem());
mEHr=Integer.parseInt((String)manSiteEtimeHrCBx.getSelectedItem());
mSMin=Integer.parseInt((String)manSiteStimeMinCBx.getSelectedItem());
mEMin=Integer.parseInt((String)manServEtimeMinCBx.getSelectedItem());
}catch (Exception en){
System.out.println("Main Exception : "+ en);
return;
}
if(validateBlockTime(mSHr,mEHr,mSMin,mEMin) != true)
{
System.out.println("Enter valid Time");
return;
}
manSiteStimeHrCBx.setSelectedIndex(0);
manSiteStimeMinCBx.setSelectedIndex(0);
manSiteEtimeHrCBx.setSelectedIndex(0);
manSiteEtimeMinCBx.setSelectedIndex(0);
.
.
.
private static boolean validateBlockTime(int val3, int val4, int val5, int val6){
if(val4 > val3)
return true;
else if((val4 == val3) && (val6 > val5))
return true;
else
return false;
}
JTable tutorial contains description about Combo Box as an Editor
all data are stored in the XxxTableModel
all changes in the JTable view are described in Concepts: Editors and Renderers
then you have to know that in the XxxTableModel is stored only String value (or Double or Long or Integer or Icon, depends of value stored in ComboBoxModel) for Combo Box as an Editor
result is
quick code (sorry I'm so lazy) based on tutorial code
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class TableRenderDemo extends JPanel {
private static final long serialVersionUID = 1L;
private boolean DEBUG = false;
public TableRenderDemo() {
super(new BorderLayout(5, 5));
final JTable table = new JTable(new MyTableModel());
table.setRowHeight(18);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
initColumnSizes(table);
setUpSportColumn(table, table.getColumnModel().getColumn(2));
add(scrollPane);
JButton resetButton = new JButton("Reset to default");
resetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < table.getRowCount(); i++) {
table.getModel().setValueAt("None of the above", i, 2);
}
}
});
add(resetButton, BorderLayout.SOUTH);
}
private void initColumnSizes(JTable table) {
MyTableModel model = (MyTableModel) table.getModel();
TableColumn column = null;
Component comp = null;
int headerWidth = 0;
int cellWidth = 0;
Object[] longValues = model.longValues;
TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();
for (int i = 0; i < 5; i++) {
column = table.getColumnModel().getColumn(i);
comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
headerWidth = comp.getPreferredSize().width;
comp = table.getDefaultRenderer(model.getColumnClass(i)).getTableCellRendererComponent(table, longValues[i], false, false, 0, i);
cellWidth = comp.getPreferredSize().width;
if (DEBUG) {
System.out.println("Initializing width of column " + i + ". " + "headerWidth = " + headerWidth + "; cellWidth = " + cellWidth);
}
column.setPreferredWidth(Math.max(headerWidth, cellWidth));
}
}
private void setUpSportColumn(JTable table, TableColumn sportColumn) {
JComboBox comboBox = new JComboBox();
comboBox.addItem("Snowboarding");
comboBox.addItem("Rowing");
comboBox.addItem("Knitting");
comboBox.addItem("Speed reading");
comboBox.addItem("Pool");
comboBox.addItem("None of the above");
sportColumn.setCellEditor(new DefaultCellEditor(comboBox));
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setToolTipText("Click for combo box");
sportColumn.setCellRenderer(renderer);
}
private class MyTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private String[] columnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
private Object[][] data = {
{"Kathy", "Smith", "Snowboarding", new Integer(5), false},
{"John", "Doe", "Rowing", new Integer(3), true},
{"Sue", "Black", "Knitting", new Integer(2), false},
{"Jane", "White", "Speed reading", new Integer(20), true},
{"Joe", "Brown", "Pool", new Integer(10), false}
};
public final Object[] longValues = {"Jane", "Kathy", "None of the above", new Integer(20), Boolean.TRUE};
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return data.length;
}
#Override
public String getColumnName(int col) {
return columnNames[col];
}
public Object getValueAt(int row, int col) {
return data[row][col];
}
#Override
public Class<?> getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
#Override
public boolean isCellEditable(int row, int col) {
if (col < 2) {
return false;
} else {
return true;
}
}
#Override
public void setValueAt(Object value, int row, int col) {
data[row][col] = value;
fireTableCellUpdated(row, col);
System.out.println(getValueAt(row, col));
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("TableRenderDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TableRenderDemo newContentPane = new TableRenderDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
output from AbstractTableModel, code line 135th.
run:
None of the above
None of the above
None of the above
None of the above
None of the above
BUILD SUCCESSFUL (total time: 37 seconds)
I'm working on a program for a little store. When I click the button "Report", it must show a Table, like this one:
Column names "A", "B"..."N", must be the names of the employees. But I can't figure out how.
Here is my code:
public void Inform()
{
String[] employee;
String[] product[];
this.setLayout(null);
Inform=new JTable(nulo, employee.length);
model = new DefaultTableModel() {
private static final long serialVersionUID = 1L;
#Override
public int getColumnCount() {
return 1;
}
#Override
public boolean isCellEditable(int row, int col) {
return false;
}
#Override
public int getRowCount() {
return Inform.getRowCount();
}
};
headerTable = new JTable(model);
for (int i = 0; i < Inform.getRowCount(); i++)
headerTable.setValueAt(product[i], i, 0);
headerTable.setShowGrid(false);
headerTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
headerTable.setPreferredScrollableViewportSize(new Dimension(50, 0));
headerTable.getColumnModel().getColumn(0).setPreferredWidth(50);
scrollPane = new JScrollPane(Inform);
scrollPane.setRowHeaderView(headerTable);
scrollPane.setBounds(5,5,500,500);
scrollPane.setEnabled(false);
this.add(scrollPane);
}
Employee and product variates depending how many are entered. nulo is how many products are ready to sell.
You should add getColumnName() in your TableModel:
String[] employee = {"Employee 1", "Employee 2"};
#Override
public String getColumnName(int index) {
return employee[index];
}
In your case this could be:
model = new DefaultTableModel() {
private static final long serialVersionUID = 1L;
String[] employee = {"Employee 1", "Employee 2"};
#Override
public int getColumnCount() {
return employee.length;
}
#Override
public boolean isCellEditable(int row, int col) {
return false;
}
#Override
public int getRowCount() {
return Inform.getRowCount();
}
#Override
public String getColumnName(int index) {
return employee[index];
}
};
And here is a fully working example:
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
public class TableNamesTest extends JFrame {
public TableNamesTest() {
DefaultTableModel model = new DefaultTableModel() {
String[] employee = {"emp 1", "emp 2"};
#Override
public int getColumnCount() {
return employee.length;
}
#Override
public String getColumnName(int index) {
return employee[index];
}
};
JTable table = new JTable(model);
add(new JScrollPane(table));
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new TableNamesTest();
}
}
Here is the example from the oracle website, you can load the names you want for your columns into an array, then pass the array to the JTable
String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
//Then the Table is constructed using these data and columnNames:
JTable table = new JTable(data, columnNames);
The resulting table looks like this:
Link to tutorial on JTables: http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#data
Try this:
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
public class Class1 extends JFrame{
static JTable table;
static String[] Employees = {"Employee1","Employee2","Employee3","Employee4"};
static int NumberOfRows=4;
static int NumberOfColumns=4;
public static void main(String[] args){
table = new JTable(NumberOfRows,NumberOfColumns);
for(int i=0;i<Employees.length;i++){
TableColumn tc = table.getColumnModel().getColumn(i);
tc.setHeaderValue(Employees[i]);
DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer();
dtcr.setHorizontalAlignment(SwingConstants.CENTER); //For Aligning the Elements of all columns to CENTER
tc.setCellRenderer(dtcr);
}
JFrame frame = new JFrame();
frame.add(new JScrollPane(table));
frame.setSize(300,300);
frame.setVisible(true);
}
}`
This is more of a manual approach but it works for me.
JTabel TABLE = new JTable();
JTableHeader HEADER = TABLE.getTableHeader();
TableColumnModel TMC = HEADER.getColumnModel();
TableColumn TC = TMC.getColumn(0);
TC.setHeaderValue("Person 1");
TableColumn TC1 = TMC.getColumn(1);
TC1.setHeaderValue("Person 2");
HEADER.repaint();
TABLE.getTableHeader().repaint();