I have create my own SpreadsheetCellEditor to show a ColorPicker, but I don't want to return back the ColorPicker.getValue().toString, I want to return a label with
Background color of selected value. I have searched for setContentDisplay(ContentDisplay.GRAPHIC_ONLY) but it seems not exist on SpreadsheetCell.
So how I can achieve this?
Here is my implementation so far,
public class comboboxCellEditor extends SpreadsheetCellEditor {
private final ColorPicker colorPicker = new ColorPicker();
private EventHandler<KeyEvent> eh;
private ChangeListener<Color> cl;
private boolean ending = false;
public comboboxCellEditor(SpreadsheetView view) {
super(view);
}
#Override
public void startEdit(Object value) {
if (value instanceof Color) {
this.colorPicker.setValue((Color) value);
}
attachEnterEscapeEventHandler();
this.colorPicker.show();
this.colorPicker.requestFocus();
}
#Override
public Control getEditor() {
return colorPicker;
}
public String getControlValue() {
return this.colorPicker.getValue().toString();
}
#Override
public void end() {
if (this.colorPicker.isShowing()) {
this.colorPicker.hide();
}
this.colorPicker.removeEventFilter(KeyEvent.KEY_PRESSED, this.eh);
this.colorPicker.valueProperty().removeListener(this.cl);
}
private void attachEnterEscapeEventHandler() {
this.eh =
new EventHandler<KeyEvent>() {
public void handle(KeyEvent t) {
if (t.getCode() == KeyCode.ENTER) {
comboboxCellEditor.this.ending = true;
comboboxCellEditor.this.endEdit(true);
comboboxCellEditor.this.ending = false;
} else if (t.getCode() == KeyCode.ESCAPE) {
comboboxCellEditor.this.endEdit(false);
}
}
};
this.colorPicker.addEventFilter(KeyEvent.KEY_PRESSED, this.eh);
this.cl = new ChangeListener<Color>() {
public void changed(ObservableValue<? extends Color> observable, Color oldValue, Color newValue) {
if (!comboboxCellEditor.this.ending)
comboboxCellEditor.this.endEdit(true);
}
};
this.colorPicker.valueProperty().addListener(this.cl);
}
}
public class SpreadSheetComboboxCellType extends SpreadsheetCellType<Color> {
#Override
public SpreadsheetCellEditor createEditor(SpreadsheetView spreadsheetView) {
return new comboboxCellEditor(spreadsheetView);
}
#Override
public String toString(Color color) {
return color.toString();
}
#Override
public boolean match(Object o) {
return true;
}
#Override
public Color convertValue(Object o) {
if (o instanceof Color)
return (Color) o;
else {
return Color.valueOf((String) o);
}
}
public SpreadsheetCell createCell(int row, int column, int rowSpan, int columnSpan, Color value) {
SpreadsheetCellBase cell = new SpreadsheetCellBase(row, column, rowSpan, columnSpan, this);
cell.setItem(value);
Label label = new Label();
label.setGraphic(null);
label.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
cell.setGraphic(label);
return cell;
}
}
The SpreadsheetCell has an updateText method each time you modify the item. Therefore it's meant to display text first.
You have several options.
The easiest one is to add a listener to the cell and modify your graphic at that moment :
The text shown in the cell will be the result of the conversion of your SpreadsheetCellType. Since you don't want text, return nothing in your SpreadSheetComboboxCellType :
#Override
public String toString(Color color) {
return "";
}
Then simply add a Listener on your SpreadsheetCell and modify the graphic :
cell.itemProperty().addListener(new ChangeListener<Object>() {
#Override
public void changed(ObservableValue<? extends Object> ov, Object t, Object newValue) {
if (newValue != null && newValue instanceof Color ) {
//Do something
cell.setGraphic(My_Graphic_Object);
} else {
cell.setGraphic(null);
}
}
});
This should do the trick. Now you can implement your own SpreadsheetCell in order to have a total control on the display. It will be more efficient. Basically copy all the code for SpreadsheetCellBase (here : https://bitbucket.org/controlsfx/controlsfx/src/755c59605e623476ff0a6c860e2c218488776aec/controlsfx/src/main/java/org/controlsfx/control/spreadsheet/SpreadsheetCellBase.java?at=default&fileviewer=file-view-default )
And simply modify the updateText method :
private void updateText() {
if(getItem() == null){
text.setValue(""); //$NON-NLS-1$
}else if (!("").equals(getFormat())) { //$NON-NLS-1$
text.setValue(type.toString(getItem(), getFormat()));
} else {
text.setValue(type.toString(getItem()));
}
}
Instead of modifying the text, you would be modifying the graphic with the new color.
Related
I've got a listview where I can select different panes that will show up in the main pane. Now for a particular pane I need some objects to use every function. On the listview there is a listener on the selectedItemProperty. I want to check if the objects I need are available, otherwise the objects oldValue and newValue should keep their value. Is there a way of doing that?
listView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Object>()
{
#Override
public void changed(ObservableValue<? extends Object> observable, Object oldValue,
Object newValue)
{
if(obj == null)
{
// keep the oldValues for both
}
});
}
Here is a runnable example in the first code snippet the second snippet is what it would look like in your program
public class MainNoFXML extends Application {
public static void main(String[] args) { launch(args); }
#Override
public void start(Stage primaryStage) {
ListView<Object> listView = new ListView<>(FXCollections.observableArrayList(new String[]{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"}));
listView.getSelectionModel().selectedItemProperty().addListener((obs, oldVal, newVal)->{
if(newVal != null && (!newVal.equals("Monday") && !newVal.equals("Tuesday")))
Platform.runLater(() -> listView.getSelectionModel().select(oldVal));
});
Scene scene = new Scene(listView);
primaryStage.setScene(scene);
primaryStage.show();
}
}
Your Program(I think this is correct not exactly sure what your working with)
listView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Object>() {
#Override
public void changed(ObservableValue<? extends Object> observable, Object oldValue,
Object newValue)
{
if(obj == null)
{
Platform.runLater(() -> listView.getSelectionModel().select(oldValue));
// keep the oldValues for both
}
});
});
In this case you should use a custom selection model to prevent some items from being selected.
The following implementation is simplified. It doesn't handle changes of the item list. Furthermore it implements single selection only, but hopefully it shows the general approach:
public class CustomSelectionModel<T> extends MultipleSelectionModel<T> {
private final ListView<T> listView;
private final ObservableList<Integer> selectedIndices = FXCollections.observableArrayList();
private final ObservableList<Integer> selectedIndicesUnmodifiable = FXCollections.unmodifiableObservableList(selectedIndices);
private final ObservableList<T> selectedItems;
private BiPredicate<Integer, T> leavePredicate;
private BiPredicate<Integer, T> enterPredicate;
public BiPredicate<Integer, T> getLeavePredicate() {
return leavePredicate;
}
public void setLeavePredicate(BiPredicate<Integer, T> leavePredicate) {
this.leavePredicate = leavePredicate;
}
public BiPredicate<Integer, T> getEnterPredicate() {
return enterPredicate;
}
public void setEnterPredicate(BiPredicate<Integer, T> enterPredicate) {
this.enterPredicate = enterPredicate;
}
public CustomSelectionModel(ListView<T> listView) {
if (listView == null) {
throw new IllegalArgumentException();
}
this.listView = listView;
this.selectedItems = new TransformationList<T, Integer>(selectedIndices) {
#Override
protected void sourceChanged(ListChangeListener.Change<? extends Integer> c) {
beginChange();
while (c.next()) {
if (c.wasReplaced()) {
nextReplace(c.getFrom(), c.getTo(), c.getRemoved().stream().map(listView.getItems()::get).collect(Collectors.toList()));
} else if (c.wasRemoved()) {
nextRemove(c.getFrom(), c.getRemoved().stream().map(listView.getItems()::get).collect(Collectors.toList()));
} else if (c.wasAdded()) {
nextAdd(c.getFrom(), c.getTo());
}
}
endChange();
}
#Override
public int getSourceIndex(int index) {
return index;
}
#Override
public T get(int index) {
return listView.getItems().get(getSource().get(index));
}
#Override
public int size() {
return getSource().size();
}
};
}
#Override
public ObservableList<Integer> getSelectedIndices() {
return selectedIndicesUnmodifiable;
}
#Override
public ObservableList<T> getSelectedItems() {
return selectedItems;
}
#Override
public void selectIndices(int index, int... indices) {
clearAndSelect(index); // ignore all indices but the first
}
#Override
public void selectAll() {
selectFirst();
}
#Override
public void selectFirst() {
if (!listView.getItems().isEmpty()) {
clearAndSelect(0);
}
}
#Override
public void selectLast() {
if (!listView.getItems().isEmpty()) {
clearAndSelect(listView.getItems().size() - 1);
}
}
private void moveSelection(int oldIndex, int newIndex) {
if ((leavePredicate == null || leavePredicate.test(oldIndex, oldIndex == -1 ? null : listView.getItems().get(oldIndex)))
&& (enterPredicate == null || enterPredicate.test(newIndex, newIndex == -1 ? null : listView.getItems().get(newIndex)))) {
setSelectedIndex(newIndex);
if (newIndex == -1) {
selectedItems.clear();
setSelectedItem(null);
} else {
setSelectedItem(listView.getItems().get(newIndex));
if (isEmpty()) {
selectedIndices.add(newIndex);
} else {
selectedIndices.set(0, newIndex);
}
}
listView.getFocusModel().focus(newIndex);
}
}
#Override
public void clearAndSelect(int index) {
moveSelection(getSelectedIndex(), index);
}
#Override
public void select(int index) {
clearAndSelect(index);
}
#Override
public void select(T obj) {
int index = listView.getItems().indexOf(obj);
if (index >= 0) {
clearAndSelect(index);
}
}
#Override
public void clearSelection(int index) {
if (getSelectedIndex() == index) {
clearSelection();
}
}
#Override
public void clearSelection() {
moveSelection(getSelectedIndex(), -1);
}
#Override
public boolean isSelected(int index) {
return selectedIndices.contains(index);
}
#Override
public boolean isEmpty() {
return selectedIndices.isEmpty();
}
#Override
public void selectPrevious() {
int index = getSelectedIndex() - 1;
if (index >= 0) {
clearAndSelect(index);
}
}
#Override
public void selectNext() {
int index = getSelectedIndex() + 1;
if (index < listView.getItems().size()) {
clearAndSelect(index);
}
}
}
#Override
public void start(Stage primaryStage) throws Exception {
ListView<Integer> listView = new ListView<>();
for (int i = 0; i < 100; i++) {
listView.getItems().add(i);
}
CustomSelectionModel<Integer> selectionModel = new CustomSelectionModel<>(listView);
listView.setSelectionModel(selectionModel);
CheckBox moveAllowed = new CheckBox("disallow movement");
moveAllowed.selectedProperty().addListener((o, oldValue, newValue) -> selectionModel.setLeavePredicate(newValue ? (index, item) -> false : null));
CheckBox enterOdd = new CheckBox("enter odd items disallowed");
enterOdd.selectedProperty().addListener((o, oldValue, newValue) -> selectionModel.setEnterPredicate(newValue ? (index, item) -> (index & 1) == 0 : null));
Scene scene = new Scene(new ScrollPane(new HBox(listView, new VBox(moveAllowed, enterOdd))));
primaryStage.setScene(scene);
primaryStage.show();
}
I tried to implement my own JSpinner model to accept an enumeration (including I18N), so I did like that:
searchSpinner.setModel(new AbstractSpinnerModel() {
int index = 0;
int minIndex = 0;
int maxIndex = MY_ENUM.values().length - 1;
Object selected = MY_ENUM.values()[index];
#Override
public Object getValue() {
return selected;
}
#Override
public void setValue(Object value) {
selected = value;
fireStateChanged();
}
#Override
public Object getNextValue() {
if (index < maxIndex) {
index++;
}
fireStateChanged();
return MY_ENUM.values()[index];
}
#Override
public Object getPreviousValue() {
if (index > minIndex) {
index--;
}
fireStateChanged();
return MY_ENUM.values()[index];
}
#Override
public void addChangeListener(ChangeListener l) {
}
#Override
public void removeChangeListener(ChangeListener l) {
}
});
The problem is that did not work, and even the spinner list looks like disabled. What am I doing wrong?
UPDATE: Based on first answer
You should extend from AbstractSpinnerModel (note to folks new to his question -- note that his original question had the class implementing the SpinnerModel interface. He later changed his code to reflect my recommendation) and be sure to call the fireStateChanged() method when appropriately. Also you've not taken into account edge cases and beyond edge cases.
e.g.,
import javax.swing.*;
import javax.swing.JSpinner.DefaultEditor;
public class MySpinnerPanel extends JPanel {
public static void main(String[] args) {
JSpinner spinner = new JSpinner(new MyEnumSpinnerModel());
JSpinner.DefaultEditor editor = (DefaultEditor) spinner.getEditor();
editor.getTextField().setColumns(5);
JPanel panel = new JPanel();
panel.add(spinner);
JOptionPane.showMessageDialog(null, panel);
}
}
enum MyEnum {
FE, FI, FO, FUM, FOO, FUBAR, SPAM
}
class MyEnumSpinnerModel extends AbstractSpinnerModel {
private int index = 0;
#Override
public Object getValue() {
return MyEnum.values()[index];
}
#Override
public void setValue(Object value) {
if (value instanceof MyEnum) {
index = ((MyEnum) value).ordinal();
fireStateChanged();
} else {
String text = value.toString() + " is not a valid enum item";
throw new IllegalArgumentException(text);
}
}
#Override
public Object getNextValue() {
if (index >= MyEnum.values().length - 1) {
return null;
} else {
return MyEnum.values()[index + 1];
}
}
#Override
public Object getPreviousValue() {
if (index <= 0) {
return null;
} else {
return MyEnum.values()[index - 1 ];
}
}
}
Edit
Note that the model itself should not require a listener to notify the view (as per the other answer to this question) as that's what the AbstractSpinnerModel does internally. It's fireStateChange() method is what the model itself should call to trigger this notification, same as most all other similar model structures in Swing such as any TableModel object that you create that derives from the AbstractTableModel. For details, please see the source code for the SpinnerListModel. Your code should emulate this class.
You should use ChangeListener to notify the view of changes in the model.
spinner = new JSpinner(new SpinnerModel() {
private ChangeListener l;
#Override
public void setValue(Object value) {
...
if(l != null) {
l.stateChanged(new ChangeEvent(this));
}
}
...
#Override
public void addChangeListener(ChangeListener l) {
this.l = l;
}
#Override
public void removeChangeListener(ChangeListener l) {
if(this.l == l) {
this.l = null;
}
}
});
Edit: You can use List to register many listeners.
I need to provide some disabled items in a combobox. All works fine except preventing of combobox from closing after click on a disabled item.
Here is my code:
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.swing.plaf.basic.BasicComboBoxRenderer;
import javax.swing.plaf.basic.ComboPopup;
public class DisabledCombo {
public static void main(String[] args) {
final DisabledSupportComboModel model = new DisabledSupportComboModel();
model.addElement(new Item("First element"));
model.addElement(new Item("Second element"));
model.addElement(new Item("Disabled", false));
model.addElement(new Item("Fourth element"));
final JComboBox<Item> itemCombo = new JComboBox<DisabledCombo.Item>(model);
itemCombo.setRenderer(new DisabledSupportComboRenderer());
final ComboPopup popup = (ComboPopup) itemCombo.getUI().getAccessibleChild(itemCombo, 0);
final JList<?> l = popup.getList();
final MouseListener[] listeners = l.getMouseListeners();
for (final MouseListener ml : listeners) {
l.removeMouseListener(ml);
System.out.println("remove listener: " + ml);
}
System.out.println("Number of listeners: " + l.getMouseListeners().length);
l.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
System.out.println("Release");
final int idx = l.locationToIndex(e.getPoint());
if (idx >= 0 && l.getModel().getElementAt(idx) instanceof Item) {
final Item itm = (Item) l.getModel().getElementAt(idx);
if (!itm.isEnabled()) {
e.consume();
}
}
}
#Override
public void mouseClicked(MouseEvent e) {
System.out.println("Click");
final int idx = l.locationToIndex(e.getPoint());
if (idx >= 0 && l.getModel().getElementAt(idx) instanceof Item) {
final Item itm = (Item) l.getModel().getElementAt(idx);
if (!itm.isEnabled()) {
e.consume();
}
}
}
});
for (final MouseListener ml : listeners) {
l.addMouseListener(ml);
}
final JFrame frm = new JFrame("Combo test");
frm.add(itemCombo);
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.pack();
frm.setVisible(true);
}
private static class Item {
private final Object value;
private final boolean enabled;
public Item(Object aValue) {
value = aValue;
enabled = true;
}
public Item(Object aValue, boolean isEnabled) {
value = aValue;
enabled = isEnabled;
}
public Object getValue() {
return value;
}
public boolean isEnabled() {
return enabled;
}
/**
* {#inheritDoc}
*/
#Override
public String toString() {
return null == value? null : value.toString();
}
}
private static class DisabledSupportComboModel extends DefaultComboBoxModel<Item> {
/**
* {#inheritDoc}
*/
#Override
public void setSelectedItem(Object anObject) {
if (anObject instanceof Item) {
if (((Item) anObject).isEnabled()) {
super.setSelectedItem(anObject);
}
} else {
super.setSelectedItem(anObject);
}
}
}
private static class DisabledSupportComboRenderer extends BasicComboBoxRenderer {
/**
* {#inheritDoc}
*/
#Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value instanceof Item) {
if (((Item) value).isEnabled()) {
setForeground(isSelected? list.getSelectionForeground() : list.getForeground());
setBackground(isSelected? list.getSelectionBackground() : list.getBackground());
} else {
setForeground(UIManager.getColor("Label.disabledForeground"));
setBackground(list.getBackground());
}
} else {
setForeground(isSelected? list.getSelectionForeground() : list.getForeground());
setBackground(isSelected? list.getSelectionBackground() : list.getBackground());
}
return this;
}
}
}
My problem is, that I get mouseReleased event, but no mouseClicked event. The only way to get mouseClicked event is to register AWTEventListener for mouse events using the Toolkit class. But it's realy ugly here. The approach to show the popup again using the setPopupVisible(true) is also difficult here due to eventually scroll pane in popup (the real combobox can have about 30 entries, so I need to save the scroll bar value to restore the drop down list at the same position). Can somebody advise me, how can I prevent the combo popup from closing?
Here's my attempt:
Override JComboBox#setPopupVisible(boolean) instead of using JList#addMouseListener(...)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DisabledCombo2 {
public static JComponent makeUI() {
DisabledSupportComboModel model = new DisabledSupportComboModel();
model.addElement(new Item("First element"));
model.addElement(new Item("Second element"));
model.addElement(new Item("Disabled", false));
model.addElement(new Item("Fourth element"));
JComboBox<Item> itemCombo = new JComboBox<Item>(model) {
//#see http://java-swing-tips.blogspot.jp/2010/03/non-selectable-jcombobox-items.html
private boolean isDisableIndex;
#Override public void setPopupVisible(boolean v) {
if (!v && isDisableIndex) {
//Do nothing(prevent the combo popup from closing)
isDisableIndex = false;
} else {
super.setPopupVisible(v);
}
}
#Override public void setSelectedObject(Object o) {
if (o instanceof Item && !((Item) o).isEnabled()) {
isDisableIndex = true;
} else {
super.setSelectedObject(o);
}
}
#Override public void setSelectedIndex(int index) {
Object o = getItemAt(index);
if (o instanceof Item && !((Item) o).isEnabled()) {
isDisableIndex = true;
} else {
super.setSelectedIndex(index);
}
}
};
itemCombo.setRenderer(new DisabledSupportComboRenderer());
return itemCombo;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame("Combo test2");
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(makeUI());
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
class Item {
private final Object value;
private final boolean enabled;
public Item(Object aValue) {
value = aValue;
enabled = true;
}
public Item(Object aValue, boolean isEnabled) {
value = aValue;
enabled = isEnabled;
}
public Object getValue() {
return value;
}
public boolean isEnabled() {
return enabled;
}
#Override public String toString() {
return null == value ? null : value.toString();
}
}
class DisabledSupportComboModel extends DefaultComboBoxModel<Item> {
#Override public void setSelectedItem(Object anObject) {
if (anObject instanceof Item) {
if (((Item) anObject).isEnabled()) {
super.setSelectedItem(anObject);
}
} else {
super.setSelectedItem(anObject);
}
}
}
class DisabledSupportComboRenderer extends DefaultListCellRenderer {
#Override public Component getListCellRendererComponent(
JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value instanceof Item) {
if (((Item) value).isEnabled()) {
setForeground(isSelected ? list.getSelectionForeground() : list.getForeground());
setBackground(isSelected ? list.getSelectionBackground() : list.getBackground());
} else {
setForeground(UIManager.getColor("Label.disabledForeground"));
setBackground(list.getBackground());
}
} else {
setForeground(isSelected ? list.getSelectionForeground() : list.getForeground());
setBackground(isSelected ? list.getSelectionBackground() : list.getBackground());
}
return this;
}
}
I found some simple solution to always keep popup open, until user clicks outside the popup. It may be useful with some custom JComboBox'es, like the one I have in my project, but is a little hacky.
public class MyComboBox extends JComboBox
{
boolean select_action_performed = false; //check when user select item
public MyComboBox(){
setRenderer(new MyComboBoxRenderer()); //our spesial render
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
//Do stuff when user select item
select_action_performed = true; //set the flag
}
});
}
class MyComboBoxRenderer extends BasicComboBoxRenderer {
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
if (index == -1){ //if popup hidden
if (select_action_performed) {
showPopup(); //show it again
select_action_performed = false; //and remove the flag
}
return r;
}
}
}
}
Short:
Is possible to set an unknown value on a JSlider having no knob?
Long:
I'm working on a project that has a desktop client developed in Java Swing where the user is required to measure some parameters using a slider. That's a requirement, it has to be a slider.
Until the user interacts with the slider the value has to be unknown, and that means showing no knob. That's a requirement too.
When using a JSlider the knob shows always and is no way to set any value out of its bounds or set it to null as it uses the primitive type int and not the object Integer.
Is there a way to set it a null fail-value or at least some value that shows no knob? Is there some extension that would allow to do so?
Make your own implementation of BasicSliderUI and override paintThumb(Graphics g) to do what you require.
Also take a look here: How to hide the knob of jSlider?
With the great help of Harry Joy about hiding the knob, finally I've been able to solve the problem.
If you check Harry's answer you can read about overriding the method BasicSliderUI.paintThumb(Graphics) for hiding the knob. It works fine on most L&F's not based on Synth (and that means Nimbus), where the approach would be different, but doable via customizations on the L&F.
Installing it is a bit tricky: having a PropertyChangeListener on the UIManager that checks any change on the L&F and installs a proper UI delegate on the component does the magic (in this solution I'm just showing the one based in BasicSliderUI the others are copy-pastes). Also I've tweaked it a bit to make it set the value to the position where is first clicked.
For the delegate to know if it must paint the knob or not I decided having a client property on the JSlider called "ready", which is to be a boolean. This way, the delegate can be installed on any JSlider, not only the one extended.
Now, how to manage unknown values? Adding another new property "selectedValue", this one is bound to both "value" and "ready" and of Integer type. "ready" is false or true depending on if it's null or not, and viceversa, and both "value" and "selectedValue" hold the same value (one being int and the other Integer) unless not ready, which would set the "selectedValue" to null. It might sound complicated, but it is not.
Also there's a little tweak for clearing the value with [Esc] and propagating properties in the component implemented.
Here's the code:
BasicSliderUIExt
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import javax.swing.JSlider;
import javax.swing.SwingConstants;
import javax.swing.plaf.basic.BasicSliderUI;
public class BasicSliderUIExt extends BasicSliderUI {
public BasicSliderUIExt(JSlider slider) {
super(slider);
}
#Override
public void paintThumb(Graphics g) {
if (isReady(super.slider)) {
super.paintThumb(g);
}
}
#Override
protected TrackListener createTrackListener(final JSlider slider) {
return new TrackListener() {
#Override
public void mousePressed(MouseEvent event) {
if (isReady(slider)) {
super.mousePressed(event);
} else {
JSlider slider = (JSlider) event.getSource();
switch (slider.getOrientation()) {
case SwingConstants.VERTICAL:
slider.setValue(valueForYPosition(event.getY()));
break;
case SwingConstants.HORIZONTAL:
slider.setValue(valueForXPosition(event.getX()));
break;
}
super.mousePressed(event);
super.mouseDragged(event);
}
}
#Override
public boolean shouldScroll(int direction) {
if (isReady(slider)) {
return super.shouldScroll(direction);
}
return false;
}};
}
public static boolean isReady(JSlider slider) {
Object ready = slider.getClientProperty(JSliderExt.READY_PROPERTY);
return (ready == null) || (!(ready instanceof Boolean)) || (((Boolean) ready).booleanValue());
}
}
JSliderExt
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.lang.reflect.Constructor;
import javax.swing.BoundedRangeModel;
import javax.swing.JSlider;
import javax.swing.LookAndFeel;
import javax.swing.UIManager;
import javax.swing.plaf.SliderUI;
public class JSliderExt extends JSlider {
private static final long serialVersionUID = 1L;
public static final String EXTENT_PROPERTY = "extent";
public static final String MAXIMUM_PROPERTY = "maximum";
public static final String MINIMUM_PROPERTY = "minimum";
public static final String READY_PROPERTY = "ready";
public static final String SELECTED_VALUE_PROPERTY = "selectedValue";
public static final String VALUE_PROPERTY = "value";
public static final boolean READY_DEFAULT_VALUE = false;
protected SliderUI uix = new BasicSliderUIExt(this);
public JSliderExt(BoundedRangeModel model, boolean ready) {
super(model);
init(ready);
}
public JSliderExt(BoundedRangeModel model) {
super(model);
init(READY_DEFAULT_VALUE);
}
public JSliderExt(int orientation, int minimmum, int maximum, int value, boolean ready) {
super(orientation, minimmum, maximum, value);
init(ready);
}
public JSliderExt(int orientation, int minimmum, int maximum, int value) {
super(orientation, minimmum, maximum, value);
init(READY_DEFAULT_VALUE);
}
public JSliderExt(int minimmum, int maximum, int value, boolean ready) {
super(minimmum, maximum, value);
init(ready);
}
public JSliderExt(int minimmum, int maximum, int value) {
super(minimmum, maximum, value);
init(READY_DEFAULT_VALUE);
}
public JSliderExt(int minimmum, int maximum, boolean ready) {
super(minimmum, maximum);
init(ready);
}
public JSliderExt(int minimmum, int maximum) {
super(minimmum, maximum);
init(READY_DEFAULT_VALUE);
}
public JSliderExt(int orientation, boolean ready) {
super(orientation);
init(ready);
}
public JSliderExt(int orientation) {
super(orientation);
init(READY_DEFAULT_VALUE);
}
public JSliderExt(boolean ready) {
super();
init(ready);
}
public JSliderExt() {
super();
init(READY_DEFAULT_VALUE);
}
private void init(boolean ready) {
UIManager.addPropertyChangeListener(new PropertyChangeListener() { // Changes the UI delegate in L&F change
#Override
public void propertyChange(PropertyChangeEvent event) {
if ("lookAndFeel".equals(event.getPropertyName())) {
Object newValue = event.getNewValue();
if ((newValue != null) && (newValue instanceof LookAndFeel)) {
LookAndFeel lookAndFeel = (LookAndFeel) newValue;
try {
if (lookAndFeel instanceof MetalLookAndFeel) {
JSliderExt.this.uix = new MetalSliderUIExt();
} else if (lookAndFeel instanceof com.sun.java.swing.plaf.motif.MotifLookAndFeel) {
JSliderExt.this.uix = new MotifSliderUIExt(JSliderExt.this);
} else if (lookAndFeel instanceof com.sun.java.swing.plaf.windows.WindowsLookAndFeel) {
JSliderExt.this.uix = new WindowsSliderUIExt(JSliderExt.this);
} else {
throw new NullPointerException("Default Look & Feel not matched");
}
} catch (Exception e) {
try {
Package sliderPackage = JSliderExt.this.getClass().getPackage();
String lookAndFeelName = lookAndFeel.getName();
if (lookAndFeelName.equals("CDE/Motif")) {
lookAndFeelName = "Motif";
} else if (lookAndFeelName.equals("Windows Classic")) {
lookAndFeelName = "Windows";
} else if (lookAndFeelName.startsWith("JGoodies")) {
lookAndFeelName = "Basic";
}
Class<?> sliderUiType = Class.forName(sliderPackage.getName() + "." + lookAndFeelName
+ "SliderUIExt");
Constructor<?> constructor1 = null;
try {
constructor1 = sliderUiType.getConstructor(JSlider.class);
} catch (Exception e3) { // Nothing to do here
}
Constructor<?> constructor0 = null;
try {
constructor0 = sliderUiType.getConstructor();
} catch (Exception e3) { // Nothing to do here
}
Object sliderUi = null;
if (constructor1 != null) {
sliderUi = constructor1.newInstance(JSliderExt.this);
} else if (constructor0 != null) {
sliderUi = constructor0.newInstance();
}
if ((sliderUi != null) && (sliderUi instanceof SliderUI)) {
JSliderExt.this.setUI((SliderUI) sliderUi);
}
} catch (Exception e2) {
JSliderExt.this.uix = new BasicSliderUIExt(JSliderExt.this);
}
}
} else {
JSliderExt.this.uix = new BasicSliderUIExt(JSliderExt.this);
}
updateUI();
}
}});
addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent event) {
String propertyName = event.getPropertyName();
if (READY_PROPERTY.equals(propertyName)) {
Object newValue = event.getNewValue();
if ((newValue == null) || (!(newValue instanceof Boolean)) || (((Boolean) newValue).booleanValue())) {
setSelectedValue(Integer.valueOf(getValue()));
} else {
setSelectedValue(null);
}
} else if (SELECTED_VALUE_PROPERTY.equals(propertyName)) {
Object newValue = event.getNewValue();
System.out.println(newValue);
if ((newValue != null) && (newValue instanceof Integer)) {
int value = getValue();
int newSelectedValue = ((Integer) newValue).intValue();
if (value != newSelectedValue) {
setValue(newSelectedValue);
}
setReady(true);
} else {
setReady(false);
}
repaint();
} else if (VALUE_PROPERTY.equals(propertyName)) {
setReady(true);
Object newValue = event.getNewValue();
if ((newValue != null) && (newValue instanceof Integer)) {
setSelectedValue((Integer) newValue);
}
}
}});
addKeyListener(new KeyAdapter() { // Enables escape key for clearing value
#Override
public void keyPressed(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.VK_ESCAPE) {
JSliderExt.this.setReady(false);
}
}});
setReady(ready);
}
#Override
public void setValue(int value) {
int oldValue = getValue();
super.setValue(value);
firePropertyChange(VALUE_PROPERTY, Integer.valueOf(oldValue), Integer.valueOf(value));
}
#Override
public void setExtent(int extent) {
int oldExtent = getExtent();
super.setExtent(extent);
firePropertyChange(EXTENT_PROPERTY, Integer.valueOf(oldExtent), Integer.valueOf(extent));
}
#Override
public void setMinimum(int minimum) {
int oldMinimum = getMinimum();
super.setMinimum(minimum);
firePropertyChange(MINIMUM_PROPERTY, Integer.valueOf(oldMinimum), Integer.valueOf(minimum));
}
#Override
public void setMaximum(int maximum) {
int oldMaximum = getMaximum();
super.setMaximum(maximum);
firePropertyChange(MAXIMUM_PROPERTY, Integer.valueOf(oldMaximum), Integer.valueOf(maximum));
}
public Integer getSelectedValue() {
return (Integer) getClientProperty(SELECTED_VALUE_PROPERTY);
}
public void setSelectedValue(Integer selectedValue) {
putClientProperty(SELECTED_VALUE_PROPERTY, selectedValue);
}
public boolean isReady() {
Object ready = getClientProperty(READY_PROPERTY);
return ((ready != null) && (ready instanceof Boolean)) ? ((Boolean) ready).booleanValue()
: READY_DEFAULT_VALUE;
}
public void setReady(boolean waiting) {
putClientProperty(READY_PROPERTY, Boolean.valueOf(waiting));
}
#Override
public void updateUI() {
setUI(this.uix);
updateLabelUIs();
}
}
Please note that using this code, might require some changes on selecting the delegates depending on your application, since this is intended for a Windows system. As said, Synth/Nimbus has to be worked in a different manner, but also any custom L&F or for OSX, needs the proper delegate to be extended and added on the listener.
I have following editor class, and I'm curious what's wrong with it. When running, it does correctly set the right radio button as selected. However, when flushing the top level editor, getValue is never called, and my object's property never get updated. Here's the code (hint - modified ValueListBox):
public class ValueRadioList<T> extends FlowPanel implements
HasConstrainedValue<T>, LeafValueEditor<T>, ValueChangeHandler<Boolean> {
private final List<T> values = new ArrayList<T>();
private final Map<Object, Integer> valueKeyToIndex =
new HashMap<Object, Integer>();
private final String name;
private final Renderer<T> renderer;
private final ProvidesKey<T> keyProvider;
private T value;
public ValueRadioList(Renderer<T> renderer) {
this(renderer, new SimpleKeyProvider<T>());
}
public ValueRadioList(Renderer<T> renderer, ProvidesKey<T> keyProvider) {
super();
this.name = DOM.createUniqueId();
this.keyProvider = keyProvider;
this.renderer = renderer;
}
private void addValue(T value) {
Object key = keyProvider.getKey(value);
if (valueKeyToIndex.containsKey(key)) {
throw new IllegalArgumentException("Duplicate value: " + value);
}
valueKeyToIndex.put(key, values.size());
values.add(value);
RadioButton radio = new RadioButton(name, renderer.render(value));
radio.addValueChangeHandler(this);
add(radio);
assert values.size() == getWidgetCount();
}
#Override public HandlerRegistration addValueChangeHandler(
ValueChangeHandler<T> handler) {
return addHandler(handler, ValueChangeEvent.getType());
}
#Override public T getValue() {
return value;
}
#Override public void onValueChange(ValueChangeEvent<Boolean> event) {
int selectedIndex = -1;
for (int i = 0, l = getWidgetCount(); i < l; i++) {
if (((RadioButton) getWidget(i)).getValue()) {
selectedIndex = i;
break;
}
}
if (selectedIndex < 0) {
return; // Not sure why this happens during addValue
}
T newValue = values.get(selectedIndex);
setValue(newValue, true);
}
#Override public void setAcceptableValues(Collection<T> newValues) {
values.clear();
valueKeyToIndex.clear();
clear();
for (T nextNewValue : newValues) {
addValue(nextNewValue);
}
updateRadioList();
}
#Override public void setValue(T value) {
setValue(value, false);
}
#Override public void setValue(T value, boolean fireEvents) {
if (value == this.value
|| (this.value != null && this.value.equals(value))) {
return;
}
T before = this.value;
this.value = value;
updateRadioList();
if (fireEvents) {
ValueChangeEvent.fireIfNotEqual(this, before, value);
}
}
private void updateRadioList() {
Object key = keyProvider.getKey(value);
Integer index = valueKeyToIndex.get(key);
if (index == null) {
addValue(value);
}
index = valueKeyToIndex.get(key);
((RadioButton) getWidget(index)).setValue(true);
}
}
Solved it, my POJO missed a setter for that field.