Java actionlistener doesn't work - java

I just started learning Java 1 week ago, and I'm a 100% totally beginner. In this code, I can't seem to be able to put an actionlistener/get one to work. I don't even know where/how/in what way to put it, despite reading dozens of tutorials. I've created a JFrame with a JPanel in it, and on the JPanel there's a button. So far so good (and working). But then, I want it to be so that if the button is clicked, another button appears. Thank you sooo much in advance!
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class Skeleton extends JFrame implements ActionListener {
public static void main(String[] args) {
//------------------------------------------------
JFrame frame = new JFrame("Skeleton");
JPanel panel = new JPanel();
frame.setContentPane(panel);
frame.setSize(600,600);
frame.setResizable(false);
frame.setVisible(true);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
JButton button = new JButton("This is a button.");
JButton button2 = new JButton("Hello");
panel.setLayout(null);
button.setBounds(20,20,200,25);
button2.setBounds(20,70,200,25);
panel.add(button);
//-------------------------------------------
button.addMouseListener(this);
}
public void ActionPerformed(ActionEvent e) {
System.out.println("Hello");
}
}

i will give you some advice
1) Don't implement ActionListener in top classes, use anonymous classes or private classes instead.
Example :
Anonymous class (also call Swing Actions)
myComponent.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt){
//code here
}
})
or
//inner class
public class Skeleton{
// in some part
private class MyActionListener implements ActionListener{
public void actionPerformed(ActionEvent evt){
//code here
}
}
}
2) Your code won't compile cause you are not implementing ActionListener interface
public void actionPerformed(ActionEvent evt) is the signature.
You have to addActionListener to your component
button.addActionListener(this);
3) Don't use null layout, cause you'll have a lot of problem if you want to add more components or resize windows cause you have to setBounds manually and it will be frustrating instead use [Layout Manager][1].
4) Try to not extends JFrame if is not necesary instead have a reference in your class, for example.
public class Skeleton{
private JFrame frame;
}

You need to add the actionlistener.
Register an instance of the event handler class as a listener on one or more components. For example:
yourdesiredcomponent.addActionListener(this);
For more details check the doc

Related

JButton ActionListener not responding

