Transmission of values between a inner class and outer class - java

I am struggling a long time now with the following problem:
I do not understand why the method setStatus () does not work. The method setButton () check whether the individual elements in a field "status" to "true" if all this have to activate a button. Unfortunately staus field values ​​do not change.
I'd like to add, that textBox.setTitle() and textBox.addStyleName work well.
Here is my code:
package com.mg;
import java.util.ArrayList;
import com.comarch.spr.client.UserServlet;
import com.comarch.spr.client.UserServletAsync;
import com.gargoylesoftware.htmlunit.javascript.host.Window;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.TextBox;
public class Validator {
private ArrayList<ValidationElement> listOfElements = new ArrayList<Validator.ValidationElement>();
private Button button;
public int i = 0;
public Validator(ArrayList<ValidationElement> listOfElements, Button button) {
this.listOfElements = listOfElements;
this.button = button;
}
public void createElement0(TextBox textbox, String regex, int type, UserServletAsync userServlet ) {
ValidationElement element = new ValidationElement(textbox, regex, type, userServlet);
listOfElements.add(element);
}
public void createElement1(TextBox textbox, String regex, int type ) {
ValidationElement element = new ValidationElement(textbox, regex, type);
listOfElements.add(element);
}
public void addElement(ValidationElement element) {
listOfElements.add(element);
}
public void setButton() {
int sizeOfList = listOfElements.size();
int check = 0;
for(ValidationElement element : listOfElements) {
element.validate();
if (element.status == true)
check = check + 1;
}
if (check != 0)
button.setEnabled(true);
else
button.setEnabled(false);
}
//========================== VALIDATION ELEMENT CLASS===========================
public class ValidationElement {
public TextBox textBox = new TextBox();
public boolean status;
public String regex;
public int type; // 0 - validateFromDatabase() , || 1 - checkRegEx()
public UserServletAsync userServlet;
public ValidationElement(TextBox textbox, String regex, int type ) {
this.textBox = textbox;
this.regex = regex;
this.type = type;
}
public ValidationElement(TextBox textbox, String regex, int type, UserServletAsync userServlet) {
this.textBox = textbox;
this.regex = regex;
this.type = type;
this.userServlet = userServlet;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
//========================== VALIDATION FUNCTIONS =========================================
public void validate() {
if (type == 0) {
validateFromDatabase();
}
else if(type == 1)
checkRegEx();
}
public void validateFromDatabase() {
textBox.addBlurHandler(new BlurHandler() {
#Override
public void onBlur(BlurEvent event) {
final String text = textBox.getText();
userServlet.validateUser(textBox.getText(), new AsyncCallback<Boolean>() {
public void onFailure(Throwable caught) {
}
public void onSuccess(Boolean result) {
boolean resultOfCallback = result;
if(resultOfCallback){
textBox.addStyleName("invalid");
textBox.setTitle("error");
}
else if (text.matches(regex) && !resultOfCallback) {
textBox.setStyleName("gwt-TextBox");
setStatus(true);
}
else if (text.matches(regex) && resultOfCallback) {
}
else {
textBox.addStyleName("invalid");
textBox.setTitle("error");
}
}
});
}
});
}
public void checkRegEx () {
textBox.addKeyPressHandler(new KeyPressHandler() {
#Override
public void onKeyPress(KeyPressEvent event) {
final String text = textBox.getText();
if(!text.matches(regex))
{
setStatus(false);
}
else {
setStatus(true);
}
isValid();
}
});
textBox.addBlurHandler(new BlurHandler() {
public void onBlur(BlurEvent event) {
final String text = textBox.getText();
if(!text.matches(regex))
{
textBox.addStyleName("invalid");
textBox.setTitle("error");
setStatus(false);
}
else
{
setStatus(true);
textBox.setStyleName("gwt-TextBox");
textBox.setTitle("error");
}
}
});
}
public void isValid() {
if(this.status = true)
i=i+1;
}
}
}

public void isValid() {
if(this.status = true)
i=i+1;
}
Shouldn't this be
public void isValid() {
if(this.status == true)
i=i+1;
}
The first method sets the status to true, then always increments i.
Or you can go one better:
public void isValid() {
if(this.status) {
i++;
}
}
Also if you're using Eclipse, you can set the compiler options to highlight accidental boolean assignments in if statements as compilation errors. It's a very useful option.

In class Validator, there is:
public int i = 0;
In class ValidationElement, which is inside Validator, in for example checkRegEx() method, I put:
i++;
public void checkRegEx () {
textBox.addKeyPressHandler(new KeyPressHandler() {
#Override
public void onKeyPress(KeyPressEvent event) {
final String text = textBox.getText();
if(!text.matches(regex))
{
setStatus(false);
}
else {
setStatus(true);
}
isValid();
}
});
textBox.addBlurHandler(new BlurHandler() {
public void onBlur(BlurEvent event) {
final String text = textBox.getText();
if(!text.matches(regex))
{
textBox.addStyleName("invalid");
textBox.setTitle("error");
setStatus(false);
}
else
{
textBox.setStyleName("gwt-TextBox");
textBox.setTitle("ok");
i++;
}
}
});
}
When I want to see if everything is okay. It turns out that the value of "i" in setButton() method in class Validator is still zero, while the other lines of code in this block work well:
textBox.setStyleName("gwt-TextBox");
textBox.setTitle("ok");

Most likely it's just too early to check status at the next line after validate() is invoked.
As far as I can tell status changes only after BlurEvent happens. TextBox updates you mention work fine because these seem to be triggered at the right moment.
public void setButton() {
int sizeOfList = listOfElements.size();
int check = 0;
button.setEnabled(false); // reset button
for(ValidationElement element : listOfElements) {
element.validate();
// drop attempt to check status here
}
// drop attempt to enable button here
}
//...
{
button.setEnabled(true); // was: setStatus(true);
textBox.setStyleName("gwt-TextBox");
textBox.setTitle("error");
}
Also I would prefer to define ValidationElement
static:
public static class ValidationElement
// have quite a painful experience chasing subtle bugs
// related to named non-static inner classes

Related

Custom JSpinner Model not working

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.

Expanding one field while others are collapsed in blackberry java

I am developing an app in which i am adding and deleting fields based on setting flag to true or false.but what i am trying to do is if i click on field that particular field should expand while others are collapsed(even if it is expanded)
i googled it but i didnt get solution please help me i am new to blackberry java
i have used below code
public final class MyScreen extends MainScreen implements
FieldChangeListener
{
/**
* Creates a new MyScreen object
*/
private VerticalFieldManager main_manager;
private HorizontalFieldManager parentNodes;
private LabelField parent_lables[];
private Bitmap bitmap,upbitmap;
private BitmapField bitmap_field[];
private VerticalFieldManager submanager[];
private int sizeOfParentNodes=3;
private int sizeOfChildNodes=5;
private static boolean flag[];
public MyScreen()
{
// Set the displayed title of the screen
bitmap=Bitmap.getBitmapResource("arrow.png");
upbitmap=Bitmap.getBitmapResource("uparrow.png");
main_manager=new
VerticalFieldManager(Manager.VERTICAL_SCROLL|VERTICAL_SCROLLBAR){
protected void sublayout(int maxWidth, int maxHeight) {
super.sublayout(Display.getWidth(), Display.getHeight());
setExtent(Display.getWidth(), Display.getHeight());
};
};
parent_lables=new LabelField[sizeOfParentNodes];
flag=new boolean[sizeOfParentNodes];
submanager=new VerticalFieldManager[sizeOfParentNodes];
bitmap_field=new BitmapField[sizeOfParentNodes];
for(int i=0;i<sizeOfParentNodes;i++)
{
submanager[i]=new VerticalFieldManager();
updateGUI(i);
main_manager.add(submanager[i]);
}
add(main_manager);
}
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
synchronized (UiApplication.getEventLock()) {
for(int i=0;i<sizeOfParentNodes;i++)
{ if(field==parent_lables[i])
{
if(flag[i]==true){
flag[i]=false;
submanager[i].deleteAll();
updateGUI(i);
parent_lables[i].setFocus();
}else{
flag[i]=true;
bitmap_field[i].setBitmap(upbitmap);
submanager[i].invalidate();
}
}
}
}
}
public void updateGUI(int index)
{
parentNodes=new HorizontalFieldManager(USE_ALL_WIDTH);
bitmap_field[index]=new BitmapField(bitmap);
parentNodes.add(bitmap_field[index]);
parent_lables[index]=new LabelField("Day"+index,Field.FOCUSABLE){
protected boolean navigationClick(int status, int time) {
fieldChangeNotify(1);
return true;
};
};
parentNodes.add(parent_lables[index]);
parent_lables[index].setChangeListener(this);
submanager[index].add(parentNodes);
}
}
I knocked this together, and will likely need some tweaks by you to get it exactly how you want it, but it should be something you can work from. Assuming I've understood your question correctly.
You'll need to create a base field, a helper able to manage a list of them, and a callback. The fact that you need a base field is the biggest downfall, because it immediately excludes all other widgets you have, as they need to be made from scratch with the paint method. You can use a VerticalFieldManager instead of field by extending VerticalFieldManager instead of Field.
On to the java classes.
My CollapsableField.java looks as follows:
public abstract class CollapsableField extends Field
{
// We make use of a different listener than the FieldChangeListener, since you can only attach one and we will most likely want to do so, we can't "occupy" the listener.
private CollapseListener listener;
private boolean collapsed;
protected int collapsedWidth;
protected int collapsedHeight;
public CollapsableField()
{
collapsed = true;
// Field is completely collapsed by default
collapsedWidth = 0;
collapsedHeight = 0;
}
public void setCollapseListener(CollapseListener listener)
{
this.listener = listener;
}
public final boolean isCollapsed()
{
return collapsed;
}
public final void collapse()
{
this.collapsed = true;
if (listener != null)
{
listener.onCollapse(this);
}
fieldChangeNotify(0); // Notify that the field has changed, so that attached field change listeners will fire
updateLayout(); // re-call layout
}
public final void expand()
{
this.collapsed = false;
if (listener != null)
{
listener.onExpand(this);
}
fieldChangeNotify(0); // Notify that the field has changed, so that attached field change listeners will fire
updateLayout(); // re-call layout
}
protected void layout(int width, int height)
{
if (collapsed)
{
// Set dimensions to collapsed
setExtent(collapsedWidth, collapsedHeight);
}
else
{
// Set dimensions to what the extending class specified
setExtent(width, height);
}
}
protected final void paint(Graphics graphics)
{
if (collapsed)
{
paintCollapsed(graphics);
}
else
{
paintExpanded(graphics);
}
}
protected abstract void paintCollapsed(Graphics graphics);
protected abstract void paintExpanded(Graphics graphics);
}
The Group then takes a list of these, applies a listener to each field as it's added. When a field signals that it has expanded, the group will tell all other fields to collapse themselves.
CollapsableGroup.java:
public class CollapsableGroup
{
private Vector fields;
private CollapseListener listener;
public CollapsableGroup()
{
fields = new Vector();
listener = new CollapseListener()
{
public void onExpand(CollapsableField source)
{
for (int i = 0; i < fields.size(); i++)
{
CollapsableField field = (CollapsableField) fields.elementAt(i);
if ((!field.isCollapsed()) && (field != source))
{
field.collapse();
}
}
}
public void onCollapse(CollapsableField source)
{
// Don't need to handle this. Method is here just for completeness
}
};
}
public void add(CollapsableField field)
{
field.setCollapseListener(listener);
fields.addElement(field);
}
public void remove(CollapsableField field)
{
field.setCollapseListener(null);
fields.removeElement(field);
}
/**
* Returns the currently expanded field. Returns <b>null</b> if all fields are collapsed.
*
* #return
*/
public CollapsableField getExpandedField()
{
for (int i = 0; i < fields.size(); i++)
{
CollapsableField field = (CollapsableField) fields.elementAt(i);
if (!field.isCollapsed())
{
return field;
}
}
return null;
}
public void expand(CollapsableField field)
{
field.expand(); // Listeners should take care of the rest
}
public void collapseAll()
{
for (int i = 0; i < fields.size(); i++)
{
CollapsableField field = (CollapsableField) fields.elementAt(i);
if (!field.isCollapsed())
{
field.collapse();
}
}
}
}
And finally the listener interface.
CollapseListener.java:
interface CollapseListener
{
public void onExpand(CollapsableField source);
public void onCollapse(CollapsableField source);
}
Those three classes should be all that you need. The classes that follow are my example/test classes.
TestLabel.java is an example of an extended class:
public class TestLabel extends CollapsableField
{
private String text;
private String collapsedText;
public TestLabel(String text, String collapsedText)
{
this.text = text;
this.collapsedText = collapsedText;
// Tells the layout method to collapse to the size of this text
collapsedWidth = getFont().getAdvance(collapsedText);
collapsedHeight = getFont().getHeight();
}
public int getPreferredWidth()
{
return getFont().getAdvance(text);
}
public int getPreferredHeight()
{
return getFont().getHeight();
}
protected void layout(int width, int height)
{
super.layout(getPreferredWidth(), getPreferredHeight());
}
protected void paintCollapsed(Graphics graphics)
{
// Paints only the collapsedText
graphics.drawText(collapsedText, 0, 0);
}
protected void paintExpanded(Graphics graphics)
{
// Paints the full Text
graphics.drawText(text, 0, 0);
}
protected boolean touchEvent(TouchEvent message)
{
// Toggle on mouse press
if (message.getEvent() == TouchEvent.CLICK)
{
if (isCollapsed())
{
expand();
}
else
{
collapse();
}
return true;
}
return super.touchEvent(message);
}
}
The following screen contains some of the fields to show that both the widgets themselves and the group can manipulate the fields.
MyScreen.java:
public final class MyScreen extends MainScreen
{
public MyScreen()
{
// Set the displayed title of the screen
setTitle("MyTitle");
final CollapsableGroup group = new CollapsableGroup();
final TestLabel label1 = new TestLabel("Label1", "L1");
label1.setBackground(BackgroundFactory.createSolidBackground(0x999999));
group.add(label1);
final TestLabel label2 = new TestLabel("Label2", "L2");
label2.setBackground(BackgroundFactory.createSolidBackground(0xBBBBBB));
group.add(label2);
final TestLabel label3 = new TestLabel("Label3", "L3");
label3.setBackground(BackgroundFactory.createSolidBackground(0xDDDDDD));
group.add(label3);
ButtonField collapseAll = new ButtonField("Collapse All")
{
protected boolean navigationClick(int status, int time)
{
group.collapseAll();
return true;
}
};
add(collapseAll);
ButtonField expand1 = new ButtonField("Expand1")
{
protected boolean navigationClick(int status, int time)
{
group.expand(label1);
return true;
}
};
add(expand1);
ButtonField expand2 = new ButtonField("Expand2")
{
protected boolean navigationClick(int status, int time)
{
group.expand(label2);
return true;
}
};
add(expand2);
ButtonField expand3 = new ButtonField("Expand3")
{
protected boolean navigationClick(int status, int time)
{
group.expand(label3);
return true;
}
};
add(expand3);
add(label1);
add(label2);
add(label3);
}
}

