Java JComboBox icon - java

Displaying data in a JTable. One column serves as a field Checkbox. The problem is that instead of the icon appears in the display ChceckBox true / false. How do I fix this?
Add data:
private DefaultTableModel headermodel = new DefaultTableModel();
private JScrollPane scrollHeader = new JScrollPane();
private JTable headerTable = new JTable();
public void loadHead(){
header = model.getHead();
int ids=0;
int id=1;
for(String head: header) {
headermodel.addRow(new Object[]{id,head});
headerMap.put(ids,head);
id++;
ids++;
count++;
}
header.clear();
}
and display data in JTable:
headerTable = new JTable(headermodel);
headermodel.addColumn("Lp.");
headermodel.addColumn("Column Name");
headermodel.addColumn("Constraint");
headermodel.addColumn("Sum");
scrollHeader = new JScrollPane(headerTable);
TableColumnModel tcm = headerTable.getColumnModel();
tcm.getColumn(2).setCellEditor(new DefaultCellEditor(new JCheckBox()));
tcm.getColumn(3).setCellEditor(new DefaultCellEditor(new JCheckBox()));
tcm.getColumn(3).setCellRenderer(headerTable.getDefaultRenderer(boolean.class));
add(scrollHeader);

The model's getColumnClass(int columnIndex) method should return Boolean.class for the appropriate column index so that the renderer knows to render a check box for that column. For example,...
DefaultTableModel headermodel = new DefaultTableModel(){
#Override
public Class<?> getColumnClass(int columnNumber) {
if (columnNumber == 2 || columnNumber == 3) {
return Boolean.class;
} else {
return super.getColumnClass(columnNumber);
}
}
}
You shouldn't have to set the cell renderer for these columns for this since the default cell renderer will handle Boolean.class appropriately.

Related

A JComboBox in a specific cell in JTable

I would like to know how to set up a JComboBox in a particular cell in a JTable.
I have seen people using TableColumn setCellEditor(new DefaultCellEditor(comboBox)).
But this is for an entire column, I would like a specific cell.
So maybe I should do a custom TableCellEditor that would fit my needs, but I am a little lost on how to do it...
The goal of this is to manage filters on parameters. There are two kinds of filters:
The one that compares two values, for instance: number of balloons > 5
The one that will say is a value is inside a range of value, for instance: parameter name is inside {"one", "two", "three", "seven"}.
screenshot of my JTable:
As we can see in the picture, when there is the "comparator" "is among", we would need a JComboBox in cell[0][2] to choose the values of the range within a complete set of fields.
While cell[1][2] does not need a JComboBox, but just an editable cell.
I hope I have been clear and thank you for your help.
EDIT:
I was able to display a JComboBox only to realize, I couldn't select multiple values on it. So now I am trying to display a JList instead of a ComboBox.
But when I click on the cell, the JList is not displayed, I don't know why.
Here is my code:
JTable tableParametersFilter = new JTable(modelParametersFilter){
// Determine editor to be used by row
public TableCellEditor getCellEditor(int row, int column)
{
int modelColumn = convertColumnIndexToModel( column );
int modelRow = convertRowIndexToModel( row );
Parameter_Filter pf = view.listParameter_Filter.get(modelRow);
if(modelColumn == 2 && pf instanceof Parameter_Filter_To_List_Of_Fields) {
Parameter_Filter_To_List_Of_Fields pftlof = (Parameter_Filter_To_List_Of_Fields)pf;
JList<String> list = new JList<String>(pftlof.list_of_fields_total_names);
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
list.setLayoutOrientation(JList.VERTICAL_WRAP);
list.setVisibleRowCount(-1);
return new TableCellEditor() {
#Override
public boolean stopCellEditing() {
return false;
}
#Override
public boolean shouldSelectCell(EventObject anEvent) {
return false;
}
#Override
public void removeCellEditorListener(CellEditorListener l) {
}
#Override
public boolean isCellEditable(EventObject anEvent) {
return true;
}
#Override
public Object getCellEditorValue() {
return list.getSelectedValuesList().toString();
}
#Override
public void cancelCellEditing() {
}
#Override
public void addCellEditorListener(CellEditorListener l) {
}
#Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
return list;
}
};
}
return super.getCellEditor(row, column);
}
};
Any suggestions?
I have solved my problem.
I have not been able to add multiple choice JComboBox, or a displayable JList on the Cell of the Jtable.
Instead, I have used a JOptionPane that displayed a JList.
Here's the code:
tableParametersFilter.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
JTable target = (JTable)e.getSource();
int row = target.getSelectedRow();
int column = target.getSelectedColumn();
if(column == 2){
Parameter_Filter pf = view.listParameter_Filter.get(row);
if(pf instanceof Parameter_Filter_To_List_Of_Fields) {
Parameter_Filter_To_List_Of_Fields pftlof = (Parameter_Filter_To_List_Of_Fields) pf;
JList<String> jlist = new JList<String>(pftlof.list_of_fields_total_names);
String StringOfIntArray = (String) tableParametersFilter.getValueAt( row, 2);
int[] list_parameter_id = Statique.StringOfIntArrayToIntegerArray(StringOfIntArray);
if(list_parameter_id.length < jlist.getModel().getSize()) {
int[] list_places = pftlof.getPlaceOfParameters(list_parameter_id);
for(int i = 0; i < list_places.length; i++) {
jlist.setSelectedIndices(list_places);
}
}
JScrollPane scrollPane = new JScrollPane(jlist);
scrollPane.setPreferredSize( new Dimension( 500, 500 ) );
JOptionPane.showMessageDialog(
null, scrollPane, "Multi-Select Example", JOptionPane.PLAIN_MESSAGE);
int[] SelectedIndices = jlist.getSelectedIndices();
Integer[] listParametersId = new Integer[SelectedIndices.length];
for(int i = 0; i < SelectedIndices.length; i++) {
int id = pftlof.list_of_fields_Total[SelectedIndices[i]].id;
try {
Parameter p = Parameter.getParameter(
id,
Parameter_Filter_To_List_Of_Fields.getTotal_Parameter_In_Parameter_Filter_To_List_Of_Fields());
listParametersId[i] = p.id;
} catch (NoSuchFieldException e1) {
e1.printStackTrace();
}
}
System.out.println(Arrays.toString(listParametersId));
tableParametersFilter.setValueAt(Arrays.toString(listParametersId), row, 2);
}
}
}
}