I couldn't find the answer anywhere else online, so I came here. I apologize in advance if the mistake in my code is very obvious; I'm still quite new to java swing. Here's what's going on: I have created a JButton named toggleElevators, and I want it to change text when clicked. I have already created an ActionListener and added it to toggleElevators. All I want right now is for the JButton to change text when clicked from Click me to Clicked.
First, here's a picture of what the JFrame looks like when executed:
NOTE: There is a third class, but it is purely for drawing the picture on the left. It has nothing to do with the GridLayout or the JButton.
Run class (created frame and adds toggleElevators JButton:
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.JFrame;
public class Run extends Input{
Input i = new Input();
public static void main(String[] args) {
new Run();
}
public Run() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Elevators");
frame.setLayout(new GridLayout(0, 3));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Elevators(Color.MAGENTA, true));
frame.add(new Elevators(Color.ORANGE, false));
frame.setSize(800,600);
frame.setResizable(false);
frame.getContentPane().add(toggleElevators); //adds toggleElevators button to JFrame
i.addButtonListeners(); //calls method defined in Input class, which adds the ActionListener to the toggleElevators button
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Input class (creates toggleElevators JButton and its ActionListener):
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
public class Input {
JButton toggleElevators = new JButton("Click me.");
public void addButtonListeners() {
toggleElevators.addActionListener(new toggleElevatorsListener());
}
class toggleElevatorsListener implements ActionListener {
public void actionPerformed (ActionEvent event) {
toggleElevators.setText("Clicked.");
System.out.println("ActionListener called."); //I know the ActionListener is not being called because this line is not being printed out in the console
}
}
}
Your Run class extends Input, but also HAS an Input named i. You're adding this.toggleElevators to the frame, but you're adding a listener to i.toggleElevators.
Remove the i field from your class. I would also forget completely about defining and extending an Input class. It doesn't serve any purpose, and seems to confuse more than help you.
You create a new Input in your Run class, while the Run class also extends Input.
When you call i.addButtonListeners(); the action listeners are added on the toggleElevators from i and not on the toggleElevators you inherited from the Input class.
Try addButtonListeners().
Your Run class extends Input. Therefore it has its own toggleElevators which is the one it sets in the frame. However, i has is own toggleElevators where it sets the event listeners. So they are not set on the one in the frame but on one that never gets used.
You can simply delete the i object. As Run extends Input, it can call the method directly, and then the listener will be added to its own toggleElevators.

ActionListener principles

I am trying to find basic principles of adding action to JButton or other components. Here is what I am doing and what am I getting.
I have created a class named : Ali which has a main method in it, inside the main method Instantiate another method called: MainFrame and Whatever components I have I put in here.
I have created a simple button here, registered that with ActionListener interface, and I wrote an actionPerformed() method for that. Very simple and easy. But, somehow this program giving an error to me.
Here is the simplified codes and and errors.
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Ali{
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
JFrame frame = new MainFrameAli2("MainFrameAli2");
frame.setSize(400,600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
And here is the MainFrameAli2 class
public class MainFrameAli2 extends JFrame implements ActionListener {
public MainFrameAli2(String title){
super(title);
// set layout manager
setLayout(new BorderLayout());
// create swing component
JTextArea textArea = new JTextArea();
JButton button = new JButton("click");
// add swing components to content pane
Container c = getContentPane();
c.add(textArea, BorderLayout.NORTH);
c.add(button, BorderLayout.SOUTH);
// add behavior
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
System.out.println("Clicked");
}
});
}
}
Now the problem is code is not running, here is the error:
Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problems:
The public type MainFrameAli2 must be defined in its own file
The type MainFrameAli2 must implement the inherited abstract method ActionListener.actionPerformed(ActionEvent)
And, if I write the code like below, everything is working OK.
// add behavior
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
System.out.println("hooyt");
}
}
Why it is not working in the first case and working in second case?
so, why it is not working in the first case and working in second case.?
Like the compiler message says, in the first example you didn't implement the ActionListener interface in your MainFrameAli2 class.
You created an anonymous inner class which implements the ActionListener interface. This is not the same thing as having your class implement the interface.
In the second example your class does implement the ActionListener.
If the first example you could have done:
//public class MainFrameAli2 extends JFrame implements ActionListener {
public class MainFrameAli2 extends JFrame {

Java JButton - making simple menu

Hi take a look on this code:
package arkanoid;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.event.*;
public class Arkanoid extends JFrame
{
private static final long serialVersionUID = 6253310598075887445L;
static JFrame frame;
static class Action1 implements ActionListener {
public void actionPerformed (ActionEvent e) {
//frame = new JFrame("Arkanoid");
frame.setLocationRelativeTo(null);
frame.setIgnoreRepaint(true);
frame.setResizable(false);
frame.setVisible(true);
frame.setSize(500,400);
frame.add(new Gra());
}
}
static class Action2 implements ActionListener {
public void actionPerformed (ActionEvent e) {
frame.dispose();
System.exit(0);
}
}
public static void main(String[] args)
{
//new Arkanoid();
frame = new JFrame("Arkanoid");
frame.setSize(500,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Arkanoid BETA");
frame.setLocationRelativeTo(null);
frame.setIgnoreRepaint(true);
frame.setResizable(false);
frame.setVisible(true);
JPanel panel = new JPanel();
frame.add(panel);
JButton button = new JButton("Nowa Gra");
panel.add(button);
button.addActionListener (new Action1());
JButton button2 = new JButton("Wyjscie");
panel.add(button2);
button2.addActionListener (new Action2());
}
}
This code almost works, I want to make a button2 a quit button working like X button in top right frame's icons and button1 need to open a Gra() in the same window. When im doing it like this it isnt work fine:/ i need to click 2 times on button1 to go to Gra() and what is more KeyListeners in Gra() arent working :(
Im new in buttons, frames and panels in java so please help with this code. Correct it please.
There are a number of fundamental problems with your code, the least of which is why your button1 requires 2 clicks.
However, for your problem you should try rearranging the order of your button1 listener, so that your Component is added to the frame first, before setting it to be visible. An example that should work:
static class Action1 implements ActionListener {
public void actionPerformed (ActionEvent e) {
frame.add(new Gra());
frame.revalidate();
}
}
Note you have already set the size, location etc of frame in main, so there is no need to set them again every time the button is clicked.
I stress that there are more important problems with your code than this issue. You should take a look at Java's Modifier Types (static does not seem applicable here), as well as object-oriented concepts such as inheritance (you define your Arkanoid class to extend JFrame, yet have a JFrame object as a class variable).
I want to make a button2 a quit button working like X button in top right frame's
You can use the ExitAction class found in Closing an Application.
For other examples of how to use buttons read the Swing tutorial on How to Use Buttons. This is the place to start for all you Swing related questions.
There are many problems with your code. I've refactored it a little. With below code & #ricky116 answer I think you should get all of them.
import javax.swing.*;
import java.awt.Color;
import java.awt.event.*;
public class Arkanoid extends JFrame
{
public Arkanoid() {
super("Arkanoid");
setSize(500,400);
setTitle("Arkanoid BETA");
setLocationRelativeTo(null);
setResizable(false);
final JPanel panel = new JPanel();
setContentPane(panel);
panel.add(new JButton(new AbstractAction("Nowa Gra") {
public void actionPerformed (ActionEvent e) {
panel.removeAll();
panel.add(new Gra());
panel.revalidate();
panel.repaint();
}
});
panel.add(new JButton(new AbstractAction("Wyjscie") {
public void actionPerformed (ActionEvent e) {
Arkanoid.this.setVisible(false);
}
});
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Arkanoid frame = new Arkanoid();
frame.setVisible(true);
}
});
}
}

ActionListener Event in Java

Ok, i started learning java, and this is a code from internet that doesn't work on my pc
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class form2
{
public static void main(String args[])
{
// Create Frame 1
JFrame frame = new JFrame("Frame 1");
frame.setSize(333,333);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create panel
JPanel panel = new JPanel();
// Create button
JButton button = new JButton("Press me!");
// Add things
panel.add(button);
frame.add(panel);
frame.setVisible(true);
// Add the action listener to that button
button.addActionListener(new action());
static class action implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
// Create Frame 2
JFrame frame2 = new JFrame("Frame 2");
frame2.setSize(200,200);
frame2.setVisible(true);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Clicked!");
JPanel panel2 = new JPanel();
// First add to frame2 the panel just create
frame2.add(panel2);
// Add to panel the label
panel2.add(label);
}
}
}
}
And it give me an error about action and i don't understand why.
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
action cannot be resolved to a type
Illegal modifier for the local class action; only abstract or final is permitted
at form2.main(form2.java:26)
What is my problem?? On that guy's computer works
http://www.youtube.com/watch?v=jEXxaPQ_fQo&feature=channel_video_title
Can anyone help me??
You are declaring a static class inside of a method which you shouldn't do. So take it out of the method, or better, make it an anonymous inner class:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Create Frame 2
JFrame frame2 = new JFrame("Frame 2");
frame2.setSize(200, 200);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Clicked!");
JPanel panel2 = new JPanel();
// First add to frame2 the panel just create
frame2.add(panel2);
// Add to panel the label
panel2.add(label);
frame2.setVisible(true);
}
});
What does this question have to do with java-ee by the way??
You declare a class inside a method, in this case main, however, it should be outside of it, like the guy in the video says.
Hope that helps!
Static classes cannot be defined inside a method. Move the class definition static class .... { } outside of your main method. Also, it is good practice to start classes with an uppercase character (e.g AddPanelAction).
The actionlistener class must be declared outside of the main method like this:
import javax.swing.*;
import java.awt.event.*;
public class Main
{
public static void main(String args[])
{
// Create Frame 1
JFrame frame = new JFrame("Frame 1");
frame.setSize(333,333);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create panel
JPanel panel = new JPanel();
// Create button
JButton button = new JButton("Press me!");
// Add things
panel.add(button);
frame.add(panel);
frame.setVisible(true);
// Add the action listener to that button
button.addActionListener(new action());
}
public static class action implements ActionListener {
public void actionPerformed(ActionEvent e) {
// Create Frame 2
JFrame frame2 = new JFrame("Frame 2");
frame2.setSize(200,200);
frame2.setVisible(true);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Clicked!");
JPanel panel2 = new JPanel();
// First add to frame2 the panel just create
frame2.add(panel2);
// Add to panel the label
panel2.add(label);
}
}
}
Or you can declare the actionlistener by using an anonymous inner class like this:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Do things here
}
});
Static classes can not be defined inside a method. Move that class outside the main method or declare your class non-static within the main method itself, if you need . A static class always requires one outer non-static class.
A day late and dollar short.... but I'll still add it.
Most of the Java actionListener examples on the web are too darn complex. To understand it, you just really need a form, button, and the actionListener. In the example below, the form server as the listener through the addition of 'implements ActionListener'.
import java.applet.Applet;
import java.awt.Button;
import java.awt.Toolkit;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Sample extends Applet implements ActionListener {
Button button;
public void init() {
setLayout(new BorderLayout());
button = new Button("Test");
add("Center", button);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
// your code to do what you want when the button was clicked goes here
}
}