Listener inside a loop won't allow to change an outsider boolean flag

Following my previous post here , I wrote a listener :
#Override
public void keyTyped(KeyEvent keyEvent)
{
PolygonFiller polyFiller = new PolygonFiller();
char key = keyEvent.getKeyChar();
final boolean runForever = true;
switch(key)
{
/**
* Fill the polygons
*/
case FILL_POLYGON:
{
if (greenLightForFilling == true)
{
while (runForever)
{
fillPolygon(polyFiller);
KeyListener listener = new KeyListener()
{
public void keyPressed(KeyEvent keyEvent)
{
char keyOther = keyEvent.getKeyChar();
if (keyOther == 'F' || keyOther == 'f')
// can't use break;
runForever = false;
}
#Override
public void keyReleased(KeyEvent arg0) {}
#Override
public void keyTyped(KeyEvent arg0) {}
};
}
}
break;
} // end FILL_POLYGON
case FILL_POLYGON_LOWERCASE:
{
if (greenLightForFilling == true)
{
fillPolygon(polyFiller);
}
break;
}
/**
* save all polygons in a .scn file
*/
case SAVE_POLYGONS :
{
if (greenLightForFilling == true)
{
saveWorkspace();
}
break;
} // end SAVE_POLYGONS
case SAVE_POLYGONS_LOWERCASE:
{
if (greenLightForFilling == true)
{
saveWorkspace();
}
break;
}
/**
* Delete everything & load all polygons from .scn file
*/
case LOAD_POLYGONS:
{
loadWorkspace();
break;
}
case LOAD_POLYGONS_LOWERCASE:
{
loadWorkspace();
break;
}
default: break;
} // end switch
}
The goal :
break from the loop , when I get a second f or F (I already got one f/F when I entered to loop) .
Do I need to attach the second listener to something ?
But I can't change the runForever to false , since it's written outside .
Even if I change it to final , I can't change its value to false either .
Any way around this ?
Note : I already have a key-listener for entering the switch-case!!
EDIT:
// Hot-keys hit by the user - used for keyboard listening
private static final char FILL_POLYGON = 'F';
private static final char SAVE_POLYGONS = 'S';
private static final char LOAD_POLYGONS = 'L';
private static final char FILL_POLYGON_LOWERCASE = 'f';
private static final char SAVE_POLYGONS_LOWERCASE = 's';
private static final char LOAD_POLYGONS_LOWERCASE = 'l';
#Override
public void keyTyped(KeyEvent keyEvent)
{
PolygonFiller polyFiller = new PolygonFiller();
char key = keyEvent.getKeyChar();
final Settable runForever = new Settable();
switch(key)
{
/**
* Fill the polygons
*/
case FILL_POLYGON:
{
if (greenLightForFilling == true)
{
KeyListener listener = new KeyListener()
{
public void keyPressed(KeyEvent keyEvent)
{
char keyOther = keyEvent.getKeyChar();
if (keyOther == 'F' || keyOther == 'f')
runForever.set(false);
}
#Override
public void keyReleased(KeyEvent arg0) {}
#Override
public void keyTyped(KeyEvent arg0) {}
};
this.addKeyListener(listener);
while (runForever.get())
{
fillPolygon(polyFiller);
}
}
break;
} // end FILL_POLYGON
...
}
Final variables cannot be changed, but if they represent a mutable object, you can change the content of that object.
For example, if you make a Settable class, and use its instance instead of boolean, you could do this:
class Settable {
private boolean flag;
public boolean get() {return flag;}
public boolean set(boolean val) { flag = val; }
}
Now, use a final instance of Settable in your code; use set(...) instead of the assignment, and get() instead of a direct access:
final Settable runForever = new Settable();
runForever.set(true);
...
while (runForever.get()) {
...
if (keyOther == 'F' || keyOther == 'f') runForever.set(false);
...
}
please did you read comment by #kleopatra in your previous post, not good idea to ignore that
not never, not wrong direction, use KeyBindings and with Swing Action instead of KeyListener
accepted answer by #dasblinkenlight solved nothing in Swing, Swing and Java2D, use KeyBindings and with Swing Action,
for example
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
public class FullScreen {
private static final long serialVersionUID = 1L;
private JButton button = new JButton("Close Meeee");
private JPanel myPanel = new JPanel();
private JFrame frame = new JFrame();
public FullScreen() {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
myPanel = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 300);
}
};
myPanel.setFocusable(true);
myPanel.add(button);
frame.add(myPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setUndecorated(true);
frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
KeyStroke.getKeyStroke("ENTER"), "clickENTER");
frame.getRootPane().getActionMap().put("clickENTER", updateBol());
frame.pack();
frame.setVisible(true);
updateCol().setEnabled(false);
updateDol().setEnabled(false);
}
private Action updateBol() {
return new AbstractAction("updateBol") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("updateCol is " + updateBol().isEnabled());
System.out.println("updateBol is " + updateCol().isEnabled());
System.out.println("updateDol is " + updateDol().isEnabled());
updateCol().actionPerformed(e);
updateDol().actionPerformed(e);
}
};
}
private Action updateCol() {
return new AbstractAction("updateCol") {
private static final long serialVersionUID = 1L;
private Boolean _enabled = false;
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("updateCol is " + updateCol().isEnabled());
if (updateCol().isEnabled()) {
} else {
}
}
public void setEnabled(Boolean bol) {
_enabled = bol;
}
#Override
public boolean isEnabled() {
return _enabled;
}
};
}
private Action updateDol() {
return new AbstractAction("updateDol") {
private static final long serialVersionUID = 1L;
private Boolean _enabled = false;
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("updateDol is " + updateDol().isEnabled());
if (updateCol().isEnabled()) {
} else {
}
}
public void setEnabled(Boolean bol) {
_enabled = bol;
}
#Override
public boolean isEnabled() {
return _enabled;
}
};
}
public static void main(String[] args) {
Runnable doRun = new Runnable() {
#Override
public void run() {
FullScreen fullScreen = new FullScreen();
}
};
SwingUtilities.invokeLater(doRun);
}
}
You can make final array of boolean of size 1 to store your flag. Even if array is final, it's elements are not, so you can modify array's elements from anonymous classes.