Preventing columns from moving on delete in JTable

I'm trying to implement a checkbox interface which allows a user to show/hide columns in a JTable, but when I remove the column, the column seems to move position and there is no way of knowing 100% where the columns are. The table is built with this code:
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
String[] columnNames = {"Artist","Track","Album","Genre","Year","Filetype"};
for (String column : columnNames) {
model.addColumn(column);
}
table.createDefaultColumnsFromModel();
table.getTableHeader().setReorderingAllowed(false);
Here's the code I have for implementing the checkbox listeners:
if (e.getSource() == artist) {
if (!artist.isSelected()) {
table.removeColumn(table.getColumnModel().getColumn(0));
} else {
table.addColumn(table.getColumnModel().getColumn(0));
}
}
if (e.getSource() == trackName) {
if (!trackName.isSelected()) {
table.removeColumn(table.getColumnModel().getColumn(1));
} else {
table.addColumn(table.getColumnModel().getColumn(1));
}
}
/* etc */
You can to use the Table Column Manager.
It will manager the hiding/showing of the table columns for you.

Select Value of Checkbox JTable on button click

I have a JTable in which the last column is Checkbox(multiple select). I want to get the values of the rows selected on a particular button click. Only the values which are checked are needed. Any idea regarding this?
Object[] columnNamesTest = {"Request No","Assigned To","Copy Data","Updated Req Number"};
Object[][] rowDataTest = {
{"111111", "ABC",false,""},
{"222222", "XYZ", true,"999999"},
{"333333", "LMN",true,"444444"},
{"444444", "PQR", false,"555555"}
};
DefaultTableModel model = new DefaultTableModel(rowDataTest, columnNamesTest);
JTable table = new JTable(model){
private static final long serialVersionUID = 1L;
#Override
public Class getColumnClass(int column) {
switch (column) {
case 0:
return String.class;
case 1:
return String.class;
case 2:
return Boolean.class;
default:
return String.class;
}
}
#Override
public boolean isCellEditable(int row, int column) {
//Only the third column
return column == 2;
}
};
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setAlignmentX(Component.LEFT_ALIGNMENT);
container.add(scrollPane);
I want to get the values of the rows selected on a particular button click.Only the values which are checked are needed.
Simply check the value of third column and get it the desired value from DefaultTableModel.
sample code:
JButton button = new JButton("Show selcted records");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
for (int i = 0; i < model.getRowCount(); i++) {
Boolean value = (Boolean) model.getValueAt(i, 2);// check state
if (value) {
System.out.println(model.getValueAt(i, 1));// second column value
}
}
}
});

JCheckBox in a Jtable's column isn't working [duplicate]

