簡體   English   中英

JTable單元格編輯器的不合格閾值

[英]JTable cell editor decimilization threshold

我有一個顯示雙打列的JTable,我想將精度限制為4位。 使用自定義單元格渲染器,這很簡單。 但是,當用戶選擇一個單元格來編輯值時,這也需要在小數點后四位截斷。 我真的不希望用戶能夠輸入類似1.23423428384的內容。

我已經在單元格編輯器上閱讀了很多線程,但是找不到最小的工作示例來完成這種簡單的操作。 在下面,我發布了帶有編輯器存根示例的表格的最小工作示例。 如果有人可以填寫存根(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.
        }
    }

}

嘗試使用DefaultCellEditor

構造函數將接受JTextField作為編輯器。

但是,您需要使用JFormattedTextField創建編輯器。 然后,您可以指定要限制小數位數的MaskFormat

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM