ActionListener Event in Java - 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
}
}

Related

How to make one class react to a button pressed in another?

Hi I am new to programming and trying to figure things out as I go. Thanks in advance for the help.
I am trying to make a button in one class that when pressed, the other class knows.
Here is the first class that contains the testWindow method that I want to call in my other class.
import javax.swing.*;
import java.awt.event.*;
public class TestWindow {
public static void testWindow() {
JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel text = new JLabel("this is a test!",SwingConstants.CENTER);
text.setBounds(0,30,300,50);
JButton button = new JButton("Start");
button.setBounds(100,100,100,40);
frame.add(text);
frame.add(button);
frame.setSize(300,200);
frame.setLayout(null);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//I don't know what to put here
}
});
}
}
And here is the second class where I want to use my testWindow method.
public class MainTest extends TestWindow {
public static void main(String[] arg){
testWindow();
//other stuff that happens when "start" is pressed
}
}
When I run the MainTest class, the testWindow appears as it should. But when the "start" button is pressed, I want to close that frame then do other actions in the main method. How would I go about that?
When I run the MainTest class, the testWindow appears as it should. But when the "start" button is pressed, I want to close that frame then do other actions in the main method. How would I go about that?
You're desiring the functionality of a modal dialog, a window that halts program flow until it has been dealt with. And in this situation you shouldn't be using a JFrame which does not allow for this type of modality, but rather a Swing modal dialog such as a JOptionPane or a JDialog that you create, make modal, and display. Then the GUI program flow halt until the dialog window is no longer visible.
If you do this, all the button's action listener has to do is to close the dialog window that holds it, that's it.
Side note: You're misusing inheritance here, as your MainTest class should most definitely not extend from the TestWindow class. While it may not matter in this simple code, it can and will cause problems in future code.
e.g.,
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Dialog.ModalityType;
import java.awt.event.*;
public class TestWindow {
public static void testWindow() {
// JFrame frame = new JFrame("test");
final JDialog frame = new JDialog((JFrame) null, "Test", ModalityType.APPLICATION_MODAL);
frame.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel text = new JLabel("this is a test!", SwingConstants.CENTER);
// text.setBounds(0, 30, 300, 50);
JButton button = new JButton("Start");
// button.setBounds(100, 100, 100, 40);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.dispose();
}
});
int eb = 15;
JPanel panel = new JPanel(new BorderLayout(eb, eb));
panel.setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
panel.add(text, BorderLayout.PAGE_START);
panel.add(button, BorderLayout.CENTER);
frame.add(panel);
frame.pack();
// frame.setSize(300, 200);
// frame.setLayout(null);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
and
import javax.swing.SwingUtilities;
public class TestTestWindow {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
TestWindow.testWindow();
System.out.println("Called after test window no longer visible");
});
}
}

Calling different screen thru button from a screen

