2013-10-31 129 views
2

我不知道爲什麼編輯器我設置爲我的jtable沒有被調用。我用另一個SO Question的編輯器例子。使用JTable單元格編輯器

當我編輯我的jtable它只是編輯爲字符串...我期望它只接受數字值。可能會有一些例外,如果我輸入任何其他文字......但我不認爲編輯器在我編輯我的表時被調用。

import javax.swing.*; 
import javax.swing.table.*; 
import javax.swing.text.NumberFormatter; 

import java.awt.*; 
import java.awt.event.*; 
import java.text.DecimalFormat; 
import java.text.NumberFormat; 
import java.text.ParseException; 
import java.text.ParsePosition; 
import java.util.Locale; 

public class Grow extends JFrame { 

private static final Object[][] rowData = {{"Hello", "World"}}; 
private static final Object[] columnNames = {"A", "B"}; 

private JTable table; 
private DefaultTableModel model; 

public Grow() { 
    Container c = getContentPane(); 
    c.setLayout(new BorderLayout()); 

    model = new DefaultTableModel(rowData, columnNames); 
    table = new JTable(); 
    table.setModel(model); 
    c.add(new JScrollPane(table), BorderLayout.CENTER); 
    JButton add = new JButton("Add"); 
    JButton delete = new JButton("Delete"); 
    c.add(add, BorderLayout.LINE_START); 
    add.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent ae) { 
      model.addRow(rowData[0]); 
     } 
    }); 

    table.setCellEditor(new NumberCellEditor()); 

    c.add(delete, BorderLayout.LINE_END); 
    delete.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent ae) { 
      if(table.getSelectedRow()>-1) 
       model.removeRow(table.getSelectedRow()); 
     } 
    }); 

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    pack(); 
} 

class NumberCellEditor extends DefaultCellEditor { 
    /** 
    * 
    */ 
    private static final long serialVersionUID = 1L; 

    public NumberCellEditor(){ 
     super(new JFormattedTextField()); 
    } 

    @Override 
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { 
     JFormattedTextField editor = (JFormattedTextField) super.getTableCellEditorComponent(table, value, isSelected, row, column); 

     if (value!=null){ 
      DecimalFormat numberFormat = new DecimalFormat("#,##0.00;(#,##0.00)"); 
      editor.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(numberFormat))); 
      Number num = (Number) value; 
      String text = numberFormat.format(num); 
      editor.setHorizontalAlignment(SwingConstants.RIGHT); 
      editor.setText(text); 
     } 
     System.out.println(value); 
     return editor; 
    } 

    /*@Override 
    public boolean stopCellEditing() { 
     try { 
      // try to get the value 
      //this.getCellEditorValue(); 
      return super.stopCellEditing(); 
     } catch (Exception ex) { 
      return false; 
     } 

    } 
    */ 

    @Override 
    public Object getCellEditorValue() { 
     // get content of textField 
     String str = (String) super.getCellEditorValue(); 
     if (str == null) { 
      return null; 
     } 

     if (str.length() == 0) { 
      return null; 
     } 

     // try to parse a number 
     try { 
      ParsePosition pos = new ParsePosition(0); 
      Number n = NumberFormat.getInstance().parse(str, pos); 
      if (pos.getIndex() != str.length()) { 
       throw new ParseException(
         "parsing incomplete", pos.getIndex()); 
      } 

      // return an instance of column class 
      return new Float(n.floatValue()); 

     } catch (ParseException pex) { 
      throw new RuntimeException(pex); 
     } 
    } 
    } 

public static void main(String[] args) { 
    Grow g = new Grow(); 
    g.setLocationRelativeTo(null); 
    g.setVisible(true); 
} 
} 
+2

請問你的目標是什麼 – mKorbel

+0

我只是在學習爲JTable創建自定義的渲染器和編輯器。我不知道爲什麼我使用的編輯器在我的示例中沒有影響。編輯器沒有正確設置,或者我錯過了一些重寫......? –

回答

2
  • 使用純香草JTextFieldDocumentFilter代替JFormattedTextField爲編輯Component

  • 我不能評論什麼的,附start_point爲JFormattedTextFieldXxxFormat(重要的細節在官方甲骨文教程,API的How to use FormattedTextFieldNumberFormat等)

  • 你可以添加爲InternationalFormatter的過濾僅數

eg

InternationalFormatter formatter = new InternationalFormatter(format); 
formatter.setAllowsInvalid(false); 
//formatter.setMinimum(0.0); 
//formatter.setMaximum(1000.00); 

screen_shot

enter image description here

從代碼

import java.awt.Component; 
import java.awt.EventQueue; 
import java.math.RoundingMode; 
import java.text.DecimalFormat; 
import java.text.NumberFormat; 
import java.text.ParseException; 
import javax.swing.*; 
import javax.swing.table.TableCellEditor; 
import javax.swing.table.TableCellRenderer; 
import javax.swing.table.TableColumnModel; 

public class EditorAsRendererTableTest { 

    public EditorAsRendererTableTest() { 
     JTable table = new JTable(3, 2); 
     TableColumnModel colModel = table.getColumnModel(); 
     colModel.getColumn(0).setCellEditor(new MyCellEditor()); 
     colModel.getColumn(0).setCellRenderer(new MyCellEditor()); 
     JFrame frame = new JFrame("Test"); 
     frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
     table.setPreferredScrollableViewportSize(table.getPreferredSize()); 
     frame.add(new JScrollPane(table)); 
     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       new EditorAsRendererTableTest(); 
      } 
     }); 
    } 

    private class MyCellEditor extends AbstractCellEditor implements TableCellEditor, TableCellRenderer { 

     private static final long serialVersionUID = 1L; 
     private JFormattedTextField renderer; 
     private JFormattedTextField editor; 
     private NumberFormat format = DecimalFormat.getInstance(); 

     public MyCellEditor() { 
      format.setMinimumFractionDigits(2); 
      format.setMaximumFractionDigits(4); 
      format.setRoundingMode(RoundingMode.HALF_UP); 
      renderer = new JFormattedTextField(format); 
      renderer.setBorder(null); 
      editor = new JFormattedTextField(format); 
     } 

     @Override 
     public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { 
      renderer.setValue(value); 
      return renderer; 
     } 

     @Override 
     public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { 
      editor.setValue(value); 
      return editor; 
     } 

     @Override 
     public boolean stopCellEditing() { 
      try { 
       editor.commitEdit(); 
      } catch (ParseException e) { 
       return false; 
      } 
      return super.stopCellEditing(); 
     } 

     @Override 
     public Object getCellEditorValue() { 
      return editor.getValue(); 
     } 
    } 
} 
+0

編輯器示例。 – camickr

+0

這個例子真的很有用,但是如果想讓這個編輯器允許我遵循如何做:1.如果我選擇一個單元格並選擇另一個單元格而不輸入任何不允許我的東西。如果我點擊它,它迫使我輸入一些值。 2.如果我輸入的值以數字開始,它會將這些數字轉換爲忽略字母字符的雙重值。我如何讓它只接受數字? –

2

我預期它僅接受數值

通常不需要創建自定義編輯器。只需重寫TableModel的getColumnClass()方法以返回存儲在模型中的適當數據類,並且該表將使用適當的渲染器和編輯器。

但是,如果您希望編輯器限制小數位數或對數字進行範圍檢查,則可以使用自定義編輯器。

相關問題