无效值的 JTable 警报 [英] JTable Alert on invalid value
本文介绍了无效值的 JTable 警报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有一个带有自定义模型的可编辑 Jtable(实际上是 TreeTable).当前的 setValueAt 方法需要更新,以防止值大于一定数量(取决于行).
So I have an editable Jtable (TreeTable actually) with a custom model. The current setValueAt method needs to be updated to prevent values greater than a certain amount (dependant on the row).
这很容易防止(如果值无效,只需不要设置该值)但是通知用户所选金额无效的最佳方法是什么?从模型中弹出一个对话框似乎很讨厌.
This is easy to prevent (simply don't set the value if it's invalid) but what's the best way to inform the user that the chosen amount was invalid? Popping a dialog from the model seems rather nasty.
推荐答案
从模型中弹出一个对话框似乎很讨厌.
Popping a dialog from the model seems rather nasty.
同意.对列使用自定义编辑器.也许是这样的:
Agreed. Use a custom editor for the column. Maybe something like:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.border.*;
import javax.swing.table.*;
public class TableEdit extends JFrame
{
TableEdit()
{
JTable table = new JTable(5,5);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollpane = new JScrollPane(table);
getContentPane().add(scrollpane);
// Use a custom editor
TableCellEditor fce = new FiveCharacterEditor();
table.setDefaultEditor(Object.class, fce);
}
class FiveCharacterEditor extends DefaultCellEditor
{
FiveCharacterEditor()
{
super( new JTextField() );
}
public boolean stopCellEditing()
{
JTable table = (JTable)getComponent().getParent();
try
{
String editingValue = (String)getCellEditorValue();
if(editingValue.length() != 5)
{
JTextField textField = (JTextField)getComponent();
textField.setBorder(new LineBorder(Color.red));
textField.selectAll();
textField.requestFocusInWindow();
JOptionPane.showMessageDialog(
null,
"Please enter string with 5 letters.",
"Alert!",JOptionPane.ERROR_MESSAGE);
return false;
}
}
catch(ClassCastException exception)
{
return false;
}
return super.stopCellEditing();
}
public Component getTableCellEditorComponent(
JTable table, Object value, boolean isSelected, int row, int column)
{
Component c = super.getTableCellEditorComponent(
table, value, isSelected, row, column);
((JComponent)c).setBorder(new LineBorder(Color.black));
return c;
}
}
public static void main(String [] args)
{
JFrame frame = new TableEdit();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}
这篇关于无效值的 JTable 警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文