JFrame class not working in Main - java

I'm trying to write a Java program that declares a JFrame class and creates an object of that class in the main. For the life of me I cannot get the JFrame title, JPanel, and JButtons to appear when I create the "MyButtons" object in the main. All I get is a blank JPanel.
import java.awt.*;
import javax.swing.*;
import java.util.*;
class MyButtons extends JFrame
{
public MyButtons()
{
JFrame frame = new JFrame("MyButtons");
JPanel panel = new JPanel();
frame.add(panel);
JButton b1 = new JButton("Button 1");
JButton b2 = new JButton("Button 2");
panel.add(b1);
panel.add(b2);
}
}
class TestMyButtons
{
public static void main(String [] args)
{
MyButtons go = new MyButtons();
go.setSize(200,75);
go.setLocation(200,300);
go.setVisible(true);
go.setResizable(true);
go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

As you extend JFrame so you don't need to create another JFrame instance at constructor. Simply add panel to MyButtons which already inherited JFrame.
public MyButtons(){
//JFrame frame = new JFrame("MyButtons"); Commentted this
JPanel panel = new JPanel();
//frame.add(panel); And this
JButton b1 = new JButton("Button 1");
JButton b2 = new JButton("Button 2");
panel.add(b1);
panel.add(b2);
add(panel); // Add panel to MyButtons frame
}

You're making two instances of JFrame, MyButtons and JFrame frame = new JFrame("MyButtons");, to which you are adding all your components...
It's very rare that you would ever need to extend directly from a top level container like JFrame, instead, extend from something like JPanel and then add that to an instance of JFrame instead...
MyButtons...
import javax.swing.JButton;
import javax.swing.JPanel;
class MyButtons extends JPanel {
public MyButtons() {
JButton b1 = new JButton("Button 1");
JButton b2 = new JButton("Button 2");
add(b1);
add(b2);
}
}
TestMyButtons ...
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
class TestMyButtons {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new MyButtons());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

Related

How to use an ActionListener to make a JPanel Visible

I tried to make the first JPanel disappear and the second JPanel visible with the click of a JButton.
So far i only get the first JPanel to show and after clicking the JButton the Frame gets empty.
I also tried to do it with composition so i dont have to extend classes. So my bad understanding of how
composition works might be the problem. I looked into it alot but couldnt find a proper solution for my problem.
First JPanel class:
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Panel1 {
JPanel firstscreenpanel = new JPanel();
JButton jButton1 = new JButton();
Panel1() {
jButton1.setBounds(300,300,400,200);
jButton1.setBackground(Color.BLACK);
jButton1.setVisible(true);
jButton1.addActionListener(new ActionListener() {
Panel2 test = new Panel2();
public void actionPerformed(ActionEvent e) {
firstscreenpanel.setVisible(false);
test.secondscreenpanel.setVisible(true);
}
});
}
public Component panelone() {
firstscreenpanel.setSize(1280, 1024);
firstscreenpanel.setLayout(null);
firstscreenpanel.setBackground(Color.BLUE);
firstscreenpanel.add(jButton1);
firstscreenpanel.setVisible(true);
return firstscreenpanel;
}
}
Second JPanel class:
import java.awt.Color;
import java.awt.Component;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Panel2 {
public JPanel secondscreenpanel = new JPanel();
public JButton jButton2 = new JButton();
Panel2() {
jButton2.setBounds(100,100,400,200);
jButton2.setBackground(Color.BLACK);
jButton2.setVisible(true);
}
public Component paneltwo() {
secondscreenpanel.setSize(1280, 1024);
secondscreenpanel.setLayout(null);
secondscreenpanel.add(jButton2);
secondscreenpanel.setBackground(Color.RED);
secondscreenpanel.setVisible(false);
return secondscreenpanel;
}
}
JFrame Class:
import javax.swing.JFrame;
public class Frame1 {
public JFrame frame1 = new JFrame();
Panel1 panel1 = new Panel1();
Panel2 panel2 = new Panel2();
Frame1() {
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setState(JFrame.MAXIMIZED_BOTH);
frame1.setSize(1280, 1024);
frame1.setLayout(null);
frame1.add(panel1.panelone());
frame1.add(panel2.paneltwo());
frame1.setVisible(true);
}
}
Main Class:
public class MainClass {
private void showGUI() {
Frame1 jframe = new Frame1();
}
public static void main(String[] args) {
final MainClass main = new MainClass();
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run() {
main.showGUI();
}
});
}
}
I did not check the whole code (too bug, too many empty lines) but stopped at Panel2 test = new Panel2();
is this instance being added to some visible component? if not it will never be displayed.
Note: using a null layout manager is often not recommended, use a CardLayout or even a JTabbedPane to switch components - see tutorial A Visual Guide to Layout Managers
This is not the best implementation, but it is simple enough for you to follow. I modified your code to create a frame containing your original two panels (although those panel classes are not necessary - as I explained in a comment on your posted solution), and a button to toggle visibility on the panels. I am using a regular JButton and not a JToggleButton also not the best use of the class, but simply for you to understand.
The Action Listener is added to the button on the frame. Notice that my action listener does not create new instances of anything. That was part of the original problem. Since the button is a member of the frame class like the panels 1 and 2, it has access to them directly. SO, in the listener, all I need to do is "toggle" the visibility of each of the panels.
public class Frame1 extends JFrame {
private Panel1 panel1 = new Panel1();
private Panel2 panel2 = new Panel2();
private JPanel btnPanel = new JPanel();
private JButton button = new JButton("Toggle");
public Frame1() {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
boolean visible = panel1.isVisible();
panel1.setVisible(!visible);
panel2.setVisible(visible);
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setState(JFrame.MAXIMIZED_BOTH);
setSize(1280, 1024);
btnPanel.setSize(400, 100);
btnPanel.add(button);
setLayout(null);
add(panel1);
add(panel2);
add(btnPanel);
}
}
public class Panel1 extends JPanel {
public Panel1() {
setBounds(100,100,400,200);
setBackground(Color.RED);
setVisible(true);
}
}
public class Panel2 extends JPanel {
public Panel2() {
setBounds(100,100,400,200);
setBackground(Color.BLACK);
setVisible(false);
}
}
public class MainClass {
private void showGUI() {
Frame1 jframe = new Frame1();
jframe.setVisible(true);
}
public static void main(String[] args) {
final MainClass main = new MainClass();
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
main.showGUI();
}
});
}
}
You can fix your program by passing a reference of your frame to your panel1. See my example below.
Frame class
import javax.swing.*;
public class Frame1 {
private JFrame frame = new JFrame();
private Panel1 panel1;
private Panel2 panel2;
Frame1() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setState(JFrame.MAXIMIZED_BOTH);
frame.setSize(1280, 1024);
frame.setLayout(null);
panel1 = new Panel1(this);
frame.add(panel1.getPanel());
panel2 = new Panel2();
frame.add(panel2.getPanel());
frame.setVisible(true);
}
public Panel2 getPanel2() {
return panel2;
}
}
Panel1 class
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Panel1 {
private JPanel panel = new JPanel();
private Frame1 frame1;
private JButton jButton1 = new JButton();
public Panel1(Frame1 frame1) {
this.frame1 = frame1;
panel.setSize(1280, 1024);
panel.setLayout(null);
panel.setBackground(Color.BLUE);
panel.add(jButton1);
panel.setVisible(true);
jButton1.setBounds(300,300,400,200);
jButton1.setBackground(Color.BLACK);
jButton1.setVisible(true);
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
panel.setVisible(false);
frame1.getPanel2().getPanel().setVisible(true);
}
});
}
public JPanel getPanel() {
return panel;
}
}
Panel2 class
import javax.swing.*;
import java.awt.*;
public class Panel2 {
private JButton jButton2 = new JButton();
private JPanel panel = new JPanel();
public Panel2() {
panel.setSize(1280, 1024);
panel.setLayout(null);
panel.add(jButton2);
panel.setBackground(Color.RED);
panel.setVisible(false);
jButton2.setBounds(100,100,400,200);
jButton2.setBackground(Color.BLACK);
jButton2.setVisible(true);
}
public JPanel getPanel() {
return panel;
}
}
I solved my problem by adding "public static" to "Panel2 panel2 = new Panel2();"
And then i just used:
"Frame1.panel2.secondscreenpanel.setVisible(true);"
inside the JButton ActionListener.
Its now working but i guess thats a bad way of doing it. Because i heard that using to much static isnt that good. But i dont now why yet.