Difficulty removing all components from a Jpanel

G'day all,
I am coding a main menu for a project. The menu displays properly. I have also set up ActionListeners for the three buttons on the menu.
What I wish to do is reuse the JPanel for a new set of radio buttons when the user chooses "Start a New Game".
However, coding ActionPerformed to remove the existing components from the JPanel has me stumped. I know removeAll is somehow important, but unfortunately NetBeans informs me I cannot call it on my mainMenu JPanel object within ActionPerformed. So i have commented it out in my code below, but left it in so you can see what I am trying to do.
Your thoughts or hints are appreciated.
Here is my main code:
public class Main {
public static void main(String[] args) {
MainMenu menu = new MainMenu();
menu.pack();
menu.setVisible(true);
}
}
Here is my mainMenu code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MainMenu extends JFrame implements ActionListener {
JButton startNewGame = new JButton("Start a New Game");
JButton loadOldGame = new JButton("Load an Old Game");
JButton seeInstructions = new JButton("Instructions");
public MainMenu() {
super("RPG Main Menu");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainMenu = new JPanel();
mainMenu.setLayout(new FlowLayout());
startNewGame.setMnemonic('n');
loadOldGame.setMnemonic('l');
seeInstructions.setMnemonic('i');
startNewGame.addActionListener(this);
loadOldGame.addActionListener(this);
seeInstructions.addActionListener(this);
mainMenu.add(startNewGame);
mainMenu.add(loadOldGame);
mainMenu.add(seeInstructions);
setContentPane(mainMenu);
}
public void actionPerformed(ActionEvent evt) {
Object source = evt.getSource();
if (source == startNewGame) {
// StartNewGame code goes here
// mainMenu.removeAll();
}
if (source == loadOldGame) {
// LoadOldGame code goes here
}
if (source == seeInstructions) {
// Quit code goes here
}
}
}
Consider using a CardLayout instead, which manages two or more components (usually JPanel instances) that share the same display space. That way you don't have to fiddle with adding and removing components at runtime.
You need mainMenu to be a member variable:
public class MainMenu extends JFrame implements ActionListener {
JButton startNewGame = new JButton("Start a New Game");
JButton loadOldGame = new JButton("Load an Old Game");
JButton seeInstructions = new JButton("Instructions");
JPanel mainMenu = new JPanel();
Why do you feel the need to re-use this object?
You don't have a reference to mainMenu actionPerformed use. If you declare mainMenu with the buttons. It would work.
The problem is that the actionPerformed method is trying to call the JPanel mainMenu which is out of scope, i.e. the mainMenu variable is not visible from the actionPerformed method.
One way to get around this is to have the JPanel mainMenu declaration in the class itself and make it an instance field which is accessible to all instance methods of the class.
For example:
public class MainMenu extends JFrame implements ActionListener
{
...
JPanel mainMenu;
public MainMenu()
{
...
mainMenu = new JPanel();
...
}
public void actionPerformed(ActionEvent e)
{
...
mainMenu.removeAll();
}
}
Avoid attempting to "reuse" stuff. Computers are quite capable of tidying up. Concentrate on making you code clear.
So instead of attempting to tidy up the panel, simply replace it with a new one.
Generally a better way to write listeners is as anonymous inner classes. Code within these will have access to final variables in the enclosing scope and to members of the enclosing class. So, if you make mainMenu final and you ActionListeners anonymous inner classes, your code should at least compile.
Also don't attempt to "reuse" classes. Try to make each class do one sensible thing, and avoid inheritance (of implementation). There is almost never any need to extend JFrame, so don't do that. Create an ActionListener for each action, rather than attempting to determine the event source.
Also note, you should always use Swing components on the AWT Event Dispatch Thread. Change the main method to add boilerplate something like:
public static void main(final String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() { public void run() {
runEDT();
}});
}

Categories

Resources