Java adding a button - java

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).

Related

Method called from first JFrame does nothing in second

I set JTextField "rfid" to setEnabled(false) in MainGUI class and created method setRfidEnabled to be able to enable textfield from another class called CardLayout.
When I try to call it from CardLayout by button event listener it does nothing, I mean to textfield, because System.out.print("LOL"); works fine. MainGUI contains JFrame and by button calls another JFrame in CardLayout class.
When I initialize MainGUI class, it has Thread[Thread-2,6,main], but when I call CardLayout it becomes Thread[AWT-EventQueue-0,6,main], same as CardLayout itself. I tried to make "rfid" volatile, no success.
---Edited code---
MainGUI:
public class MainGUI {
JTextField rfid;
JButton button;
final JFrame frame;
final JPanel pane;
LayoutChanger layout = new LayoutChanger();
public MainGUI() {
rfid = new JTextField("", 10);
button = new JButton("CardLayoutSwitch");
frame = new JFrame("Main GUI Panel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout(5,5));
pane = new JPanel(new GridLayout(5, 5));
frame.add(pane,BorderLayout.CENTER);
pane.add(rfid);
pane.add(button);
rfid.setEnabled(false);
button.setEnabled(true);
frame.pack();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed (ActionEvent e){
layout.changeLayout(1);
}
});
}
public void setRfidEnabled() {
System.out.println("LOL");
rfid.setEnabled(true);
button.setEnabled(false);
}
}
LayoutChanger class:
public class LayoutChanger {
public static void main(String[] args) {
MainGUI gui = new MainGUI();
}
public void changeLayout(int i){
if (i == 1) {
CardLayout card = new CardLayout();
}
}
}
CardLayout class:
public class CardLayout {
JFrame frame;
JButton manual;
final JPanel pane;
MainGUI gui = new MainGUI();
public CardLayout() {
manual = new JButton("UID MANUAL");
frame = new JFrame("Card Scan Panel");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLayout(new BorderLayout(5, 5));
pane = new JPanel(new BorderLayout(5, 5));
manual.setPreferredSize(new Dimension(50, 25));
frame.add(pane, BorderLayout.CENTER);
pane.add(manual);
frame.pack();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
manual.addActionListener(new ActionListener() {
#Override
public void actionPerformed (ActionEvent e){
gui.setRfidEnabled();
}
});
}
}
As stated in the comments above by #matt
Every time you click on manual button, you're creating a new MainGUI().
You need to create a single instance, either in your constructor or in the ActionListener and ask if you already have an instance of it (i.e. a Singleton) and use it.
If you decide to use the first one, declare gui as a global variable:
MainGUI gui = new MainGUI();
And on your ActionListener have it changed as:
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(currentThread());
gui.setRfidEnabled();
//frame.dispose();
}
Then you have a single instance of it.
Also as stated by #Sergiy you don't really need all those threads
Here are some examples on how to use ActionListeners:
I'm trying to make a button to count characters in a text field
AppletViewer bugged and trying to involve a timer
Calculator returns 0.0 to all questions asked
Java - My action event doesn't work
Drawing shapes on a JForm java
Animated Sprites with Java Swing This one includes a Timer (Another thread that handles the animation but doesn't block the EDT)
As you can see in all the above examples, none of them required another Thread to handle the actions, the one that uses a thread is only for performing the animation and not to react to user clicks.
Recommended tutorial: How to use Actions

JFrame appears blank instead of showing UI

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!

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

Categories

Resources