Click a button to open a new JFrame / GUI,

I seem to not be able to find a way to get my code to work.
I am making a program and until now everything was working, i have some buttons and they do what they should.
But now i added a button that when a user click it, it should close the current GUI and open a new one.
I also want to point out that i created a new class for this new GUI.
The other GUI class that i want to call is the GuiCrafting, in that class the GUI is also all coded, and works if i call it on the Main.
My question is what do i type here (I tried a lot of things like dispose() etc but i just get error messages) :
public void actionPerformed(ActionEvent event) {
if( str.equals("Crafting")){
//insert code to call the GuiCrafting class and open his GUI
}
Thanks in advance and if you need something more please let me know.
Multiple JFrames are frowned upon as you can read about here and here
Perhaps what you want to use is a CardLayout which manages two or more components (usually JPanel instances) that share the same display space.
After clicking the button "Goto Card 2"
TestApp.java:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestApp {
final static String CARD1 = "Card1";
final static String CARD2 = "Card2";
public TestApp() {
initComponents();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(TestApp::new);
}
private void initComponents() {
JFrame frame = new JFrame("TestApp");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create the panel that contains the "cards".
JPanel cards = new JPanel(new CardLayout());
// card 1 components
JButton buttonGotoCard2 = new JButton("Goto Card 2");
buttonGotoCard2.addActionListener((ActionEvent e) -> {
CardLayout cl = (CardLayout) (cards.getLayout());
cl.show(cards, CARD2);
});
// create card 1
JPanel card1 = new JPanel();
card1.add(new JLabel("Card 1"));
card1.add(buttonGotoCard2);
// card 2 components
JButton buttonGotoCard1 = new JButton("Goto Card 1");
buttonGotoCard1.addActionListener((ActionEvent e) -> {
CardLayout cl = (CardLayout) (cards.getLayout());
cl.show(cards, CARD1);
});
// create card 2
JPanel card2 = new JPanel();
card2.add(new JLabel("Card 2"));
card2.add(buttonGotoCard1);
// add cards to cards panel
cards.add(card1, CARD1);
cards.add(card2, CARD2);
frame.getContentPane().add(cards, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
There is also a JDialog which could be what you want.
HOWEVER
You can easily do something like that (Open a JFrame from another If you must):
TestApp.java:
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
public class TestApp {
public TestApp() {
initComponents();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(TestApp::new);
}
private void initComponents() {
JFrame mainFrame = new JFrame();
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(new EmptyBorder(10, 10, 10, 10));
JLabel label = new JLabel("JFrame 1");
JButton button = new JButton("Open JFrame 2");
button.addActionListener((ActionEvent e) -> {
this.showNewJFrame(new WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent e) {
// here we listen for the second JFrame being closed so we can bring back the main JFrame
mainFrame.setVisible(true);
}
});
// hide the main JFrame
mainFrame.setVisible(false);
});
panel.add(label);
panel.add(button);
mainFrame.add(panel);
mainFrame.pack();
mainFrame.setVisible(true);
}
private void showNewJFrame(WindowAdapter windowAdapter) {
JFrame frame2 = new JFrame();
frame2.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // we dont wnat to exit when this JFrame is closed
JPanel panel2 = new JPanel();
panel2.setLayout(new BoxLayout(panel2, BoxLayout.Y_AXIS));
panel2.setBorder(new EmptyBorder(10, 10, 10, 10));
JLabel label2 = new JLabel("JFrame 2");
panel2.add(label2);
frame2.add(panel2);
frame2.addWindowListener(windowAdapter);
frame2.pack();
frame2.setVisible(true);
}
}
This produces:
and when the "Open JFrame 2" is clicked:
and when JFrame 2 is closed it brings back the main JFrame via the WindowAdapter#windowClosing.

Window displayed but not the buttons

I wrote this code to display a window with three buttons. However, the window appears but not the buttons. Here is the code:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.*;
import java.awt.*;
public class Test3 extends JFrame{
public Test3() {
JFrame frame = new JFrame("Exemple");
JButton button1 = new JButton("Règles");
button1.setBounds(100, 60, 100, 30);
JButton button2 = new JButton("Jouer");
JButton button3 = new JButton("Scores");
JPanel pane1 = new JPanel(new GridLayout(0, 1));
this.setVisible(true);
pane1.add(button1);
pane1.add(button2);
pane1.add(button3);
frame.getContentPane().add(pane1, BorderLayout.EAST);
this.setVisible(true);
setSize(800, 600);
}
public static void main(String[] args) {
Test3 test3 = new Test3();
}
}
Does anyone have an idea on how to fix this ?
Thanks for your help !
Agnès
You have two windows...
public class Test3 extends JFrame{
public Test3() {
JFrame frame = new JFrame("Exemple");
You're adding content to frame, but showing Test3...
As a general rule of thumb, you should avoid extending from top level containers like JFrame and instead, create an instance when you need it. This unlocks you from a given implementation and allows you flexibility in deciding how you might re-use given components, as an example.
public class Test3 {
public Test3() {
JFrame frame = new JFrame("Exemple");
JButton button1 = new JButton("Règles");
JButton button2 = new JButton("Jouer");
JButton button3 = new JButton("Scores");
JPanel pane1 = new JPanel(new GridLayout(0, 1));
pane1.add(button1);
pane1.add(button2);
pane1.add(button3);
frame.getContentPane().add(pane1, BorderLayout.EAST);
frame.pack();
frame.setVisible(true);
}
Runnable example...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test3 {
public Test3() {
JFrame frame = new JFrame("Exemple");
JButton button1 = new JButton("Règles");
button1.setBounds(100, 60, 100, 30);
JButton button2 = new JButton("Jouer");
JButton button3 = new JButton("Scores");
JPanel pane1 = new JPanel(new GridLayout(0, 1));
pane1.add(button1);
pane1.add(button2);
pane1.add(button3);
frame.getContentPane().add(pane1, BorderLayout.EAST);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
Test3 test3 = new Test3();
}
});
}
}
Please try like this, I have corrected
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.*;
import java.awt.*;
public class Test3 extends JFrame{
public Test3() {
super("Exemple");
JButton button1 = new JButton("Règles");
button1.setBounds(100, 60, 100, 30);
JButton button2 = new JButton("Jouer");
JButton button3 = new JButton("Scores");
JPanel pane1 = new JPanel(new GridLayout(0, 1));
this.setVisible(true);
pane1.add(button1);
pane1.add(button2);
pane1.add(button3);
getContentPane().add(pane1, BorderLayout.EAST);
this.setVisible(true);
setSize(800, 600);
}
public static void main(String[] args) {
Test3 test3 = new Test3();
}
}

Java JButton it is not running truly

I added a jbutton with eclipse but it is not seeing correctly. How do I fix it?
this is screen shot:
public class GUITest // test class
{
// block the warnings
public static void main(String[] args) //main
{
System.out.println("start of main");
/* stackoverflow want to add more details */
JFrame frame = new JFrame();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JPanel panel = new JPanel();
frame.add(panel);
JButton button = new JButton("Click here");
panel.add(button);
button.addActionListener(new Action());
System.out.println("end of main");
/* stackoverflow want to add more details */
}
public static class Action implements ActionListener //actionlistener
{
public void actionPerformed (ActionEvent e)
{ /* stackoverflow want to add more details */
JFrame frame2 = new JFrame("Clicked");
frame2.setVisible(true);
frame2.setSize(200,200);
JLabel label = new JLabel("You clicked me!");
JPanel panel = new JPanel();
frame2.add(panel);
panel.add(label); // some more details
}
}
}
I have used this and It will working fine. Can you please check your Graphics Driver or other things.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Ashwin Parmar
*/
public class GUITest {
public static void main(String[] args) {
System.out.println("Start");
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
JPanel panel = new JPanel();
frame.add(panel);
JButton button = new JButton("Click here");
panel.add(button);
button.addActionListener(new Action());
frame.setVisible(true);
System.out.println("End");
}
public static class Action implements ActionListener{
#Override
public void actionPerformed(ActionEvent ae) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
JFrame frame2 = new JFrame("Clicked");
frame2.setSize(200,200);
JLabel label = new JLabel("You have clicked me!");
JPanel panel = new JPanel();
frame2.add(panel);
panel.add(label);
frame2.setVisible(true);
}
}
}
Always create and modify the UI from within the context of the Event Dispatching Thread
Wherever possible, call setVisible last, after you have established the basic UI. You will be required to call revalidate and repaint if you add components after the window is made visible.
For example...
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
JButton button = new JButton("Click here");
panel.add(button);
button.addActionListener(new Action());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
Do the same thing within your ActionListener.
See Initial Threads for more details

JPanel does not displayed on JFrame

Problem - the given codes below is not displaying my JPanel(PageOne) and I am not sure why is it not displaying my JPanel(PageOne). Please Help.
I have added the JPanel(PageOne) to my panel which has a cardLayout();
I have set my JFrame to visible already.
PageOne.java
import javax.swing.JLabel;
import javax.swing.JPanel;
public class PageOne extends JPanel {
public PageOne() {
JLabel label = new JLabel("Page 1");
JPanel panel = new JPanel();
panel.add(label);
} }
PageTwo.java
import javax.swing.JLabel;
import javax.swing.JPanel;
public class PageTwo extends JPanel {
public PageTwo() {
JLabel label = new JLabel("Page 2");
JPanel panel = new JPanel();
panel.add(label);
}
}
DisplayUI.java
import java.awt.CardLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class DisplayUI {
public static void main(String[] args) {
new DisplayUI();
}
public DisplayUI() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
CardLayout cardLayout = new CardLayout();
JFrame frame = new JFrame("frame");
JPanel panel = new JPanel();
panel.setLayout(cardLayout);
panel.add(new PageOne(), "1");
panel.add(new PageTwo(), "2");
cardLayout.show(panel,"1");
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
You're not actually adding anything to PageOne or PageTwo panels...
public PageOne() {
JLabel label = new JLabel("Page 1");
JPanel panel = new JPanel();
panel.add(label);
// But nothing is actually added to "this"...
}
Unless you "really" need it, you can get rid of the second JPanel and add the label directly to PageOne (and the same thing goes for PageTwo)
public PageOne() {
JLabel label = new JLabel("Page 1");
add(label);
}
Or add the JPanel you create (which contains the label)
public PageOne() {
JLabel label = new JLabel("Page 1");
JPanel panel = new JPanel();
panel.add(label);
add(panel);
}
Remember, JPanel is type of Container, it can have child components.
Get the content pane of frame and than try adding :
Container container=frame.getContentPane();
container.add(panel);
Hope this helps you.

Categories

Resources