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.
Related
I want to open MainWindow (that I created and added UI) after some time but Java opens blank default Jframe instead. How can I open already created window after splashscreen (Start)?
public class Start extends JFrame{
private JPanel panel1;
public static void main(String[] args) {
JFrame frame = new JFrame("Starting");
frame.setContentPane(new Start().panel1);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setExtendedState(JFrame.NORMAL);
frame.setUndecorated(true);
//frame.setAlwaysOnTop(true);
frame.setVisible(true);
/*Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(dim.width/2-frame.getSize().width/2, dim.height/2-frame.getSize().height/2);*/
frame.toFront();
frame.pack();
frame.setLocationRelativeTo(null);
Timer timer = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new MainWindows().setVisible(true);
frame.setVisible(false);
//System.exit(0);
}
});
timer.start();
}
MainWindows.java
public class MainWindows extends JFrame{
private JPanel panel;
public static void main(String[] args)
{
boolean clicked = false;
JOptionPane.showConfirmDialog(null, "Це перша вершія гри. Будь ласка, закрийте всі програми, щоб уникнути помилок.", "Увага!", JOptionPane.YES_OPTION);
JFrame frame2 = new JFrame("Flying");
frame2.setContentPane(new MainWindows().panel);
frame2.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame2.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame2.setUndecorated(true);
frame2.setAlwaysOnTop(true);
frame2.setVisible(true);
frame2.toFront();
frame2.pack();
Your MainWindow class has a static main method that's never invoked. It looks a lot like the code in there should have gone intoa constructor instead.
You seem to have two main methods in this program. I would suggest removing the main method from MainWindows.java and move the code from it into the MainWindows constructor. This will ensure that when you initialize the new MainWindows() object, everything in the new JFrame should be set up correctly.
Code in MainWindows.java:
public MainWindows()
{
boolean clicked = false;
JOptionPane.showConfirmDialog(null, "Це перша вершія гри. Будь ласка, закрийте всі програми, щоб уникнути помилок.", "Увага!", JOptionPane.YES_OPTION);
JFrame frame2 = new JFrame("Flying");
frame2.setContentPane(new MainWindows().panel);
frame2.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame2.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame2.setUndecorated(true);
frame2.setAlwaysOnTop(true);
frame2.setVisible(true);
frame2.toFront();
frame2.pack();
I finally fixed it. frame2.setContentPane(panel); Thank you for all your answers!
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");
});
}
}
So I tried to add a button to my game, but I can't understand, how to make the code work. Here's the code for my Launcher class (which has the button code and launches my whole game, imports and package not included):
public class Launcher extends JFrame {
public static void main(String[] args) {
Game game = new Game("Ninja Adventures", 720, 480);
game.start();
JButton button = new JButton("hello agin1");
Game.add(button);
button.addActionListener (new Action1());
}
static class Action1 implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame frame2 = new JFrame("Clicked");
frame2.setVisible(true);
frame2.setSize(200,200);
JLabel label = new JLabel("you clicked me");
}
}
}
Some extra code, that I think might help:
private void createDisplay(){
frame = new JFrame(title);
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
As already said you need to add the JButton to the JFrame. Which in this case is in another method. So you can create the button in that method an add it like so: frame.add(button);
Or you pass the button to the method via the constructor (I recommend the first version).
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
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
}
}