I have an issue, I have a method which is an action performed. If the checkbox is ticked then additional fields become available. If not ticked then they are greyed out. So basically what I want is to add to this method. I have a first condition and now need to add a second condition to it. I pasted the code snippet below, basically what I need is to put it into an if else, but I get some errors. Any advise is much appreciated.
public void actionPerformed(ActionEvent e) {
boolean sel = _useSSL.isSelected();
_port.setUseSSL(sel);
_keystore.setEnabled(sel);
_passphrase.setEnabled(sel);
L_KEYSTORE.setEnabled(sel);
L_PASSPHRASE.setEnabled(sel);
}
Above is the working method, now I need to add in if _truststore.isSelected(); then execute something else.
How can I add this second Boolean condition to the method?
I think you can do it by building a method per boolean and binding them to one "action performed" method like this:
public void actionPerformedForUseSSL(boolean useSSL) {
_port.setUseSSL(useSSL);
_keystore.setEnabled(useSSL);
_passphrase.setEnabled(useSSL);
L_KEYSTORE.setEnabled(useSSL);
L_PASSPHRASE.setEnabled(useSSL);
}
public void actionPerformedForTrustStore(boolean trustStore) {
_port.setTrustStore(trustStore);
_a.setEnabled(trustStore);
_b.setEnabled(trustStore);
_c.setEnabled(trustStore);
}
//Fire this when action performed
public void actionPerformed() {
boolean sel = _useSSL.isSelected();
boolean trust = _trustStore.isSelected();
actionPerformedForUseSSL(sel);
if(trust) {
actionPerformedForTrustStore(trust);
}
}
Add or remove or mix any fields with this structure easily.
You can use it just like you have used 'sel' in "actionPerfomed" method like this:
public void actionPerformed(ActionEvent e) {
boolean sel = _useSSL.isSelected();
_port.setUseSSL(sel);
_keystore.setEnabled(sel);
_passphrase.setEnabled(sel);
L_KEYSTORE.setEnabled(sel);
L_PASSPHRASE.setEnabled(sel);
boolean trus = _truststore.isSelected();
//Use trus for the other things
}
You can use the following piece of code:
public void actionPerformed(ActionEvent e) {
boolean sel = _useSSL.isSelected();
_port.setUseSSL(sel);
_keystore.setEnabled(sel);
_passphrase.setEnabled(sel);
L_KEYSTORE.setEnabled(sel);
L_PASSPHRASE.setEnabled(sel);
boolean selOther= _truststore.isSelected();
if(selOther){
//perform task if the _truststore is selected
}
}
Related
I'm using preferences to save the sound settings in my game as a boolean value. However, when I first start the game, the boolean initializes to false (sound off), because I'm not initializing it elsewhere. I could initialize it to true in the create method, but then the game would just start with sounds on every time you start the game, and that would just defeat the purpose of preferences.
Otherwise it works fine, it's just that I want the boolean to initialize to true the first time you start the game and not every time you restart it.
Is there a way to do this with preferences or do I have to use some other kind of saving method?
Note: this is a desktop application
public Preferences getPreferences() {
if (preferences == null) {
preferences = Gdx.app.getPreferences("myPrefs");
}
return preferences;
}
private void generatePreferences() {
getPreferences().clear();
getPreferences().putBoolean("soundEnabled", true).flush();
getPreferences().putBoolean("notFirstLaunch", true).flush();
}
public void loadPreferences() {
if (!getPreferences().getBoolean("notFirstLaunch")) {
generatePreferences();
} else {
//read the prefs and do your stuff
}
}
I would suggest you a slightly different approach:
Firstly, I think that the perfect place to initialize prefs is create method of the main game class (the one that extends Game):
public void create () {
Prefs.initPrefs();
....other initialization....
}
Then, initPrefs method looks like:
private static final String MUSIC_ON = "music_on";
private static final String LANG = "lang";
public static void initPrefs() {
boolean needChange = false;
if (!pref.contains(MUSIC_ON)) {
pref.putBoolean(MUSIC_ON, true);
needChange = true;
}
//if no lang - select system default
if (!pref.contains(LANG)) {
String language = Locale.getDefault().getLanguage();
pref.putString(LANG, language);
needChange = true;
}
if (needChange) {
pref.flush();
}
}
And finally to toggle the music:
public static boolean isMusicOn() {
return pref.getBoolean(MUSIC_ON);
}
public static void toggleMusic() {
pref.putBoolean(MUSIC_ON, !isMusicOn());
pref.flush();
}
I know this is a few years old now but just in case anyone else was wondering.
I think what you need to do is add a default value to your getBoolean() method without calling flush().
In my game i have a method called isSoundOn() which i call when my sound button is created. The very first time you start your game after installing it, you probably wont have saved a preference which means that the method below has to default to something. if you add true to the getBoolean method then your game should initialize to true.
public boolean isSoundOn() {
return preferences.getBoolean("soundOn", true);
}
I want to make some processing every time when a particular DataObject is saved. If I understand NetBeans IDE API correctly, there is an Savable interface that can be used to implement saving options for custom editors. The problem here is that I do not want to implement my own editor, nor DataObject. I have a MIME type that is edited by a default Gsf editor (the common scripting language api) and has a GsfDataObject (I expect with the DOSavable). I want to keep all that way, just to add a hook, maybe a callback method or something, that would be called every time a save is done upon a given GsfDataObject (and I want a default save action be called, I dont want to override it).
So far I came to this simple solution but it seems ugly (it is more or less inspired by http://wiki.netbeans.org/DevFaqListenForSaveEvents ):
// I have a FileObject fobj
final DataObject dobj = DataObject.find(fobj);
dobj.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals(DataObject.PROP_MODIFIED)) {
if (!((Boolean) evt.getOldValue()) & ((Boolean) evt.getNewValue())) {
System.out.println(">>>> here it gets modified");
} else {
System.out.println(">>>> here the data object gets saved");
}
}
}
});
However, this is not called only when the save is done, but also when the file gets modified, but then the modifications are reverted by Ctrl + Z. It only checks whether the data object changes its state from modified to unmodified. Is there a way to hook to a save event only?
P.S.: I tried to call new SJDOSavable(dobj).add(); in the moment when the DataObject gets modified and then to remove it in the other branch. However, the handleSave method does not get called. SJDOSavable class is a simple Savable implemented according to DOSavable from the DataSystems API:
private static final class SJDOSavable extends AbstractSavable implements Icon {
final DataObject obj;
public SJDOSavable(DataObject obj) {
this.obj = obj;
}
#Override
public String findDisplayName() {
return obj.getNodeDelegate().getDisplayName();
}
#Override
protected void handleSave() throws IOException {
System.out.println(">>>>> but this does not get called");
}
#Override
public boolean equals(Object other) {
if (other instanceof SJDOSavable) {
SJDOSavable dos = (SJDOSavable) other;
return obj.equals(dos.obj);
}
return false;
}
#Override
public int hashCode() {
return obj.hashCode();
}
final void remove() {
unregister();
}
final void add() {
register();
}
#Override
public void paintIcon(Component c, Graphics g, int x, int y) {
icon().paintIcon(c, g, x, y);
}
#Override
public int getIconWidth() {
return icon().getIconWidth();
}
#Override
public int getIconHeight() {
return icon().getIconHeight();
}
private Icon icon() {
return ImageUtilities.image2Icon(obj.getNodeDelegate().getIcon(BeanInfo.ICON_COLOR_16x16));
}
}
Did you try this ?
http://wiki.netbeans.org/DevFaqListenForSaveEvents
Also if you want to listen to global Save events, it seems you can do that now.
https://netbeans.org/bugzilla/show_bug.cgi?id=140719
I'm working on a JavaFX application which will have several tab panes which I want to set to visible or hidden using check box which will send boolean flag to render or not to render the component.
Check box
final CheckMenuItem toolbarSubMenuNavigation = new CheckMenuItem("Navigation");
toolbarSubMenuNavigation.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent e)
{
// call here the getter setter and send boolean flag
System.out.println("subsystem1 #1 Enabled!");
}
});
Tab pane which will listen for the boolean property:
public boolean renderTab;
public boolean isRenderTab()
{
return renderTab;
}
public void setRenderTab(boolean renderTab)
{
this.renderTab = renderTab;
}
tabPane.setVisible(renderTab);
The check box and the tab pane are isolated into different Java Classes. I need to send the value of the flag every time when I check or uncheck the flag. Can you tell me how I can send the flag using getter and setter?
EDIT
I tested this code:
final CheckMenuItem toolbarSubMenuNavigation = new CheckMenuItem("Navigation");
toolbarSubMenuNavigation.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent e)
{
boolean dcd = toolbarSubMenuNavigation.isSelected();
DataTabs nn = new DataTabs();
nn.setRenderTab(dcd);
// call here the getter setter and send boolean flag
System.out.println("subsystem1 #1 Enabled!");
}
});
and
public boolean renderTab;
public boolean isRenderTab()
{
return renderTab;
}
public void setRenderTab(boolean renderTab)
{
this.renderTab = renderTab;
}
But it's not working when I switch the checkbox.
No.
Inorder to get that eithr you need to have a intance or you need to create new intance there.
If you create a new object there it will create a fresh intance,which doesnt helps you any more..
I guess the only way you have is to Make the renderTab as a static field and access there.
I seem not to grasp the concept of Events and such. After reading a while on how to implement the listeners and such I came across the Java tutorial saying I should extend AbstractListModel to get the data event firing. For some reason it still doesn't work.
Is there anything I'm doing wrong?
And what kind of code is expected at addListDataListener(ListDataListener l) for it to work? Since I don't understand that either.
public class CarComboBox extends AbstractListModel<Object> implements ComboBoxModel<Object> {
private JdbcRowSet jdbc;
private int size = 0;
private String selection;
public CarComboBox() {
try {
jdbc = new Query().getCarInfo();
jdbc.beforeFirst();
while (jdbc.next()) {
size++;
}
jdbc.beforeFirst();
}
catch (SQLException ex) {
System.err.println(ex.toString());
}
}
#Override
public void setSelectedItem(Object anItem) {
selection = (String) anItem;
}
#Override
public Object getSelectedItem() {
return selection;
}
#Override
public void addListDataListener(ListDataListener l) {
}
#Override
public void removeListDataListener(ListDataListener l) {
}
#Override
public int getSize() {
return size;
}
#Override
public String getElementAt(int index) {
try {
jdbc.absolute(index + 1);
return jdbc.getString(2);
}
catch (SQLException ex) {
System.out.println(ex.toString());
}
return null;
}
}
And to add a listener to the CarComboBox I do:
CarComboBox ccb = new CarComboBox();
ccb.addListDataListener(new ListDataListener()
I'm guessing that you are using the official tutorial.
However you should not touch ListModel and ComboBoxModel. Those are more advanced features you probably do not need.
The 4 examples in the tutorial do NOT use ListModel and ComboBoxModel.
If you use a standard JComboBox (no ListModel or ComboBoxModel), what happens is that when someone makes a selection, an ActionEvent is fired. This event is magically fired by Swing; you don't have to worry about how it is generated. However what is your responsibility is to have some (zero, one or more) objects being able to receive and do something about the ActionEvent:
public class MyClass implements ActionListener {
JComboBox comboBox = ...;
...
// You must register explicitly every ActionListener that you
// want to receive ActionEvent's from comboBox.
// Here we register this instance of MyClass.
comboBox.addActionListener(this);
...
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JComboBox) {
System.out.println("MyClass registered an ActionEvent from a JComboBox.");
System.out.println("Selected: " +
((JComboBox) e.getSource()).getSelectedItem());
}
}
}
Note that if you don't have any other ActionEvent's fired by different Swing components you
can skip the if (e.getSource() instanceof JComboBox) since you know your ActionEvent always comes from a JComboBox.
In my example the JComboBox is inside MyClass, but it does not have to be:
JComboBox comboBox = ...;
MyClass myClass = ...;
comboBox.addActionListener(myClass);
...
comboBox.addActionListener(someOtherActionListener);
You don't need to override addListDataListener() and removeListDataListener() method. The AbstractListModel already take care of the listeners. Here is the implementation of AbstractListModel.addListDataListener():
public void addListDataListener(ListDataListener l) {
listenerList.add(ListDataListener.class, l);
}
The idea of abstract classes is that they do most of the work for you. Usually you only need to implement abstract methods.
XXListener and XXModel are different sides of the coin: the former is the observer to the latter which is the observable. The listener registers itself to the model when it wants to get notified on changes. It's the responsibility of the model to
manage its listeners (that's typically handled already by the AbstractXXModel, as already explained by #userWhateverNumber ;)
fire the notifications if appropirate: that's the part a custom model must take over, in your case
like
#Override
public void setSelectedItem(Object item) {
selection = item;
fireContentChanged(this, -1, -1);
}
Arguably (there are personal preferences around :-) you often don't need custom model implementations but can just as well re-use the provided DefaultXXModels. In your context and assuming the content of the resultset is immutable it might be an option to fill the default model with the data at construction time, like
DefaultComboBoxModel model = new DefaultComboBoxModel();
forEachRowInResultSet {
model.addElement(resultSet.getString(2));
}
If, on the other hand, the content changes then your model implementation is invalid anyway: the model must notify its listeners whenever something had changed
Object one = model.getElementAt(index);
Object other = model.getElementAt(index)
if (!one.equals(other)) {
listener must have received a contentsChanged
}
I want to remove a GWT event handler the first time I receive an event. I also want to avoid polluting my class with tracking registration objects that aren't really necessary. I currently have it coded as:
final HandlerRegistration[] registrationRef = new HandlerRegistration[1];
registrationRef[0] = dialog.addFooHandler(new FooHandler()
{
public void onFoo(FooEvent event)
{
HandlerRegistration removeMe = registrationRef[0];
if(removeMe != null)
{
removeMe.removeHandler();
}
// do stuff here
}
});
but the use of registrationRef makes the code less readable. Is there a better way to do this without adding variables to my class?
I'd just make the HandlerRegistration object a field of the enclosing class, that way you won't be bothered by the compiler and it's more "elegant" than shuffling arrays and stuff:
public class TestWidget extends Composite {
//...
HandlerRegistration handler;
public TestWidget() {
// ...
handler = button.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
// ...
handler.removeHandler();
}
});
}
}