Java - JButton text disappears if actionPerformed defined afterwards - java

This has been bugging me for a while. If I define setText on a JButton before defining setAction, the text disappears:
JButton test = new JButton();
test.setText("test"); // Before - disappears!
test.setAction(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
// do something
}
});
this.add(test);
If it's after, no problems.
JButton test = new JButton();
test.setAction(new AbstractAction() {
public void actionPerformed(ActionEvent e) {
// do something
}
});
test.setText("test"); // After - no problem!
this.add(test);
Furthermore, if I set the text in the JButton constructor, it's fine! Yarghh!
Why does this happen?

As described in the documentation:
Setting the Action results in immediately changing all the properties
described in Swing Components Supporting Action.
Those properties are described here, and include text.

Have a look at
private void setTextFromAction(Action a, boolean propertyChange)
in AbstractButton. You can see it's calling setText() based on the action.
It looks like you can call setHideActionText(true); to sort out your problem.

This is because Action has name for the control as well. Since you are not setting any name in the Action it is getting set to empty string.

1) Listeners put all Events to the EDT,
2) all events are waiting in EDT and output to the screen would be done in one moment
3) you have to split that to the two separate Action inside Listener
setText()
invoke javax.swing.Timer with Action that provide rest of events inside your original ActionListener

If you only want to handle the event, you don't need Action. You can add an ActionListener:
JButton test = new JButton();
test.setText("test");
test.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// do something
}
});
this.add(test);
Calling setAction overrides pre-set text.

Related

How to get a GUI button click to trigger an if statement [duplicate]

private JButton jBtnDrawCircle = new JButton("Circle");
private JButton jBtnDrawSquare = new JButton("Square");
private JButton jBtnDrawTriangle = new JButton("Triangle");
private JButton jBtnSelection = new JButton("Selection");
How do I add action listeners to these buttons, so that from a main method I can call actionperformed on them, so when they are clicked I can call them in my program?
Two ways:
1. Implement ActionListener in your class, then use jBtnSelection.addActionListener(this); Later, you'll have to define a menthod, public void actionPerformed(ActionEvent e). However, doing this for multiple buttons can be confusing, because the actionPerformed method will have to check the source of each event (e.getSource()) to see which button it came from.
2. Use anonymous inner classes:
jBtnSelection.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectionButtonPressed();
}
} );
Later, you'll have to define selectionButtonPressed().
This works better when you have multiple buttons, because your calls to individual methods for handling the actions are right next to the definition of the button.
2, Updated. Since Java 8 introduced lambda expressions, you can say essentially the same thing as #2 but use fewer characters:
jBtnSelection.addActionListener(e -> selectionButtonPressed());
In this case, e is the ActionEvent. This works because the ActionListener interface has only one method, actionPerformed(ActionEvent e).
The second method also allows you to call the selectionButtonPressed method directly. In this case, you could call selectionButtonPressed() if some other action happens, too - like, when a timer goes off or something (but in this case, your method would be named something different, maybe selectionChanged()).
Your best bet is to review the Java Swing tutorials, specifically the tutorial on Buttons.
The short code snippet is:
jBtnDrawCircle.addActionListener( /*class that implements ActionListener*/ );
I don't know if this works but I made the variable names
public abstract class beep implements ActionListener {
public static void main(String[] args) {
JFrame f = new JFrame("beeper");
JButton button = new JButton("Beep me");
f.setVisible(true);
f.setSize(300, 200);
f.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Insert code here
}
});
}
}
To add an action listener, you just call addActionListener from Abstract Button.

How to create a general action that changes tabs in GUI?

I have several actionListeners throughout my code for when I push a button, it changes tabs between the ones I have.
However, I would like to create a general action that depending on which button was pressed (through an int), it changed to a different tab. This is the current actionListener I have.
JButton btnSaveAddESS = new JButton("Save");
btnSaveAddESS.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tabbedBackground.setSelectedIndex(0);
tabbedBackground.setEnabledAt(1, false);
}
});
With this, I would like to create a general action, however , while creating the action as a different class, I am not able to access the TabbedPane (tabbedBackground) component.
How can I implement this, avoiding actionListeners?
Thanks,
Nhekas
changeTab(int i){
tabbedBackground.setSelectedIndex(i);
tabbedBackground.setEnabledAt(i, false);
}
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(Jbutton.getText());
changeTab(int i);
}
what you need is actually a method which handles the operation pass an int to the method changetab and the method will change the selectedTab

Java: Can I import an action listener that disables a swing component?