Is possible to set an unknown value on a JSlider?

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.

Customize listfield item on BlackBerry

I have a simple list field class which shows the default menu when I select a particular listitem. I want to customize the listfield item, so that when an item is selected a new screen is pushed onto the stack. I am overridding trackwheeel() method, but am not able to make it work.
import net.rim.device.api.system.*;
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import java.util.Vector;
public class TeamListScreen extends UiApplication
{
public static void main(String[] args)
{
TeamListScreen theApp = new TeamListScreen();
theApp.enterEventDispatcher();
}
public TeamListScreen()
{
pushScreen(new ListFieldScreen());
}
}
class ListFieldScreen extends MainScreen
{
private ListField _listField;
private Vector _listElements;
int listFieldIndex = -1;
public ListFieldScreen()
{
setTitle("List Field Sample");
_listElements = new Vector();
_listField = new ListField();
ListCallback _callback = new ListCallback();
_listField.setCallback(_callback);
_listField.setRowHeight(45);
//_listField.setChangeListener(this);
add(_listField);
initializeList();
_listField = new ListField(_listElements.size()) {
protected void drawFocus(Graphics graphics, boolean on) {
}
protected boolean trackwheelClick(int status, int time) {
listFieldIndex = _listField.getSelectedIndex();
if (listFieldIndex < 0) {
listFieldIndex = 0;
}
try {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
UiApplication.getUiApplication().pushScreen(new LiveScreen());
// UiApplication.getUiApplication().popScreen(getActiveScreen());
}
});
} catch (Exception e) {
}
return true;
}
};
}
private void initializeList()
{
String itemOne = "List item one";
String itemTwo = "List item two";
_listElements.addElement(itemOne);
_listElements.addElement(itemTwo);
reloadList();
}
private void reloadList()
{
_listField.setSize(_listElements.size());
}
private class ListCallback implements ListFieldCallback
{
public void drawListRow(ListField list, Graphics g, int index, int y, int w)
{
String text = (String)_listElements.elementAt(index);
g.drawText(text, 0, y, 0, w);
}
public Object get(ListField list, int index)
{
return _listElements.elementAt(index);
}
public int indexOfList(ListField list, String prefix, int string)
{
return _listElements.indexOf(prefix, string);
}
public int getPreferredWidth(ListField list)
{
return Display.getWidth();
}
}
}
trackwheelClick() function is deprecated, you should use navigationClick() instead.
BTW, you don't need to use UiApplication.getUiApplication().invokeLater, because it is already running in the event queue.

Categories