我有一个显示一列 double 的 JTable,我想将精度限制为 4 位。使用自定义单元格渲染器,这很简单;但是,当用户选择一个单元格来编辑值时,也需要截断小数点后四位。我真的不希望用户能够输入类似 1.23423428384 的内容。
我已经阅读了许多有关单元格编辑器的线程,但找不到执行如此简单操作的最小工作示例。下面我发布了一个带有编辑器 stub 示例的表格的最小工作示例。如果任何人都可以填写 stub 方法以防止用户输入 > 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.
}
}
}
最佳答案
尝试使用DefaultCellEditor
。
构造函数将接受 JTextField
作为编辑器。
但是,在您的情况下,您可能希望使用 JFormattedTextField
创建编辑器。然后您可以指定要限制小数位数的MaskFormat
。
关于java - JTable 单元格编辑器十进制阈值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37868731/