I have looked on the internet and can not find any help with understanding action listeners. I am just starting to learn Java and I have yet to find a good tutorial that helps me understand how to use action listeners. Could someone look over my code or point me in the way of a useful tutorial explaining how to use action listeners?
public static void go implements ActionListener(){
JFrame j = new JFrame();
j.setDefaultCloseOperation(EXIT_ON_CLOSE);
j.setSize(640,480);
final Screen screen = new Screen();
j.add(BorderLayout.CENTER, screen);
JButton button = new JButton("Click Me!");
button.addActionListener(new ActionListener(){
public void ActionPerformed(Event e){
screen.repaint();
}
});
j.add(BorderLayout.NORTH, button);
j.setVisible(true);
}
Other way and much better way is to use Anonymous class. You don't need to implement ActionListener
public static void go(){ // no need to implement actionListener
JFrame j = new JFrame();
j.setDefaultCloseOperation(EXIT_ON_CLOSE);
j.setSize(640,480);
final Screen screen = new Screen();
j.add(BorderLayout.CENTER, screen);
JButton button = new JButton("Click Me!");
button.addActionListener(new ActionListener(){ // change are made here
#Override
public void actionPerformed(ActionEvent e) { //& here
screen.repaint();
}
});
j.add(BorderLayout.NORTH, button);
j.setVisible(true);
}
actionPerformed is a method of interface, its not a class.
So use actionPerformed insted of ActionPerformed and use annotation #Ovveride for ovveriding the actionPerformed to provide your own defination.
#Override
public void actionPerformed(ActionEvent e) {
screen.repaint();
}
Related
my first post here. I'm currently in school and usually spend my time here on Stackoverflow looking for answers to homework, this time i'd thought that perhaps i'll put my code here and maybe i'll get help more precis and quicker! Anyways, my problem is that i've written a code which you can see below, and I'm new to swing, studied it for a few hours only. My problem is that I'm not quite sure how to proceed with my problem, I have 2 buttons, what i want is when you click on first button the panel will change to Red, second button the panel changes to blue, so far only Red works and I don't know how to implement it so that blue works aswell.
Would greatly appreciate your help! (Don't be shy about pointing out a few errors or help along the way that doesn't have with the buttons to do, as I said, I'm new :P)
public class FirstProgram extends JFrame {
public FirstProgram() {
initUI();
}
private void initUI() {
JPanel panel = new JPanel();
panel.setBackground(Color.yellow);
getContentPane().add(panel);
panel.setLayout(null);
JButton Colorbutton = new JButton("Red");
Colorbutton.setBounds(50, 60, 80, 30);
Colorbutton.setToolTipText("Panel changes to red");
Colorbutton.setBackground(Color.green);
JButton Colorrbutton = new JButton("Blue");
Colorrbutton.setBounds(1, 30, 90, 30);
Colorrbutton.setToolTipText("Panel changes to blue");
Colorrbutton.setBackground(Color.orange);
Colorbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
panel.setBackground(Color.red);
}
});
panel.add(Colorbutton);
panel.add(Colorrbutton);
setTitle("Time to change colors");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
FirstProgram ex = new FirstProgram();
ex.setVisible(true);
}
});
}
}
you need another ActionListener. right now you just have one and it has just one behavior. create another one and tie to the 'Blue" button
JButton RedColorbutton = new JButton("Red");
RedColorbutton .setBounds(50, 60, 80, 30);
RedColorbutton.setToolTipText("Panel changes to red");
RedColorbutton.setBackground(Color.green);
JButton BlueColorbutton = new JButton("Blue");
BlueColorrbutton.setBounds(1,30,90,30);
BlueColorrbutton.setToolTipText("Panel changes to blue");
BlueColorrbutton.setBackground(Color.orange);
RedColorbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
panel.setBackground(Color.red);
}
});
BlueColorbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
panel.setBackground(Color.blue);
}
});
You've set an action listener for your Colorbutton, but not for Colorrbutton
Add this next to your other ActionListener
Colorrbutton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
panel.setBackground(Color.blue);
}
});
You are missing an ActionListener for the blue JButtton.
Similar to how you added the ActionListener to your ColorButton, your ColorrButton needs to have one registered. By the way, you may wish to change the ColorButton to redButton and the ColorrButton to blueButton or something like that to make things stick out better.
example:
Colorrbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
panel.setBackground(Color.blue);
}
});
For the sake of reducing duplicate code, you can simplify the logic even further by having your class implement ActionListener.
public class FirstProgram extends JFrame implements ActionListener {
Then, when you are instantiating your buttons, add a listener like so:
redButton.addActionListener(this);
blueButton.addActionListener(this);
And then in your implementation of actionPerformed you could do something like:
public void actionPerformed(ActionEvent e) {
switch (e.getSource()) {
case redButton:
panel.setBackground(Color.red);
break;
case blueButton:
panel.setBackground(Color.blue);
break;
}
}
Anytime the red or blue buttons performs an action, the actionPerformed will be triggered, and then the logic to determine which button was the source will take over from there. This will add a little bit of length to your code, but as(if?) your program grows, it will reduce complexity greatly
I have my JButton set up and everything but it does absolutely nothing. Could someone tell me how to add a command such as system.out.println or some Scanner commands to a JButton?
Here is my line of code. It is very simple and I'm just testing JButton to add it to some of my other programs
import javax.swing.*;
public class Swing extends JFrame {
JButton load = new JButton("Load");
JButton save = new JButton("Save");
JButton unsubscribe = new JButton("Unsubscribe");
public ButtonFrame() {
super ("ButtonFrame");
setSize(140, 170);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane = new JPanel();
pane.add(load);
pane.add(save);
pane.add(unsubscribe);
add(pane);
setVisible(true);
}
public static void main(String[] arguments) {
ButtonFrame bf = new ButtonFrame();
}
}
See How to Write an Action Listener.
I suggest you read the entire tutorial (or keep a link to it for reference) as it contains all the Swing basics.
Hope this helps
load.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Here goes the action (method) you want to execute when clicked
System.out.println("You clicked the button load");
}
});
//The same for save button
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Here goes the action (method) you want to execute when clicked
System.out.println("You clicked the button save");
}
});
Ok. I'm not sure about the title of my question and whether I used the right words.
As I am a self taught total amateur I'm finding it hard to ask my question as I don't know the correct terms for things so I will write something in code and then ask my question. I've written it without import statements, setting up layouts and scrollbars and some other things just to keep it simpler.
public class Foo{
JTextArea text;
public static void main(String[] args){
Foo foo = new Foo;
foo.go();
}
public void go(){
JFrame frame = new JFrame();
JButton button = new JButton("One");
JButton button2 = new JButton("Two");
JPanel panel = new JPanel();
frame.setVisible(true);
frame.setSize(600, 300);
frame.getContentPane().add(BorderLayout.EAST, panel);
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(button);
panel.add(button2);
text = new JTextArea(10, 20);
panel.add(text);
button.addActionListener(new ButtLis());
button2.addActionListener(new ButtLis());
}
class ButtLis implements ActionListener{
#override
// this is where I have the problem
text.append();
}
}
What I want is an if statement to go into my inner class (ButtLis) which will determine which of the buttons are pressed and then append certain text to the JTextArea based on that. But I don't know what to call to find out which button was pressed.
You have a couple options. In the current case you have, where the JButton objects are locally scoped within the constructor, you would need to check for actionCommmand because the objects are not accessible from the ActionListener with their current scope. So you could do this
class ButtLis implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if ("One".equals(command)) {
// do something
}
}
}
If you wanted to compare object source, you would need to give your buttons a global scope
public class Foo {
JButton button = new JButton("One");
JButton button2 = new JButton("Two");
class ButtLis implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
}
}
}
}
A third option is to register the buttons individually
public void go() {
...
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
// do something
}
});
}
See more at How to use Common Button and How to Write ActionListeners
I think this is what you're looking for, although I would hardly recommend it:
class ButtLis implements ActionListener {
private JTextArea text;
public ButtLis(JTextArea text) {
this.text = text;
}
#Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton)e.getSource(); // Warning! This is not good coding practice, because you don't know that the source will be a button
text.append(button.getText());
}
}
Instead, I'd recommend:
JButton button1 = new JButton("One");
button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
text.append("one");
}
});
That uses an "anonymous inner class" to define the action listener. For Button2, you'd say a similar thing. The benefits here are that the action listener is right next to the button that it works on, and it prevents you from having a single ActionListener that has to check where each event came from (using e.getSource()).
Inside your ButtLis, add this
class ButtLis implements ActionListener {
public void actionPerformed(ActionEvent e) {
e.getSource();
//Your implementation
}
}
Here the class that implements ActionListener:
class ButtLis implements ActionListener {
JTextArea text;
public ButtLis(JTextArea text) {
this.text = text;
}
#Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() instanceof JButton) {
JButton button = (JButton) ae.getSource();
if(text != null){
text.append(" " + button.getText());
}
}
}
}
And here how to add an action listener to the buttons:
button.addActionListener(new ButtLis(text));
button2.addActionListener(new ButtLis(text));
For a generale ActionListsner, i suggest a different customer ActionListener like this:
abstract class ButtLis implements ActionListener {
protected String sourceEvent; //or you can use a reference for the source object
public ButtLis(String sourceEvent) {
this.sourceEvent = sourceEvent;
}
public String getSourceEvent() {
return sourceEvent;
}
#Override
public void actionPerformed(ActionEvent ae) {
customer_actionPerformed(ae);
}
public abstract void customer_actionPerformed(ActionEvent ae);
}
And the adding of action listener for any component is the same as an ordinary ActionListener:
//for exemple button
button.addActionListener(new ButtLis(button.getText()) {
#Override
public void customer_actionPerformed(ActionEvent ae) {
text.append(getSourceEvent());
}
});
I am a new comer to java and currently teaching myself via the HeadFirst java book.
I was going through GUI interfaces and the code from the book does not seem to run,
import javax.swing.*;
import java.awt.event.*;
public class SimpleGui1 implements ActionListener {
JButton Button;
public static void main(String[] args) {
SimpleGui1 gui = new SimpleGui1();
gui.go();
}
public void go(){
JFrame frame = new JFrame();
JButton button = new JButton("click me");
button.addActionListener(this);
frame.getContentPane().add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
}
public void actionPerformed (ActionEvent event) {
Button.setText("I have been clicked");
}
}
The exception :
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Can someone tell me what's wrong?
The class member variable Button is never initialized. Rather another with a different name (Java is case sensitive) is defined locally in the go method.
In the ActionListener you can simply use the ActionEvent source to determine the source of the Action:
public void actionPerformed(ActionEvent event) {
JButton button = (JButton) event.getSource();
button.setText("I have been clicked");
}
This removes the need to have the JButton as a class member variable.
Initialize button, it's still null.
You're having a NullPointerException.
How can I call a method by pressing a JButton?
For example:
when JButton is pressed
hillClimb() is called;
I know how to display messages etc when pressing a JButton, but want to know if it is possible to do this?
Many thanks.
If you know how to display messages when pressing a button, then you already know how to call a method as opening a new window is a call to a method.
With more details, you can implement an ActionListener and then use the addActionListener method on your JButton. Here is a pretty basic tutorial on how to write an ActionListener.
You can use an anonymous class too:
yourButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
hillClimb();
}
});
Here is trivial app showing how to declare and link button and ActionListener. Hope it will make things more clear for you.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class ButtonSample extends JFrame implements ActionListener {
public ButtonSample() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(100, 100);
setLocation(100, 100);
JButton button1 = new JButton("button1");
button1.addActionListener(this);
add(button1);
setVisible(true);
}
public static void main(String[] args) {
new ButtonSample();
}
#Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if (command.equals("button1")) {
myMethod();
}
}
public void myMethod() {
JOptionPane.showMessageDialog(this, "Hello, World!!!!!");
}
}
Fist you initialize the button, then add ActionListener to it
JButton btn1=new JButton();
btn1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
hillClimb();
}
});
You need to add an event handler (ActionListener in Java) to the JButton.
This article explains how to do this.
btnMyButton.addActionListener(e->{
JOptionPane.showMessageDialog(null,"Hi Manuel ");
});
with lambda