Shouldn't the new Boolean appear as a checkbox? It's showing up as a true/false string value instead. This is how I'm populating the data:
Object[] columnNames4 = {"Name", "City", "Checkbox"};
Object[][] data = {
{"john smith",
"x", new Boolean(false)},
{"jenny m",
"y", new Boolean(false)}
};
JTable table4 = new JTable(data, columnNames4);
JScrollPane S3 = new JScrollPane(table4);
S3.setPreferredSize(new Dimension(300, 300));
Create a subclass ofAbstractTableModel and return Boolean.class in the Method getColumnClass() for the column you want.
You need to setup a TableCellRenderer and TableCellEditor
see http://docs.oracle.com/javase/tutorial/uiswing/components/table.html
Once you have defined the render's / editor's you can
define the render/editor as the default render for a Type
table.setDefaultRenderer(Boolean.class, new MyBooleanRender());
table.setDefaultEditor(Boolean.class, new MyBooleanCellEditor());
define the render / editor to a column
TableColumnModel tcm = table.getColumnModel();
tcm.getColumn(4).setCellRenderer(new MyBooleanRender());
tcm.getColumn(4).setCellEditor(new MyBooleanCellEditor());
You can define a checkbox cellRender like:
public class MyBooleanRender extends JCheckBox
implements TableCellRenderer {
private JCheckBox checkBox = this;
/**
* #see javax.swing.table.TableCellRenderer#getTableCellRendererComponent
* (javax.swing.JTable, java.lang.Object, boolean, boolean, int, int)
*/
public Component getTableCellRendererComponent(
JTable tbl,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column) {
boolean val = false;
if (Common.isEmpty(value)) {
checkBox.setSelected(false);
} else {
try {
val = ((Boolean) value).booleanValue();
} catch (Exception e) {
}
checkBox.setSelected(val);
}
if (Common.OPTIONS.highlightEmpty.isSelected() && value == Common.MISSING_VALUE) {
checkBox.setBackground(Common.EMPTY_COLOR);
} else if (value == Common.MISSING_REQUIRED_VALUE) {
checkBox.setBackground(Common.MISSING_COLOR);
} else {
...
}
checkBox.setSelected(val);
return checkBox;
}
}
For a checkboxEditor, you can use the DefaultCellEditor class.

TableModelListener and multiple column validation

This is the first time for me to post here, so sorry if I made some mistake.
I am working on a JTable which column data have to verify some parameters, for example:
Column 3 values > 30
Column 4 values > 10
Column 5 values > 4
Also the first 2 columns are filled "automatically", putting 0s in the rest of the columns.
If that data is correct, in the Column 5 I would show an image of a tick, otherwise, I would show an image of a warning.
For verifying this I use the following code
ImageIcon accept = new javax.swing.ImageIcon(getClass().getResource("/resources/accept.png"));
ImageIcon deny = new javax.swing.ImageIcon(getClass().getResource("/resources/exclamation.png"));
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
double d1 = Double.valueOf(jTable.getValueAt(row, 2).toString());
double d2 = Double.valueOf(jT.getValueAt(row, 3).toString());
double d3 = Double.valueOf(jT.getValueAt(row, 4).toString());
if(d1>MAX_A||d2>MAX_B||d3>MAX_C){
jTable.setValueAt(deny, row, 5);
}
else{
jTable.setValueAt(accept, row, 5);
}
}
The problem of this code is that returns a Stack Overflow, and I don't know how to handle this.
Is there any other way to implement some verifier on a table that implies multiple cells?
Thanks in advance.
The problem of this code is that
returns a Stack Overflow, and I don't
know how to handle this.
The problem is that your code sets a value in the model listener so another tableChanged event is generated. Your code should be something like:
if (e.getColumn() != 5)
// do your code
I don't see a problem using a TableModelListener to dynamically set the value of a column based on data in another column. Here is a simple example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class TableProcessing extends JPanel implements TableModelListener
{
public TableProcessing()
{
String[] columnNames = {"Item", "Quantity", "Price", "Cost"};
Object[][] data =
{
{"Bread", new Integer(1), new Double(1.11), new Double(1.11)},
{"Milk", new Integer(1), new Double(2.22), new Double(2.22)},
{"Tea", new Integer(1), new Double(3.33), new Double(3.33)},
{"Cofee", new Integer(1), new Double(4.44), new Double(4.44)}
};
DefaultTableModel model = new DefaultTableModel(data, columnNames)
{
// Returning the Class of each column will allow different
// renderers to be used based on Class
#Override
public Class getColumnClass(int column)
{
return getValueAt(0, column).getClass();
}
// The Cost is not editable
#Override
public boolean isCellEditable(int row, int column)
{
return (column == 3) ? false : true;
}
};
model.addTableModelListener( this );
JTable table = new JTable( model );
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane( table );
add( scrollPane );
String[] items = { "Bread", "Milk", "Tea", "Coffee" };
JComboBox<String> editor = new JComboBox<String>( items );
DefaultCellEditor dce = new DefaultCellEditor( editor );
table.getColumnModel().getColumn(0).setCellEditor(dce);
}
/*
* The cost is recalculated whenever the quantity or price is changed
*/
public void tableChanged(TableModelEvent e)
{
if (e.getType() == TableModelEvent.UPDATE)
{
int row = e.getFirstRow();
int column = e.getColumn();
if (column == 1 || column == 2)
{
TableModel model = (TableModel)e.getSource();
int quantity = ((Integer)model.getValueAt(row, 1)).intValue();
double price = ((Double)model.getValueAt(row, 2)).doubleValue();
Double value = new Double(quantity * price);
model.setValueAt(value, row, 3);
}
}
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Table Model Listener");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TableProcessing());
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args) throws Exception
{
EventQueue.invokeLater( () -> createAndShowGUI() );
/*
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
*/
}
}
You probably get your error because of getFirstRow call. I think it's a bad idea to validate table structure in JTable.tableChanged - how do you know that the table was fully filled and ready for validation? I would suggest filling the whole table first, then invokation of validation. Maybe there would be also a good idea to use separate table to display validation results

Categories