I want to program Java software which contains a jTable. In this jTable, there is a column (Double value). My problem is that I want to limit the "Double" value entered by the user between -1 and 20. Is there any solution? Thank you
Asked
Active
Viewed 2,103 times
-2
-
3Learn some googling techniques which will benefit you always. Spoon feeding is not allowed here :) – Shoaib Chikate Nov 18 '13 at 16:02
-
You want a `CellEditor`, for [example](http://stackoverflow.com/a/7539298/230513). – trashgod Nov 18 '13 at 16:14
1 Answers
3
You will need to create a custom editor.
Here is an example to get you started:
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);
add(scrollpane);
// Use a custom editor
TableCellEditor fce = new FiveCharacterEditor();
table.setDefaultEditor(Object.class, fce);
add(new JTextField(), BorderLayout.NORTH);
}
class FiveCharacterEditor extends DefaultCellEditor
{
private long lastTime = System.currentTimeMillis();
FiveCharacterEditor()
{
super( new JTextField() );
}
public boolean stopCellEditing()
{
JTable table = (JTable)getComponent().getParent();
try
{
String editingValue = (String)getCellEditorValue();
System.out.println(table.isEditing());
System.out.println(editingValue);
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);
}
}

camickr
- 321,443
- 19
- 166
- 288
-
ohhh thank you it's a precious answer, can i apply this on one column only? – stack Nov 18 '13 at 17:14
-