不用JTable。
想将Table的一个单元格做成只能输数字的,如何做好呢?
想将Table的一个单元格做成只能输数字的,如何做好呢?
解决方案 »
- 关于Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException的问题
- Finally 之后的语句
- 对象问题!
- 关于JTree的一个问题,我用函数JTree.setEditable(false),但树还是可以编辑,请问漏了些什么?
- Java1.4的帮助文档有无有中文版??
- 在java application中怎么调用.chm文件?
- long类型不是64位有符号整数么??怎么还出错???
- Error loading class classname : wrong name,
- Java会不会很难学呢?
- catch的错误会引起程序崩溃吗?
- short s1 = 1; s1 = s1 + 1;有什么错? short s1 = 1; s1 += 1;有什么错?
- jar打包java源代码文件(utf-8)之后,在eclipse直接查看,汉字乱码,该怎么解决?
void setCellEditor(TableCellEditor cellEditor)
Sets the editor to used by when a cell in this column is edited.
void setCellRenderer(TableCellRenderer cellRenderer) 改写TableCellEditor/*
* IntegerEditor is used by TableFTFEditDemo.java.
*/import javax.swing.AbstractAction;
import javax.swing.DefaultCellEditor;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.Component;
import java.awt.Toolkit;
import java.text.NumberFormat;
import java.text.ParseException;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.NumberFormatter;/**
* Implements a cell editor that uses a formatted text field
* to edit Integer values.
*/
public class IntegerEditor extends DefaultCellEditor {
JFormattedTextField ftf;
NumberFormat integerFormat;
private Integer minimum, maximum;
private boolean DEBUG = false; public IntegerEditor(int min, int max) {
super(new JFormattedTextField());
ftf = (JFormattedTextField)getComponent();
minimum = new Integer(min);
maximum = new Integer(max); //Set up the editor for the integer cells.
integerFormat = NumberFormat.getIntegerInstance();
NumberFormatter intFormatter = new NumberFormatter(integerFormat);
intFormatter.setFormat(integerFormat);
intFormatter.setMinimum(minimum);
intFormatter.setMaximum(maximum); ftf.setFormatterFactory(
new DefaultFormatterFactory(intFormatter));
ftf.setValue(minimum);
ftf.setHorizontalAlignment(JTextField.TRAILING);
ftf.setFocusLostBehavior(JFormattedTextField.PERSIST); //React when the user presses Enter while the editor is
//active. (Tab is handled as specified by
//JFormattedTextField's focusLostBehavior property.)
ftf.getInputMap().put(KeyStroke.getKeyStroke(
KeyEvent.VK_ENTER, 0),
"check");
ftf.getActionMap().put("check", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (!ftf.isEditValid()) { //The text is invalid.
if (userSaysRevert()) { //reverted
ftf.postActionEvent(); //inform the editor
}
} else try { //The text is valid,
ftf.commitEdit(); //so use it.
ftf.postActionEvent(); //stop editing
} catch (java.text.ParseException exc) { }
}
});
} //Override to invoke setValue on the formatted text field.
public Component getTableCellEditorComponent(JTable table,
Object value, boolean isSelected,
int row, int column) {
JFormattedTextField ftf =
(JFormattedTextField)super.getTableCellEditorComponent(
table, value, isSelected, row, column);
ftf.setValue(value);
return ftf;
} //Override to ensure that the value remains an Integer.
public Object getCellEditorValue() {
JFormattedTextField ftf = (JFormattedTextField)getComponent();
Object o = ftf.getValue();
if (o instanceof Integer) {
return o;
} else if (o instanceof Number) {
return new Integer(((Number)o).intValue());
} else {
if (DEBUG) {
System.out.println("getCellEditorValue: o isn't a Number");
}
try {
return integerFormat.parseObject(o.toString());
} catch (ParseException exc) {
System.err.println("getCellEditorValue: can't parse o: " + o);
return null;
}
}
} //Override to check whether the edit is valid,
//setting the value if it is and complaining if
//it isn't. If it's OK for the editor to go
//away, we need to invoke the superclass's version
//of this method so that everything gets cleaned up.
public boolean stopCellEditing() {
JFormattedTextField ftf = (JFormattedTextField)getComponent();
if (ftf.isEditValid()) {
try {
ftf.commitEdit();
} catch (java.text.ParseException exc) { }
} else { //text is invalid
if (!userSaysRevert()) { //user wants to edit
return false; //don't let the editor go away
}
}
return super.stopCellEditing();
} /**
* Lets the user know that the text they entered is
* bad. Returns true if the user elects to revert to
* the last good value. Otherwise, returns false,
* indicating that the user wants to continue editing.
*/
protected boolean userSaysRevert() {
Toolkit.getDefaultToolkit().beep();
ftf.selectAll();
Object[] options = {"Edit",
"Revert"};
int answer = JOptionPane.showOptionDialog(
SwingUtilities.getWindowAncestor(ftf),
"The value must be an integer between "
+ minimum + " and "
+ maximum + ".\n"
+ "You can either continue editing "
+ "or revert to the last valid value.",
"Invalid Text Entered",
JOptionPane.YES_NO_OPTION,
JOptionPane.ERROR_MESSAGE,
null,
options,
options[1]);
if (answer == 1) { //Revert!
ftf.setValue(ftf.getValue());
return true;
}
return false;
}
}
import java.awt.BorderLayout;
import javax.swing.table.DefaultTableModel;
import javax.swing.JTable;
import javax.swing.JFrame;
import javax.swing.JPanel;public class Frame1 extends JFrame {
JPanel contentPane;
Object[][] object = { {"aaa", new Integer(1)}, {"bbb", new Integer(1)},
{"ccc", new Integer(1)}, {"ddd", new Integer(1)}
};
String[] name = {"a", "b"};
JTable table=new JTable(new DefaultTableModel(object,name){
public void setValueAt(Object aValue, int rowIndex, int columnIndex)
{
if (columnIndex == 1) {
Integer num = null;
try {
num = Integer.parseInt((String) aValue);
} catch (Exception ex) {
javax.swing.JOptionPane.showMessageDialog(null, "只能输入数字!");
return; }
}
super.setValueAt(aValue,rowIndex,columnIndex);
this.fireTableDataChanged();
}
}); public Frame1() {
try {
setDefaultCloseOperation(EXIT_ON_CLOSE);
jbInit();
} catch (Exception exception) {
exception.printStackTrace();
}
} /**
* Component initialization.
*
* @throws java.lang.Exception
*/ private void jbInit() throws Exception {
contentPane = (JPanel) getContentPane();
contentPane.setLayout(new BorderLayout());
setSize(new Dimension(600, 550));
this.add(table,BorderLayout.CENTER); }}
package excise;import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;public class TableNum extends JFrame { public TableNum() {
super();
this.init();
} private void init() {
this.getContentPane().add(new JTable(new DefaultTableModel() {
@SuppressWarnings("unchecked")
public Class getColumnClass(int c) {
return Integer.class;
} public int getColumnCount() {
return 10;
} public int getRowCount() {
return 10;
}
}));
} public static void main(String[] args) {
TableNum l = new TableNum();
l.setVisible(true);
l.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}