Hi i am making a lotto gui where the user picks 4 numbers from a selection of 28. The way i am currently doing it is as follows
private void no1InputButtonActionPerformed(java.awt.event.ActionEvent evt) {
numberSelectionList.add("1");
}
private void no2InputButtonActionPerformed(java.awt.event.ActionEvent evt) {
chosenNumDisplayLabel.setText(chosenNumDisplayLabel.getText()+" 2");
}
private void no3InputButtonActionPerformed(java.awt.event.ActionEvent evt) {
chosenNumDisplayLabel.setText(chosenNumDisplayLabel.getText()+" 3");
}
etc up through the 28 numbers.
Is there a way to add the actions to each button through a for loop
as this seems more logical?
Also is there a way to add each number picked into an array?
Create a single Action that can be shared by all buttons. The Action will then simply get the text of the button and then do some processing.
Check out setText method with panel and button. This example will show you how to:
create a single ActionListener to be shared by each button
"append" the text to the text field instead of replacing the text
use Key Bindings so the user can also just type the number
On each button you can set an action command:
button.setActionCommand("1");
And you can get the value after that using your ActionEvent:
evt.getActionEvent();
More complete:
ActionListener listener = new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
System.out.println(e.getActionCommand()+" clicked");
}
};
int howMuchYouWant = 32;
for(int i = 0; i<howMuchYouWant; i++)
{
JButton button = new JButton(""+(i+1));
button.setActionCommand(""+i);
button.addActionListener(listener);
//add to whatever gui you want here
}
Related
I have added an action listener to the text field. When the btnReadString (Button Read String) is pressed the program should read what is on the text field and show on the JPanel. but nothing shows on the panel.
stringTextField.addActionListener(new ActionListener() {
public void stringTextField (java.awt.event.ActionEvent e) {
if(e.getSource()==btnReadString) //when the button is pressed
{
String stringParameter = stringTextField.getText(); //gets the text and puts it on this string called "stringParameter"
textPane.setText(stringParameter);//the JPanel is set to what is on the string.
}
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
});
The functionality for the ActionListener should go in the actionPerformed method, as nothings calling the stringTextField method...
stringTextField.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==btnReadString) //when the button is pressed
{
String stringParameter = stringTextField.getText(); //gets the text and puts it on this string called "stringParameter"
textPane.setText(stringParameter);//the JPanel is set to what is on the string.
}
}
});
But, based on the code, the ActionListener should be attached to the btnReadString and not the field, as the above logic will never result in anything been executed (as the source of the event will never be btnReadString)
btnReadString.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String stringParameter = stringTextField.getText(); //gets the text and puts it on this string called "stringParameter"
textPane.setText(stringParameter);//the JPanel is set to what is on the string.
}
});
I would suggest having a closer look at How to Write an Action Listener and How to Use Buttons, Check Boxes, and Radio Buttons for more details
You have added the ActionListener to the text field. So the event source is never going to be the button and hence, the code is never going to execute. What you want is to add the ActionListener to the JButton.
Also, the actionPerformed() is there for a reason. All your 'action' code goes inside this method.
So your code should look like this:
btnReadString.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String stringParameter = stringTextField.getText();
textPane.setText(stringParameter);
}
});
I am creating a quiz for school. There are several buttons for the questions which, when pressed, display the new question and create 4 different ActionListeners for the buttons of the 4 answers.
Now I need to remove the 4 ActionListeners after one button was pressed.
I am able to remove the ActionListener from the button itself, but I want to remove the other 3 ActionListeners as well.
Every new ActionListener looks like this:
btAnswer1.addActionListener(new java.awt.event.ActionListener()
{
#Override
public void actionPerformed(java.awt.event.ActionEvent evt)
{
lResult.setForeground(Color.red);
lResult.setText("Wrong Answer :(");
// The team is changed.
if (aktTeam == 1)
{
aktTeam = 2;
lAktTeam.setText("Team 2");
}
else
{
aktTeam = 1;
lAktTeam.setText("Team 1");
}
// Here, this ActionListener is removed. But the others should
// be removed too.
btAntwort1.removeActionListener(this);
}
});
I hope somebody can help. :)
Edit: Solved by davidxxx. Thanks!
1) In your example you don't remove the ActionListener from the same btn on the which one you have added the listener:
You add it to btAnswer1:
btAnswer1.addActionListener(new java.awt.event.ActionListener()...
But you remove it from btAntwort1:
btAntwort1.removeActionListener(this);
So, it should not work.
Now I need to remove the 4 ActionListeners after one button was
pressed.
2) If removing all the ActionListeners associated to the Button is valid in our use case, you can do :
for( ActionListener listener : btAntwort1.getActionListeners() ) {
btAntwort1.removeActionListener(listener);
}
Otherwise if you don't want to remove all the ActionListeners associated to the button, you should not inline the anonymous ActionListener instances in order to keep a reference on them when you want to remove them from the button.
For example do that :
ActionListener actionListenerOne = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
...
}
};
ActionListener actionListenerTwo = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
...
}
};
Now you have for example two references on the ActionListener instances you may add to the button.
So you may do :
JButton button = ...;
button.addActionListener(actionListenerOne);
button.addActionListener(actionListenerTwo);
and later :
button.removeActionListener(actionListenerOne);
button.removeActionListener(actionListenerTwo);
I have many jbuttons (around 50+) which can be clicked.
After clicking one the program will check for key inputs and set the button text as the pressed key.
Instead of copy pasting 50 codeblocks to each onkeypressed and onclick event of one button i wanted to use a function in each event.
My code so far (reduced):
private JButton attackMoveBtn = new JButton();
private boolean isAlreadyClicked = false;
private void attackMoveBtnKeyPressed(java.awt.event.KeyEvent evt) {
if(attackMoveBtn.getText().equals(Strings.setHotkey)){
isAlreadyClicked = false;
attackMoveBtn.setText(String.valueOf(evt.getKeyChar()));
}
}
private void attackMoveBtnMouseClicked(java.awt.event.MouseEvent evt) {
if(evt.getButton() == 3){
isAlreadyClicked = false;
attackMoveBtn.setText("");
}else{
if(!isAlreadyClicked){
isAlreadyClicked = true;
attackMoveBtn.setText(Strings.setHotkey);
}else{
isAlreadyClicked = false;
attackMoveBtn.setText("Mouse "+evt.getButton());
}
}
}
The only thing that would change for the next button is the JButton itself (attackMoveBtn would become moveBtn for example)
I tried to use String compName = evt.getComponent().getName(); to retrieve the name of the button i pressed but i cannot use "attackMoveBtn".setText() because dynamic var names are not really supported by java.
Is there a way to get which button was pressed? I could then call a function with the buttonObject as a parameter like myOnKeyPressFunction(JButton myButton)
My question would be how i can do dynamic variable names or if my approach is wrong and i should use a different pattern.
"Is there a way to get which button was pressed? I could then call a function with the buttonObject as a parameter like myOnKeyPressFunction(JButton myButton)"
Just use getSource of the event which returns Object and cast JButton to it
JButton button = (JButton)evt.getSource();
myOnKeyPressFunction(button);
Fyi, buttons are to be used with ActionListener to. If you are using the GUI Editor tool, when right click on the button from the design view, select, event->action->actionPerformed and an ActionListener will be added for you.
"i am using netbeans graphic editor to build my gui (i suck at gui programming tbh)"
I strongly suggest you ditch the builder tool and go through some tutorial and learn to hand code first. Go through Creating GUIs with Swing.
If its just JButtons using the ActionListener
public void actionPerformed(ActionEvent e){
JButton temp = (JButton)e.getSource();
//do whatever with temp
}
If you share the ActionListener with other objects
public void actionPerformed(ActionEvent e){
if(e.getSource() instanceof JButton){
JButton temp = (JButton)e.getSource();
//do whatever with temp
}
}
I have:
for (int i = 0; i <= 9; i++) {
JButton c = new JButton();
c.setText(Integer.toString(i));
ActionListener l = new NumericButtonListener(i);
c.addActionListener(l);
buttonGrid.add(c); }
So basically, some code that creates a grid of numbers. How can I map my pane to allow hitting the appropriate number and trigger my NumericButtonListener?
You can use keyBindings and assign one common Action for the specific key.
Make use of button's doClick() function to generate an Action event and listens to it. You will need to invoke this function on the specific button to which mapped key is pressed. For example:
Action generateClick = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
JButton butt = (JButton) e.getSource();
butt.doClick();
}
};
Use keyBinding for each button. See tutorial for KeyBindings
For example add next code in creation:
c.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(Integer.toString(i)), "doSomething");
c.getActionMap ().put("doSomething", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent arg0) {
System.out.println(c.getText());
}
});
How can I display a series of images one by one every time the user clicks the next button?
I have few images stored in array. I used button next to go from image to image. How to programme the button? I used action listener but I just don't know how to get back to the array.
I know I'm being lazy here by not writing the entire code, but here goes anyway.
class whatEver implements ActionListener{
JButton btnNext = new JButton();
static int fileNumber = 0;
static int totalFiles;
void functionLoadInterface () //Function with
{
btnNext.addActionListener(this);
//Initialize array ImageArray with file paths.
}
public void cycleImage()
{
String file = ImageArray[fileNumber%totalFiles];
//Code to load the image wherever follows
}
public void actionPerformed(ActionEvent e)
{
filenumber++;
this.cycleImage();
}