I have a JTable that displays a column of doubles, and I'd like to limit the precision to 4 places. Using a custom cell renderer, this is straightforward; however, when a user selects a cell to edit the value, this also needs to truncate at four decimal places. I really don't want users to be able to enter something like 1.23423428384.
I've read many threads on cell editors, but can't find a minimum working example to do something this simple. Below I've posted a minimum working example of a table with stubbed example of editor. If anyone could fill in the stubbed methods to prevent users from entering > 4 decimals, that would be tremendously helpful.
package sandbox;
import java.awt.Component;
import javax.swing.AbstractCellEditor;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.TableCellEditor;
public class TableExample extends JFrame {
public TableExample() {
//headers for the table
String[] columns = new String[]{
"Id", "Name", "Hourly Rate", "Part Time"
};
//actual data for the table in a 2d array
Object[][] data = new Object[][]{
{1, "John", 40.0, false},
{2, "Rambo", 70.0, false},
{3, "Zorro", 60.0, true},};
//create table with data
JTable table = new JTable(data, columns);
/**
* SET EDITOR HERE
*/
table.getColumnModel().getColumn(2).setCellEditor(new DecimalEditor());
//add the table to the frame
this.add(new JScrollPane(table));
this.setTitle("Table Example");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TableExample();
}
});
}
public class DecimalEditor extends AbstractCellEditor implements TableCellEditor {
@Override
public Object getCellEditorValue() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public Component getTableCellEditorComponent(JTable jtable, Object o, boolean bln, int i, int i1) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
}
Try using a DefaultCellEditor
.
The constructor will accept a JTextField
as an editor.
However in your case you would want to create the editor using a JFormattedTextField
. Then you can specify the MaskFormat
that you want to limit the number of decimals.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.