[英]JTable cell editor decimilization threshold
I have a JTable that displays a column of doubles, and I'd like to limit the precision to 4 places. 我有一个显示双打列的JTable,我想将精度限制为4位。 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.
我真的不希望用户能够输入类似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.
如果有人可以填写存根(stubbed)的方法以防止用户输入> 4个小数,那将非常有用。
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
. 尝试使用
DefaultCellEditor
。
The constructor will accept a JTextField
as an editor. 构造函数将接受
JTextField
作为编辑器。
However in your case you would want to create the editor using a JFormattedTextField
. 但是,您需要使用
JFormattedTextField
创建编辑器。 Then you can specify the MaskFormat
that you want to limit the number of decimals. 然后,您可以指定要限制小数位数的
MaskFormat
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.