问题
For putting a JSlider
into a JTable
I wrote am AbstractCellEditor
which implements a TableCellRenderer
and a TableCellEditor
. It gets initialized with values from 0 to 100.
I have the strange behaviour that when I first click onta a slider it jumps to the maximum.
The second weird behaviour: I've added a ChangeListener
. This Listener gets only called if I first click into the slider. A second click (which also changes the value) doesn't cause this event. Why?
public class SliderTableColumn extends AbstractCellEditor implements TableCellRenderer,
TableCellEditor
{
private final JSlider slRenderer;
private final JSlider slEditor;
private final int INITAL_VALUE;
private final int MIN_VLAUE;
private final int MAX_VALUE;
public SliderTableColumn(int min, int max, int initial, ChangeListener listener)
{
INITAL_VALUE = initial;
MIN_VLAUE = min;
MAX_VALUE = max;
slRenderer = new JSlider(MIN_VLAUE, MAX_VALUE);
slEditor = new JSlider(MIN_VLAUE, MAX_VALUE);
slEditor.addChangeListener(listener);
slRenderer.setUI(new CustomSliderUI(slRenderer, INITAL_VALUE));
slEditor.setUI(new CustomSliderUI(slEditor, INITAL_VALUE));
slRenderer.setValue(INITAL_VALUE);
slEditor.setValue(INITAL_VALUE);
}
@Override
public Object getCellEditorValue()
{
return slEditor.getValue();
}
@Override
public Component getTableCellRendererComponent(JTable table,
Object value,
boolean isSelected,
boolean hasFocus,
int row,
int column)
{
if(value != null)
{
slRenderer.setValue(((Integer) value).intValue());
}
return slRenderer;
}
@Override
public Component getTableCellEditorComponent(JTable table,
Object value,
boolean isSelected,
int row,
int column)
{
if(value != null)
{
slEditor.setValue(((Integer) value).intValue());
}
return slEditor;
}
}
回答1:
Absent your sscce, I'm speculating; but I can suggest two things to examine critically:
In
getTableCellEditorComponent()
, the actual parametervalue
comes from your table model. YoursetValue()
invocation forwards thevalue
to the slider's range model. An out-of-rangevalue
is pinned to the extreme.Your
ChangeListener
needs tofireEditingStopped()
, as shown in theItemListener
of this related example.
来源:https://stackoverflow.com/questions/8854841/jslider-in-jtable