Each time the user presses a button a counter amountWrongGuessed gets incremented by 1. (works correctly with testing with System.prinln)
But how exactly do i get this to update in my label each time i press the button?
I have made a property that returns this value.
public int getAmountGuessed(){
return amountGuessed;
}
Next i try to get the value of the label, but the value always remains at 0.
lblAmountGuessDisplay = new JLabel(String.valueOf(hg.getAmountGuessed()));
private void UpdateComponents()
{
lblAmountGuessDisplay.setText(String.valueOf(hg.getAmountGuessed()));
}/*updateComponents*/
This example shows one way to update a label each time a button is clicked.
It might be a threading issue. Please take a look here.
I agree with Fredrick -- that you've not posted enough information for your question to be answerable and that it may be a reference issue -- that the JLabel you are changing is not the one that is displayed in the program. If you post more code, we'll have a better chance of giving your a decent answer. Also, this doesn't smell like a threading issue.
You need to add an ActionListener to your button. When the ActionListener is notified that the button is pressed, you can increment the counter and update the JLabel. The actionPerformed method will be triggered in the EDT, so you should be ok with threading.
lblAmountGuessDisplay.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent ae) {
hg.incrementAmountGuessed();
lblAmountGuessDisplay.setText(String.valueOf(hg.getAmountGuessed()));
}
}
You will probably need to implement the incrementAmountGuessed method (which may be the root of your problem in the first place).
Related
So, this is really annoying, and an incredible magic show at the same time. So I have a global string called setAnagram. I'm making a GUI with Eclipse, and so what I'm trying to do, is have the user click a button, it start another thread, and on that thread it gets the value of a text field. The way I did this was to set setAnagram to the value of the text field.
However, that didn't actually work, and setAnagram had a blank value (""). So then I thought okay well what if I set the variable to null. Well then I get a NullPointerException.
I thought well, what if the variable actually doesn't change, and it starts the thread before it can change the variable? Well I made it so you press the button once and it changes it, then you press it again, and then it starts the thread. Here's where the weird stuff comes in. I print out the value of setAnagram on the first button click after it has been changed. However, when I start the thread on the next button click, it's back to the what it was initialized as ("test"). Here's the code for the button click:
decodeAnagramButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (buttonPresses == 0) {
setAnagram = chosenAnagram.getText(); // chosenAnagram is the text field
buttonPresses++;
decodeAnagramButton.setText("Click again");
System.out.println(setAnagram); // These two lines output the same thing
System.out.println(chosenAnagram.getText());
}
else {
titleText.setText("Decoding anagram...");
decodeAnagramButton.setVisible(false);
MainWindow thread = new MainWindow();
thread.start();
}
}
});
And then to minimize, I won't add the thread code because it's kinda long, just know that all it does with setAnagram is get the value. Any ideas on why this is changing unexpectedly?
MainWindow thread = new MainWindow();
thread.start();
So... you create a new instance of MainWindow (which is apparently a thread?!?). That means that new instance of MainWindow also has its own setAnagram member variable, right?
Try adding thread.setAnagram = this.setAnagram; between these two lines of code.
(Also, something about your design smells fishy, why is your main window a thread?)
I've run into what seems (to me, anyway) an odd problem with JavaFX spinners and not being able to attach any kind of listener to it.
I'm used to Swing programming, where I can attach a ChangeListener to a JSpinner and receive events that way, but JavaFX doesn't seem to have anything like that.
The code in question...
IntegerSpinnerValueFactory spinnerValueFactory = new SpinnerValueFactory.IntegerSpinnerValueFactory(0, Integer.MAX_VALUE);
hullPointsSpinner = new Spinner<Integer>(spinnerValueFactory);
hullPointsSpinner.setEditable(true);
((TextField)hullPointsSpinner.getEditor()).setOnAction(new EventHandler<ActionEvent>() {
public void handle( ActionEvent event )
{
System.out.println("Howdy, folks! Value is " + hullPointsSpinner.getValue() + "!!");
}
});
The arrow buttons will increase and decrease the value in the field, but have no effect on the value in the model. Only selecting the contents of the field and pressing enter will actually update the data in the model and prints out the value. (The pressing enter thing is in the documentation, I know.)
I also realize that I'm putting that EventHandler onto the Spinner's TextField with getEditor, but I have yet to see another way to do this.
Is there a way to hook a listener to the spinner's buttons?
(Heck, is there even a way to get at those buttons to attach a listener?)
Am I receiving the wrong type event from the spinner/editor?
Can I put some kind of listener on the spinnerValueFactory?
Is there some kind of obvious solution that I'm overlooking here?
I'll replace this with a JSpinner, if necessary, but it just seems crazy to me that this API would have a spinner component and such an awkward way to use it.
Thanks in advance.
The following seems to work fine for me:
hullPointsSpinner.valueProperty().addListener((obs, oldValue, newValue) ->
System.out.println("New value: "+newValue));
Alternatively you can do
spinnerValueFactory.valueProperty().addListener(...);
with the same listener as above.
You should note this bug, which is fixed in 1.8.0u60.
I am doing an autonomous code while refreshing things on the gui. (the logic is completely random right now).
When I call the button.doClick() method. It runs like it should have, but inside I have the button.setBackground(Color.red) method.
The problem being it doesn't set the background until the end. Do I have to do things with multiple threads? Thank you
EDIT: CODE ADDED
private void jButtonAutoActionPerformed(java.awt.event.ActionEvent evt){
//pick one here, but lets say it is number one
JB00.doClick();
}
private void JB00ActionPerformed(java.awt.event.ActionEvent evt){
//sends out shot and gets response
if(response.equals("Hit"){
JB00.setBackground(Color.red);
}
else{
JB00.setBackgorund(Color.Blue)
}
}
Everything works when I just click the button from the gui, So I do not think it is an issue with anything in the JB00 method.
I have a strange issue with our application that only manifests itself in java7, everything worked flawlessy in java6.
I have a product-choosing JDialog that has a JTable, an ok button, a cancel button, a jtextfield for searching and a jcheckbox "keep window open".
The idea is, that if "keep window open" is selected, then a press to the ok button will not dispose the jdialog, but instead set a reopen-variable to true, and call setVisible(false).
Then I have the following code to reopen it:
while(SelectionDialog.isReopen()){
Product p1 = SelectionDialog.reopen();
if (p1 == null) return;
//Do stuff with product
}
In SelectionDialog:
public static SelectionDialog reopen = null; //Is instanciated to current jdialog if ok button is pressed and reopen-checkbox is selected. setvisible(false) is then called instead of dispose()
public static Product reopen() {
SelectionDialog.reopen.setVisible(true);
return SelectionDialog.returnedData;
}
The strange thing is, that when the JDialog is redisplayed, the jtextfield is not focusable/clickable. Everything else seems ok. If I then press the ok button and it reopens, the jtextfield is ok again, but if I press ok another time it is not focusable/clickable again.
The jtextfield displays text, but there is no blinking cursor when it does not work.So every other time the jtextfield simply doesn't work, and every other time it works.
All these methods return true for the jtextfield: isEnabled, isEditable, isDisplayable, isVisible, isFocusable, isOpaque, isShowing, isValid.
Calling updateUI on jtextfield in swingutilities.invokelater before setVisible(true) on jdialog does not solve the problem. Neither does requestfocusinwindow.
The only thing that seems to work to bring the jtextfield back from the dead is switching to another program, and then switching back to my java-program.
I have tested, and the problem persists in both jdk1.7.0_03 and 1.7.0_51.
I don't have this problem in java6 and before.
What can be causing the problem? (I have removed everything from "//Do stuff with product" in case this did something, but the problem persists).
And even if you don't know what causes the problem, does anyone have any suggestions to a workaround that may work?
UPDATE:
Thanx to MadProgrammers comments, it now works with the following code:
SwingUtilities.invokeLater(new ReopenProductList()); //Instead of while-loop
private class ReopenProductList implements Runnable{
public void run(){
if (SelectionDialog.isReopen()){
Product p1 = SelectionDialog.reopen();
if (p1 == null) return;
//Do stuff with product
SwingUtilities.invokeLater(new ReopenProductList());
}
}
}
Based on the description of the problem, it would appear that you are blocking the Event Dispatching Thread by using the while loop.
Having had a situation when testing Java 7 early on (it actually deadlocked on SwingUtiltiies.invokeLater). We never found the fault, as we re-wrote the entire action of code (the original was funky), it would suggest that the threading model,has changed between Java 6 & 7.
Try removing the while loop from the EDT
This may be a stupid question, but I have to ask!
I have the following code snippets that are supposed to run their corresponding methods when the user interacts with objects.
For some reason, "foo" is never printed, but "bar" is.
myJSpinner1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseEntered(java.awt.event.MouseEvent evt) {
System.out.println("foo"); //"foo" is not printed
}
});
myJSpinner2.addChangeListener(new java.awt.event.ChangeListener() {
public void stateChanged(java.awt.event.ChangeEvent evt) {
System.out.println("bar"); //"bar" is printed
}
});
I get no exceptions or stack trace. What am I missing in the MouseListener one?
Thanks in advance.
EDIT: MouseEntered works perfectly on a JCheckBox implemented in exactly the same way!
JSpinner is a composite component consisting of a text field and 2 buttons. It's possible to add mouse listeners to all of those by iterating over the results of getComponents() and adding a listener to each.
However, in my experience, when something takes that much work, you're probably going about it the wrong way.
Why do you need the mouse-entered information for a JSpinner?
What do you want to do with this event?
Update:
If you're looking to supply information about all of the controls in your panel, you may want to look at using a glasspane to detect the component under the mouse.
A Well-behaved Glasspane by Alexander Potochkin is a good place to start.
This is a guess but I suspect you need to add a MouseListener to the JSpinner's editor (via a call to getEditor()). I imagine that the editor Component occupies all available space within the JSpinner and is therefore intercepting all MouseEvents.
This worked for me.
JSpinner spinner = new JSpinner();
((JSpinner.DefaultEditor)spinner.getEditor()).getTextField().addMouseListener(
new java.awt.event.MouseAdapter() {
public void mouseClicked(final MouseEvent e) {
// add code here
}
});
I needed this in order to evoke a popup key dialog for added usability due to our software requirements.
Aditional to #Rapier answer...
If you change the Spinner using something like
yourOldSpinner = new JSpinner(new SpinnerModel(...))
you will lost your previosly MouseListener...
If you need to change something of SpinnerModel, Don't create a new, change its parameters instead! (if you do it, you will need to reassign the MouseListener again, because it will be lost when you assign a new SpinnerModel).
an example (I'm talking...):
((SpinnerNumberModel)yourOldSpinner.getModel()).setValue(size/3);
((SpinnerNumberModel)yourOldSpinner.getModel()).setMinimum(0);
((SpinnerNumberModel)yourOldSpinner.getModel()).setMaximum(isize/2);
((SpinnerNumberModel)yourOldSpinner.getModel()).setStepSize(1);