I am working on a GUI java program for class where there are 10 numbered buttons in a grid layout. The user is trying to guess a 3 digit number where each digit is unique. When they click a number the corresponding number should be stored as one of the digits in the guess and then the button should be disabled. This is done in the actionPerformed method.
My problem is how to tell which button is disabled.
Currently I am trying to successfully read the value and disable the button for one digit and my code looks like this:
private class NumberListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent click){
Object source = click.getSource();
keyTry1 = getButtonNumber(source);
source.setEnabled(false); //error
}
However at the line I marked error NetBeans complains that source has no method setEnabled, presumably because in the method it is declared as type Object. However if I try to declare it as JButton I cannot use click.getsource();
I know I could go the brute force approach and have a long string of if/else statements or even another method which disables the button based on the number it represents, but I was wondering if there is a way to access source as a JButton, since it obviously is referencing a JButton.
source is an Object and does not have an setEnabled method, so it makes no sense to the compiler to allow you to make such a call. You need to first case the instance of source to it's appropriate class type.
Assuming you can guarantee that the source of the action is the button, you can use something like...
((JButton)click.getSource()).setEnabled(false);
If you can't guarantee that source is JButton, but might be component of some kind, you might even be able to use something like...
((Component)click.getSource()).setEnabled(false);
If you can't guarantee that, then you need to make appropriate checks (which you should do anyway)...
Object source = click.getSource();
if (source instanceof JButton) {
((JButton)source).setEnabled(false);
}
This concept is an example of Polymorphism, where one instance of an Object can act like one it's parents
Related
(A general Question)
I have an assignment in which I have to build a sudoku and I thought about the classes/logic to build it and thought I could use an advice.
I want to use a JFrame and build on it a JPanel with TextFields (the user is supposed to "solve" the sudoku).
I have a class called "DrawSudoku" which draws an empty board. I have to draw an empty board first, so the "user" can type numbers in it.
On that board I have to check some logic. So I have to access the textFields themselves.
So far that's all I've done. Now I am thinking about building another class with the "logic" behind the board.
But I've encountered a problem
How do I get the JTextFields that exists on the JPanel, from another class?
Can I have separate classes for the Drawing and Logic Behind it?
Thanks!
On that board I have to check some logic. So I have to access the textFields themselves.
Not necessarily
How do I get the JTextFields that exists on the JPanel, from another class?
How do you assess the state of any object from another object -- via an accessor or "getter" method.
Can I have separate classes for the Drawing and Logic Behind it?
Not only can you, you absolutely should.
If this were my project I would consider doing the following:
First and foremost, create a non-GUI Sudoku model class. This could include:
SudokuCellValue enum (name it what you want), an enum that can hold a value from 1 to 9 as well as possibly an EMPTY value (although you could use null to represent this)
SudokuCell objects, ones that have boolean editable, and holds a single value to the above enum.
SudokuGrid object, a 9 x 9 grid of SudokuCells.
A mechanism to hook listeners into the model so that they are notified of changes in state -- i.e., changes in the SudokuCellValue held by one or more SudokuCell objects. The View (the GUI) will be one of the major listeners to this model, and will change its display when the model's state changers.
I'd create a View class, meaning the GUI,
One that holds a reference to its model (see above)
and one that has attached listeners to its model -- I like to use PropertyChangeListeners for this
I'd hook it up with a grid of JTextFields,
These text fields would use a DocumentFilter to allow the user to either clear the field or enter only 1 through 9 single digit numeric text.
Would be enabled for input (or perhaps better -- focusable for input), based on the editable state of the corresponding model cell.
I'd create a Controller that would control some of the communication between the view and model.
With this type of set up, outside classes could listen for changes to the model and wouldn't have to have any access directly to the JTextFields of the view.
You don't need to have access to the text fields themselves if you include public methods in your DrawSudoku class that your logic class can then call. This would be very similar to writing getter and setter methods for private variables. For example, if you wanted your logic class to be able to write the number "6" into a certain square on the board, you could write a method in DrawSudoku like this:
public void setSquareText(String text, int row, int column) {
// change the appropriate text field here
textField.setText(text);
}
Then, call this method in your logic class, by making an instance of the drawing class:
DrawSudoku drawer = new DrawSudoku();
drawer.setSquareText("6", 1,1);
Alternatively, you could write a method in DrawSudoku that returns a given JTextField, like this:
public JTextField getTextField(int row, int column){
// find the appropriate text field, then return it
return textField;
}
Then, call this method in your logic class to get access to the JTextField, like this:
JTextField textField = drawer.getTextField(1,1);
textField.getText();
textField.setText("6");
I have an application with a GUI with sliders and comboboxes mainly. I use the sliders and combos to change values and parameters in various classes in the project. I'm trying to implement the possibility to save and load this parameters and I have done so using the preferences API.
I can save and load parameters, but when I load them I can see the changes in values, so that works, but the GUI does not update to reflect those new values. is there a way to tell the GUI to do so?
For instance I have a frequency slider that changes the frequency value in an oscillator. If I change the value with the slider, save it, change the value of the slider again and then load the saved value, I can hear it has changed but the slider didn't move.(makes sense as I haven't told it too). Can I bind the position of the slider with that frequency value somehow?
gui
//OSC1 slider
JSlider Osc1FreqSlider = new JSlider(SwingConstants.HORIZONTAL, MIN_OSC_FREQ, MAX_OSC_FREQ, NOTE_A_FREQ);
Osc1FreqSlider.setOpaque(false);
Osc1FreqSlider.setMajorTickSpacing(50000);
Osc1FreqSlider.setMinorTickSpacing(50);
Osc1FreqSlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
JSlider source = (JSlider) e.getSource();
settings.setOsc1Freq((float)source.getValue()/100);
}
});
settings class
public void setOsc1Freq(float freq) {
m_Osc1Freq = freq;
}
After setOsc1Freq( freq ) you have to do jSlider.setValue( freq ).
The way I do this in my own projects is that I never use free-standing primitive values like float freq; instead, I have an observable class with a getter and a setter, which issues an event when the value changes, and then I wrap every single one of my controls in another class which knows how to interact with such an observable. So, every time the value of the control changes, the value in the observable changes too, but also, every time my program changes the value of the observable, the control also takes notice and updates itself too.
I would think that it is practically impossible to write any kind of gui without this functionality, but apparently I seem to be contradicted by the existence of a myriad of gui frameworks out there that do not support this and force you to re-invent.
(Posted on behalf of the OP).
I solved my problem by splitting components declaration, moving them to another singleton class, creating accessor methods and then in the gui class I assigned the variables to the getters.
My program is supposed to get information about a person (first and last names, address, phone) so that it can add the person into an address book.
I made a JLabel which gives instructions on what to enter right below. Below the JLabel is a JTextField which has an ActionListener listening to what is being entered. My method has about 8 ActionListener's with 8 actionPerformed methods. I am running into trouble it is not working. I can't figure out any other way.
Best to create a form, perhaps with GridBagLayout or MigLayout that holds displays JLabel/JTextField pairs, so that the user can enter all the data on a single simple form, much like most software you use.
If you absolutely must use a single JTextField, then you should use a single ActionListener, but change how it responds based on the state of the GUI. That is, perhaps use an int counter variable, that you increment each time data is entered, and base what the listener does with the data based on the value held by the counter.
You can create an instance of the listener and reuse it across the class, like:
...
OnChangeListener listener = new OnChangeListener() {
//All the code here
};
...
textField1.addOnChangeListener(listener);
textField2.addOnChangeListener(listener);
textField3.addOnChangeListener(listener);
...
For the longest time I have been invoking getActionCommand on ActionEvent objects to retrieve information from some JButtons, but as my programs grew more complex, I wanted to send several bits of information through setActionCommand, i.e. having a command like "r3" to indicate to the Action Listener that I wanted to remove the 3rd button from a panel within a JFrame. Eventually, I grew tired of parsing the strings and extracting the information that I wanted to use and instead started using getSource. (I want to know which one is better to use to retrieve information)
Also, I created a subclass of JButton called OperationButton that has two instance fields: an int ID and an Operation op (Operation is a custom enumerated type whose values are ADD, REMOVE, SWITCH, etc). I want to know if the following method is more efficient/a better practice than simply using getActionCommand, or if there is a third way of handling events that I have not thought of yet.
public void actionPerformed(ActionEvent e)
{
OperationButton opButton = (OperationButton) e.getSource();
int ID = opButton.getID();
Operation op = opButton.getOperation();
switch (op)
{
case ADD: //adds a custom panel to frame
break;
case REMOVE: //removes a button and a custom panel with the specified ID
break;
case SWITCH: //highlights a button with the specified ID and
//displays a custom panel with the specified ID
//...
}
}
(OperationButtons are the only buttons in my program)
Again, I want to retrieve information without having to set the action command of a JButton, but I'm not entirely sure if this is the right way to go. Also, would this method be feasible for future programs in which I might want to send more than 2 pieces of information?
I started to look into using GWT in combination with UiBuilder. I'm a bit puzzled about how you can use the #UiHandler(..) directive to make simple event handle code as written down in the GWT documentation:
#UiHandler("button")
void handleClick(ClickEvent e) {
Window.alert("Hello, AJAX");
}
In this case the method handleClick is used.
How do you know for each GWT widget what methods can be created with #UiHandler? For some you can also create a doClose() method.
But what can you use with, for instance, a ListBox to get an event an item is selected? Where in the documentation can I see this?
The parameter you pass to the #UiHandler annotation is the name of the appropriate field you want to assign that *Handler. So, in this case you are assigning a ClickHandler to a Button button (actually, we just know the field's name).
As for how this exactly works - it's part of GWT magic :) My guess is that, just like any other UiBinder related code (I think there was a presentation on Google IO, that showed the code that UiBinder generates), at compilation time the compiler figures out what goes where. In this example: we have a Button button, and we have a #UiHandler annotated method that has a ClickEvent parameter -> that must mean it's a ClickHandler (notice that the method's name doesn't matter). So let's add some code at compile time (in the constructor, probably) that adds that handler to the button. If you are interested in a more comprehensive answer - check out the source :D
But what can you use with, for
instance, a ListBox to get an event
an item is selected? Where in the
documentation can I see this?
In the GWT API reference. In this case, you are probably looking for ListBox.addChangeHandler. But you usually won't find #UiHandler related code there - that's because it would be redundant - you always construct the #UiHandler methods the same way:
You check the *Handler that you want to add, say ChangeHandler
It has a void onChange(ChangeEvent event) - so, your method needs a ChangeEvent parameter and should look like this:
#UiHandler("listBox")
void whateverName(ChangeEvent event) {
// ...
}
Probably your problem is in your onModuleLoad method:
public void onModuleLoad()
{
HelloWorld helloWorld = new HelloWorld("BOTAO");
// Using this way #UiHandler will not work
//Document.get().getBody().appendChild(helloWorld.getElement());
// correct way
RootPanel.get().add(helloWorld);
}