Hello I would like to ask how can I call my Main menu screen from MainScreen? and kindly explain a little more details about Listener.
below is my prepared code:
public class MainScreen {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.add(panel);
placeComponents(panel);
frame.setVisible(true);
}
private static void placeComponents(JPanel panel) {
JLabel WelcomeNote = new JLabel("Welcome");
panel.add(WelcomeNote);
JButton Start = new JButton("Start");
panel.add(Start);
//Insert action for Start button here
}
}
public class MainMenu {
public static void main(String[] args){
JFrame frame = new JFrame();
JPanel panel = new JPanel();
frame.add(panel);
placeComponents(panel);
frame.setVisible(true);
}
private static void placeComponents(JPanel panel) {
JLabel menuLbl = new JLabel("Main Menu");
panel.add(menuLbl);
}
}
What is wrong?
You cannot have two main methods in a single file in Java.
Program
Here is a demo program to change windows.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class First extends JFrame
{
JLabel jlb = new JLabel("Label in First Window");
JButton jb = new JButton("Next Window");
First()
{
super("First Windows");
//Set this frame
this.setSize(350,250);
this.setLayout(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Setting size of components
jlb.setBounds(10,10,200,40);
jb.setBounds(10,120,150,40);
add(jlb);
add(jb);
jb.addActionListener((e)->{
this.setVisible(false);
new Second();
});
setVisible(true);
}
}
class Second extends JFrame implements ActionListener
{
JLabel jlb = new JLabel("Label in Second Window");
JButton jb = new JButton("Prev. Window");
Second()
{
super("Second Window");
this.setSize(350,250);
this.setLayout(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Setting size of components
jlb.setBounds(10,10,200,40);
jb.setBounds(10,120,150,40);
add(jlb);
add(jb);
jb.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
this.setVisible(false);
new First();
}
}
class StartHere
{
public static void main(String[] args) {
Runnable r = ()->{
new First();
};
r.run();
}
}
Understanding the above program.
The StartHere class has a main method. It is just used for calling the first window you like. I could even call Second using new Second().
First and Second are similar codes.
Both of them have buttons. On each button (or JButton) I have added a method named addActionListner(this). This method fires up an ActionEvent which as you can see in Second class is captured by actionPerformed method. This method is declared in Functional Interface, ActionListener. The 'this' passed in Second class is you telling where the actionPerformed method is present in your code. The parameter is an ActionListener. Hence, you have to implement ActionListener for the class where you define actionPerformed.
Bonus
The First class doesn't seem to follow the norms described above. I passed a strange syntax. It is a new feature included in Java 8.
See this Oracle tutorial about Lambda Expressions.

How to opening a new class within java

Started of with java coding for school. when i create the following code it won't work.
Please help me out.
import javax.swing.*;
import java.awt.*;
public class StartScherm extends JFrame
{
public static void main( String[] args ){
JFrame frame = new StartScherm();
frame.setSize( 800, 800 );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setTitle( "CityTours" );
JPanel Paneel = new Paneel();
frame.setContentPane( Paneel );
frame.setVisible( true );
}
}
class Paneel extends JPanel {
private JButton Eng, LoginAdmin, LoginUser;
private JTextField Text;
public Paneel(){
setLayout (null);
Eng = new JButton ("Bring me to the English version");
Eng.setBounds(250,20,300,20);
Eng.addActionListener(newEngHandler());
Text = new JTextField (" Welkom bij CityTours ");
Text.setBounds(100,80,600,600);
Text.setEditable (false);
LoginAdmin = new JButton ("Login administrator");
LoginAdmin.setBounds(100,720,200,20);
LoginUser = new JButton ("Login gebruiker");
LoginUser.setBounds(500,720,200,20);
add (Eng);
add (Text);
add (LoginAdmin);
add (LoginUser);
}
class EngHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
this.dispose();
new MainScreen().setVisible(true);
}
}
}
I'm trying to create a JButton called Eng to close the frame of StartScherm.Java and open a frame of MainScreen.Java (all in the same project)
All it does is create 3 JButtons and a JTextField, and the Eng JButton action won't work. (error: cannot find symbol)
Please help me and explain to me what i do wrong.
It is not clear from your code what is MainScreen but, let me give you an idea on how you can switch between two JFrame windows with a button click.
You need access to isVisible() and setVisible() methods of JFrame in order to hide/display a window. Since, I do not know what MainScreen is, I will use StartScherm and create two instance of it (two windows with different titles) and then switch between the two.
Declare two instances of StartScherm outside your main method in StartScherm as shown below:
public class StartScherm extends JFrame {
static JFrameCloseEvent frame1;
static JFrameCloseEvent frame2;
public static void main(String[] args) {
//your main code initializing frame1 and frame2 goes here
}
}
The reason we declare frame1 and frame2 outside main method is because we want to be able to reference them in Paneel class. The reason they are static is because we initialize them in main method and main is static that is why.
Now that we have to instances of StartScherm as frame1 and frame2 we can initialize them differently in main method of StartScherm, see below:
//already declared frame1 outside main method
frame1 = new JFrameCloseEvent();
frame1.setSize(800, 800);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setTitle("CityTours Default Language");
JPanel Paneel = new Paneel();
frame1.setContentPane(Paneel);
//frame1 be visible when program start
frame1.setVisible(true);
And we will will initialize the frame2 in a similiar fashion but, with different title and set its visibility to false. See below:
frame2 = new JFrameCloseEvent();
frame2.setSize(800, 800);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setTitle("CityTours English Version");
JPanel Paneel2 = new Paneel();
frame2.setContentPane(Paneel2);
//set visibility to false because frame1 is visible at beginning
frame2.setVisible(false);
Now that we have both frame1 and frame2 initialized. We can tweak our Paneel to properly implement an ActionListener and switch visibility of the frame1 and frame2. In order to set ActionListener on a button, I prefer the following approach:
Eng = new JButton("Bring me to the English version");
Eng.setBounds(250, 20, 300, 20);
Eng.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(StartScherm.frame1.isVisible()) {
StartScherm.frame1.setVisible(false);
StartScherm.frame2.setVisible(true);
} else {
StartScherm.frame1.setVisible(true);
StartScherm.frame2.setVisible(false);
}
}
});
As you can see above, I attach the ActionListener straight to button. Since both frame1 and frame2 use Paneel hence, they will get the same button with action listener. When the button is clicked, the actionPerformed is executed which checks whether frame1 is visible or frame2. If frame1 is visible then it will set its visibility to false and set visibility of frame2 to true, else other way round.
Make above changes to your code, that is properly implement ActionListener as shown above, and make sure that your frame1 and frame2 instances are accessible in actionPerformed method.
I have modified your code to make it runnable, see below (obviously I removed references to MainScreen because, the only difference between frame1 and frame2 is title).
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class StartScherm extends JFrame {
static StartScherm frame1;
static StartScherm frame2;
public static void main(String[] args) {
frame1 = new StartScherm();
frame1.setSize(800, 800);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setTitle("CityTours Default Language");
JPanel Paneel = new Paneel();
frame1.setContentPane(Paneel);
frame1.setVisible(true);
frame2 = new StartScherm();
frame2.setSize(800, 800);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setTitle("CityTours English Version");
JPanel Paneel2 = new Paneel();
frame2.setContentPane(Paneel2);
frame2.setVisible(false);
}
}
class Paneel extends JPanel {
private JButton Eng, LoginAdmin, LoginUser;
private JTextField Text;
public Paneel() {
setLayout(null);
Eng = new JButton("Bring me to the English version");
Eng.setBounds(250, 20, 300, 20);
Eng.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(StartScherm.frame1.isVisible()) {
StartScherm.frame1.setVisible(false);
StartScherm.frame2.setVisible(true);
} else {
StartScherm.frame1.setVisible(true);
StartScherm.frame2.setVisible(false);
}
}
});
Text = new JTextField(" Welkom bij CityTours ");
Text.setBounds(100, 80, 600, 600);
Text.setEditable(false);
LoginAdmin = new JButton("Login administrator");
LoginAdmin.setBounds(100, 720, 200, 20);
LoginUser = new JButton("Login gebruiker");
LoginUser.setBounds(500, 720, 200, 20);
add(Eng);
add(Text);
add(LoginAdmin);
add(LoginUser);
}
}
Eng.addActionListener(newEngHandler());
should be
Eng.addActionListener(new EngHandler());
newEngHandler() would denote a method which cannot be found new EngHandler() would denote instantiating a new class