I have a JButton on an extension of a JForm called MyForm. The button executes quite lengthy code. Amongst this code is 'MyForm.this.setEnabled(false)' to disable the form whilst the button method executes. (And subsequently, 'MyForm.this.setEnabled(true)'.)
(I do this because it is the only solution I have found for ensuring that any mouse-clicks during the button's execution are ignored. Otherwise, I've found they queue up and execute immediately afterwards).
Can I export this button's code to some other file, for importing into a variety of other forms?
EDIT: Code:
JButton myButton = new JButton("Button Text");
myButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
MyForm.this.setEnabled(false);
...
MyForm.this.setEnabled(true);
}
});
Pass the form to disable as argument to the constructor of your listener:
public class FormDisablingActionListener implements ActionListener {
private final Form formToDisable;
public FormDisablingActionListener(Form formToDisable) {
this.formToDisable = formToDisable;
}
#Override
public void actionPerformed(ActionEvent e){
this.formToDisable.setEnabled(false);
...
this.formToDisable.setEnabled(true);
}
}
BTW, that's what the compiler generates for you when using an anonymoous class referencing its outer class instance like you're doing.
Then use it the following way:
JButton myButton = new JButton("Button Text");
myButton.addActionListener(new FormDisablingActionListener(this));

JButton background image

Hi i am trying to implement Action listener for JButton and code look like following:
ImageIcon imageForOne = new ImageIcon(getClass().getResource("resources//one.png"));
one = new JButton("",imageForOne);
one.setPreferredSize( new Dimension(78, 76));
one.addActionListener(myButtonHandler);
Using the above JButton it looks fine
When i add specific value to button for e.g.
ImageIcon imageForOne = new ImageIcon(getClass().getResource("resources//one.png"));
//Check this
one = new JButton("one",imageForOne);
one.setPreferredSize( new Dimension(78, 76));
one.addActionListener(myButtonHandler);
It look like the following image
Is there any way i can avoid this and set the value too.
Thanks for your help in advance.
Personally, I would be using the Action API.
It will allow you defined a hierarchy of action commands (if that's what you want) as well as define self contained response to the commands.
You could...
public class OneAction extends AbstractAction {
public OneAction() {
ImageIcon imageForOne = new ImageIcon(getClass().getResource("resources//one.png"));
putValue(LARGE_ICON_KEY, imageForOne);
}
public void actionPerfomed(ActionEvent evt) {
// Action for button 1
}
}
Then you would simply use with your button...
one = new JButton(new OneAction());
one.setPreferredSize( new Dimension(78, 76));
For example...
Instead of determining the button clicked in the action listener, I would use an adapter pattern:
one.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
handleClick("one");
}
});
where handleClick can still be the handler for all your buttons.
i want to get that value and use it on action listener.
You use the action command for this:
one.setActionCommand("1");
However it is better to use the actual text that you want to insert into your display component. Then you can share the ActionListener on all you buttons by using code like:
ActionListener clicked = new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e) {
String text = e.getActionCommand()
// displayComponent.appendText(text);
}
};
one.addActionListener(clicked);
two.addActionListener(clicked);

How do you add an ActionListener onto a JButton in Java

private JButton jBtnDrawCircle = new JButton("Circle");
private JButton jBtnDrawSquare = new JButton("Square");
private JButton jBtnDrawTriangle = new JButton("Triangle");
private JButton jBtnSelection = new JButton("Selection");
How do I add action listeners to these buttons, so that from a main method I can call actionperformed on them, so when they are clicked I can call them in my program?
Two ways:
1. Implement ActionListener in your class, then use jBtnSelection.addActionListener(this); Later, you'll have to define a menthod, public void actionPerformed(ActionEvent e). However, doing this for multiple buttons can be confusing, because the actionPerformed method will have to check the source of each event (e.getSource()) to see which button it came from.
2. Use anonymous inner classes:
jBtnSelection.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectionButtonPressed();
}
} );
Later, you'll have to define selectionButtonPressed().
This works better when you have multiple buttons, because your calls to individual methods for handling the actions are right next to the definition of the button.
2, Updated. Since Java 8 introduced lambda expressions, you can say essentially the same thing as #2 but use fewer characters:
jBtnSelection.addActionListener(e -> selectionButtonPressed());
In this case, e is the ActionEvent. This works because the ActionListener interface has only one method, actionPerformed(ActionEvent e).
The second method also allows you to call the selectionButtonPressed method directly. In this case, you could call selectionButtonPressed() if some other action happens, too - like, when a timer goes off or something (but in this case, your method would be named something different, maybe selectionChanged()).
Your best bet is to review the Java Swing tutorials, specifically the tutorial on Buttons.
The short code snippet is:
jBtnDrawCircle.addActionListener( /*class that implements ActionListener*/ );
I don't know if this works but I made the variable names
public abstract class beep implements ActionListener {
public static void main(String[] args) {
JFrame f = new JFrame("beeper");
JButton button = new JButton("Beep me");
f.setVisible(true);
f.setSize(300, 200);
f.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Insert code here
}
});
}
}
To add an action listener, you just call addActionListener from Abstract Button.

Categories