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!
Related
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.
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
I have 2 classes. Both implements runnable to create the GUI. The first one is the main, and the second one is the secondary class.
I want within the actionlistener of the main class to startup the secondary class.
Here is the code (the two classes are separated files):
public class Main implements Runnable
{
private JTextField txt1, txt2;
private JLabel lbl1, lbl2;
public void run()
{
JFrame frame = new JFrame("Secondary");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = frame.getContentPane();
JPanel background = new JPanel();
background.setLayout(new BoxLayout(background, BoxLayout.LINE_AXIS));
.........
// Horizontally adding the textbox and button in a Box
Box box = new Box(BoxLayout.Y_AXIS);
......
background.add(box);
pane.add(background);
frame.pack();
frame.setVisible(true);
}
private class SListener implements ActionListener
{
public void actionPerformed(ActionEvent a)
{
Secondary s = new Secondary();
}
}
public static void main (String[] args)
{
Main gui = new Main();
SwingUtilities.invokeLater(gui);
}
}
public class Secondary implements Runnable
{
private JTextField txt1, txt2;
private JLabel lbl1, lbl2;
public Secondary()
{
Secondary gui = new Secondary();
SwingUtilities.invokeLater(gui);
}
public void run()
{
JFrame frame = new JFrame("Secondary");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container pane = frame.getContentPane();
JPanel background = new JPanel();
background.setLayout(new BoxLayout(background, BoxLayout.LINE_AXIS));
.........
// Horizontally adding the textbox and button in a Box
Box box = new Box(BoxLayout.Y_AXIS);
......
background.add(box);
pane.add(background);
frame.pack();
frame.setVisible(true);
}
}
I want to keep the code in two files, I don't want to mixed the two classes in one file.
As you can see from the code, in the Secondary class, in it's constructor I create an Instance of the Secondary class and I run the gui so that when the Instance of this class is created in the Main class, to run the gui.
Unfortunately this technique is not working.
Any ideas?
Thanks
The following line are complety wrong:
public Secondary(){
Secondary gui = new Secondary();
SwingUtilities.invokeLater(gui);
}
Each time you call new Secondary() somewhere in your code, the above code will be triggered, which in turn calls new Secondary() again, and again, and again, ... and your program is blocked.
You probably want to replace it either by
public Secondary(){
SwingUtilities.invokeLater(this);
}
which will avoid the loop, but this is weird behaviour for a constructor.
It makes much more sense to switch to an empty constructor (or delete it all together)
public Secondary(){
}
and rewrite your listener to
public void actionPerformed(ActionEvent a){
Secondary s = new Secondary();
SwingUtilities.invokeLater( s );
}
I would recommend that you completely re-design your program. I find that it is most helpful to gear my GUI's towards creation of JPanels, not top level windows such as JFrame, which can then be placed into JFrames or JDialogs, or JTabbedPanes, or swapped via CardLayouts, wherever needed. I find that this greatly increase the flexibility of my GUI coding, and is exactly what I suggest that you do. So...
Your first class creates a JPanel that is then placed into a JFrame.
In the first class's ActionListener, create an instance of the 2nd class, place it into a JDialog (not a JFrame), and then display it.
For example,
import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class TwoWindowEg {
public TwoWindowEg() {
// TODO Auto-generated constructor stub
}
private static void createAndShowGui() {
GuiPanel1 mainPanel = new GuiPanel1();
JFrame frame = new JFrame("Main GUI");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class GuiPanel1 extends JPanel {
private static final int PREF_W = 800;
private static final int PREF_H = 650;
private GuiPanel2 guiPanel2 = new GuiPanel2(); // our second class!
private JDialog dialog = null; // our JDialog
public GuiPanel1() {
setBorder(BorderFactory.createTitledBorder("GUI Panel 1"));
add(new JButton(new LaunchNewWindowAction("Launch New Window")));
add(new JButton(new DisposeAction("Exit", KeyEvent.VK_X)));
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class LaunchNewWindowAction extends AbstractAction {
public LaunchNewWindowAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent e) {
if (dialog == null) {
// get the Window that holds this JPanel
Window win = SwingUtilities.getWindowAncestor(GuiPanel1.this);
dialog = new JDialog(win, "Second Window", ModalityType.APPLICATION_MODAL);
dialog.add(guiPanel2);
dialog.pack();
}
dialog.setVisible(true);
}
}
}
class GuiPanel2 extends JPanel {
public GuiPanel2() {
setBorder(BorderFactory.createTitledBorder("GUI Panel 1"));
add(new JLabel("The second JPanel/Class"));
add(new JButton(new DisposeAction("Exit", KeyEvent.VK_X)));
}
}
class DisposeAction extends AbstractAction {
public DisposeAction(String name, int mnemonic) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
Component comp = (Component) e.getSource();
Window win = SwingUtilities.getWindowAncestor(comp);
win.dispose();
}
}
Alternatively, you could swap JPanel "views" using a CardLayout, but either way, you will want to avoid showing two JFrames. Please have a look at The Use of Multiple JFrames, Good/Bad Practice?.
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);
}
});
}
}