How do I maintain data from main Jframe?

So I have this calculator when you first run it you will have to input name and section and then press submit and when you press submit 4 buttons will appear and each of those buttons will bring you to another JFrame. The problem is when I press back from that other JFrame it will direct me back from that main frame and you will again have to input name and section. How do I maintain the data which the user first inputted?
You can manage that using array of Jframes , when click frame you know the index of it
May be beacuse you are Extending JFrame. Which is a bad habit .
Here I have done a short EG which creates the Object of respective Frames and calls the method
setVisible(T/F) accordingly :
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class TestMultiFrames {
JFrame mainFrame,frame2,frame3;
public TestMultiFrames(){
mainFrame =new JFrame();
frame2 =new JFrame();
frame3 =new JFrame();
JPanel p=new JPanel();
JButton but1=new JButton("frame2");
JButton but2=new JButton("frame3");
JButton but3=new JButton("back to frame 3");
p.add(but1);
frame2.add(but2);
frame3.add(but3);
but1.addActionListener(new CustomActionListener1());
but2.addActionListener(new CustomActionListener2());
but3.addActionListener(new CustomActionListener3());
mainFrame.add(p);
mainFrame.setSize(200,200);
frame2.setSize(200,200);
frame3.setSize(200,200);
mainFrame.setVisible(true);
}
public static void main(String... args)
{
new TestMultiFrames ();
}
class CustomActionListener1 implements ActionListener{
public void actionPerformed(ActionEvent e) {
mainFrame.setVisible(false);
frame2.setVisible(true);
}
}
class CustomActionListener2 implements ActionListener{
public void actionPerformed(ActionEvent e) {
frame2.setVisible(false);
frame3.setVisible(true);
}
}
class CustomActionListener3 implements ActionListener{
public void actionPerformed(ActionEvent e) {
frame3.setVisible(false);
frame2.setVisible(true);
}
}
}

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

Categories

Resources