Identifying which button was pressed - java

I'm trying to build a GUI which has a lot of buttons(JButton)/dropdown items (JMenuItem) and when each button containing letters is pressed the associated letter is being added to a label.
I'm having trouble identifying which button was pressed.Can you please give me a tip on how to do this?
Code:
private void dodajCrko(java.awt.event.ActionEvent evt) {
jlStatus.setText(jlStatus.getText() + evt.getSource()/* what to add here?*/);
}

I would use the getActionCommand() method:
private void dodajCrko(java.awt.event.ActionEvent evt) {
jlStatus.setText(jlStatus.getText() + actionEvent.getActionCommand());
}

I think you need this
((Button)actionEvent.getSource()).getLabel()
This will give you the label of the button clicked. You need to type cast the Source to Button like (Button)actionEvent.getSource()
Your code should be
private void dodajCrko(java.awt.event.ActionEvent evt) {
jlStatus.setText(jlStatus.getText() +
((Button)actionEvent.getSource()).getLabel());
}
As #Anto said, You should use actionEvent.getActionCommand() if you use any toggle buttons because the command string would identify the intended action.

In my opinion i find this works better.
private JButton button1;
Then use this.
button1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Button 1 was presseed");
}
});
Hope this helps, Luke.

Related

Java GUI adding buttons with a for loop

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
}

Disabling Enabled Effect on JToggleButton

I've got an application that is using Swing for it's UI. I want a button that switch the type of communication that the app is using. I want to use a Toggle Button to identify the type of communication that's selected.
My problem is that I don't want the color of the button to change after it's been clicked. Currently the button looks like this...
Non-Selected
And then when clicked it looks like this...
Selected
The text changing is what I want, but I would prefer them to have the same color / style.
Here's my code for this...
JToggleButton tglbtnCommunicationType = new JToggleButton("AlwaysOn");
tglbtnCommunicationType.setFocusPainted(false);
tglbtnCommunicationType.addChangeListener(new ChangeListener( ) {
public void stateChanged(ChangeEvent tgl) {
System.out.println("ChangeEvent!");
if(tglbtnCommunicationType.isSelected()){
tglbtnCommunicationType.setText("REST");
tglbtnCommunicationType.setBackground(UIManager.getColor("Button.background"));
}
else
{
tglbtnCommunicationType.setText("AlwaysOn");
};
}
});
My thought is that setting the background when it is selected to the standard background color would fix that, but it doesn't look like it. Any ideas?
Thanks!
Answer:
I switched to a JButton instead, thanks for the help everyone!
JButton btnCommunicationType = new JButton("AlwaysOn");
btnCommunicationType.setFocusPainted(false);
btnCommunicationType.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(btnCommunicationType.getText().equals("AlwaysOn"))
{
btnCommunicationType.setText("REST");
//TODO: Insert Code for Switching Communication to REST here
}
else if(btnCommunicationType.getText().equals("REST")){
btnCommunicationType.setText("AlwaysOn");
//TODO: Insert Code for Switching Communication to AlwaysOne here
}
}
});
btnCommunicationType.setBounds(275, 199, 97, 25);
thingWorxConnectionPanel.add(btnCommunicationType);
you can do it by using JButton only instead of JToggleButton ,
JButton showButton = new JButton("AlwaysOn");
showButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String currentText = showButton.getText();
if("AlwaysOn".equals(currentText)){
showButton.setText("REST");
}else{
showButton.setText("AlwaysOn");
}
}
});

Many jbuttons with the same onkeypress function

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
}
}

Can I call ActionPerformed method from an Event Handler class for JButton?

I have a JButton titled "select"
In the class that creates that JButton and other classes, I want to use an if condition with ActionPerformed method.
Something like(pseudo-code)
if(_selectListener.actionPerformed(ActionEvent)) { //i.e., if select Button is clicked,
//do something
}
Is this possible?
I want to call this method because I have to handle a situation in which a player should be able to choose something by clicking "select" button, or another "scroll" button, and I want to control it using something similar to a bunch of if statements like the one above.
If it is possible, what is the syntax for it? What is the argument ActionEvent?
Thank you!
The easiest and cleanest way is to add a dedicated, specific action listener to each button. That way, when the actionPerformed() method is called, you're sure that the associated button has been clicked, and don't need to test which button has been clicked:
selectButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// handle click on select button
}
});
scrollButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// handle click on scroll button
}
});
Another way is to use a common ActionListener, and use the getSource() method of ActionEvent to know which component triggered the event. Compare the result with each potential button to determine which is the one that has been clicked:
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == selectButton) {
// handle click on select button
}
else if (e.getSource() == scrollButton) {
// handle click on scroll button
}
}
What is the argument ActionEvent?
The answer is in the documentation. Read it.
no you cant call, if needs boolean expression/value, but this method returns void.

Clicking the textfield and clear the text?

Is it possible that when I clicked the textfield it would clear the recent text that was inputed there?. Mine was like, suppose these are textfields.
Name: Last Name First Name Middle Initial
Then I would click the Last Name and it would be cleared, same as First Name and Middle Initial. thanks for reading, hope you can help me.
Consider a FocusListener, one where all the text is selected:
myTextField.addFocusListener(new FocusAdapter() {
public void focusGained(FocusEvent fEvt) {
JTextField tField = (JTextField)fEvt.getSource();
tField.selectAll();
}
});
By selecting all of the text, you give the user the option of either typing and thus deleting the current text and replacing it with the new text, or using the mouse or arrow keys to keep the current text and possibly change it.
I think Hovercraft is right. Better to use a FocusListener for this purpose.
I would write a utility class that could deal with this, I've done something similar for auto select. Means I don't have to extend every text component that comes along or mess around with lost of small focus listeners that do the same thing.
public class AutoClearOnFocusManager extends FocusAdapter {
private static final AutoClearOnFocusManager SHARED_INSTANCE = new AutoClearOnFocusManager();
private AutoClearOnFocusManager() {
}
public static AutoClearOnFocusManager getInstance() {
return SHARED_INSTANCE;
}
#Override
public void focusGained(FocusEvent e) {
Component component = e.getComponent();
if (component instanceof JTextComponent) {
((JTextComponent)component).setText(null);
}
}
public static void install(JTextComponent comp) {
comp.addFocusListener(getInstance());
}
public static void uninstall(JTextComponent comp) {
comp.removeFocusListener(getInstance());
}
}
Then you just need to use
JTextField textField = new JTextField("Some text");
AutoClearOnFocusManager.install(textField);
If you're just looking to supply a "prompt" (text inside the field that prompts the user), you could also look at the Prompt API
Why don't use the mouseClicked event?
So, you can have something like
jTextFieldMyText.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTextFieldMyTextMouseClicked(evt);
}
});
private void jTextFieldMyTextMouseClicked(java.awt.event.MouseEvent evt) {
jTextFieldMyText.setText("");
}
In the case of focus
jTextFieldMyText.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jTextFieldMyTextFocusGained(evt);
}
});
private void jTextFieldMyTextFocusGained(java.awt.event.MouseEvent evt) {
jTextFieldMyText.setText("");
}
If deleting text inmediatelly isn't what's wanted, use selectAll() instead of setText("") as suggested many times

Categories

Resources