How to access a CardLayout variable from an outside class? - java

I have two classes (lay and panelTwo). In "lay" I have my MainMethod and this is where I've put my CardLayout. What I'm trying to do is access that class within another outside class. But I can't seem to access it whilst trying to write my ActionListener:
public class lay {
JFrame frame;
JPanel panelCont;
JPanel panelOne;
JButton buttonOne;
CardLayout cards;
PanelTwo panelTwo;
public lay() {
frame = new JFrame("Start");
panelCont = new JPanel();
panelOne = new JPanel();
panelTwo = new PanelTwo();
buttonOne = new JButton("Got to two");
cards = new CardLayout();
panelCont.setLayout(cards);
panelOne.add(buttonOne);
panelOne.setBackground(Color.BLUE);
panelCont.add(panelOne, "1");
panelCont.add(panelTwo, "2");
cards.show(panelCont, "1");
buttonOne.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cards.show(panelCont, "2");
}
});
frame.add(panelCont);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new lay();
}
});
}
}
And here is my other class where the problem is:
public class PanelTwo extends JPanel {
JButton buttonTwo;
public PanelTwo() {
buttonTwo = new JButton("Go to one");
add(buttonTwo);
setBackground(Color.GREEN);
buttonTwo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cards.show(panelCont, "1");
}
});
}
}
As you can probably tell, I get errors in "cards.show(panelCont, "1")". And I do understand why that is. I just don't know what the solution is.

Do they need to be in separate files? You can make PanelTwo an inner class of lay class. You're getting the error, because the tow variables are not in the scope of the lay class which those are members of. If you did the below, errors would go away.
public class lay {
...
private class PanelTwo {
}
}
EDIT
What you need to do using two separate class files is to create a constructor in the PanelTwo where you take in arguments of your CardLayout and the JPanel from the lay class. Then instantiate the PanelTwo with those two arguments.
Try this out. I passed the CardLayout and the JPanel to a constructor of PanelTwo. Works fine.
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class lay {
JFrame frame;
JPanel panelCont;
JPanel panelOne;
JButton buttonOne;
CardLayout cards;
PanelTwo panelTwo;
public lay() {
frame = new JFrame("Start");
panelCont = new JPanel();
panelOne = new JPanel();
cards = new CardLayout();
panelTwo = new PanelTwo(cards, panelCont);
buttonOne = new JButton("Got to two");
panelCont.setLayout(cards);
panelOne.add(buttonOne);
panelOne.setBackground(Color.BLUE);
panelCont.add(panelOne, "1");
panelCont.add(panelTwo, "2");
cards.show(panelCont, "1");
buttonOne.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cards.show(panelCont, "2");
}
});
frame.add(panelCont);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new lay();
}
});
}
}
class PanelTwo extends JPanel {
JButton buttonTwo;
CardLayout layout;
JPanel panelCont;
public PanelTwo(final CardLayout layout, final JPanel panelCont) {
this.layout = layout;
this.panelCont = panelCont;
buttonTwo = new JButton("Go to one");
add(buttonTwo);
setBackground(Color.GREEN);
buttonTwo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
layout.show(panelCont, "1");
}
});
}
}
I also initialized the CardLayout in the lay constructor before initializing the PanelTwo. This avoids a NullPointerException

Related

Is there a way to reference setVisible() and dispose() from an ActionListener in a separate class file?

I'm working on a very complicated, multi-layered Swing GUI, and the main issue I'm running into right now involves having a JButton ActionListener perform setVisible() on a separate JFrame and immediately dispose() of the current JFrame. Because of the length of my code, it's important that main, both JFrames, and the ActionListener are all split into individual class files. I wrote a VERY simplified version of my problem, split into 4 tiny class files. Here they are:
File 1:
import javax.swing.*;
public class Test {
public static void main(String[] args) {
JFrame g1 = new GUI1();
g1.pack();
g1.setLocation(200,200);
g1.setVisible(true);
JFrame g2 = new GUI2();
g2.pack();
g2.setLocation(400,200);
g2.setVisible(false);
}
}
File 2:
import javax.swing.*;
public class GUI1 extends JFrame {
JPanel panel;
JButton button;
public GUI1() {
super("GUI1");
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new JPanel();
button = new JButton("Create GUI2");
button.addActionListener(new Listener());
add(panel);
add(button);
}
}
File 3:
import javax.swing.*;
public class GUI2 extends JFrame {
JPanel panel;
JLabel label;
public GUI2() {
super("GUI2");
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new JPanel();
label = new JLabel("I'm alive!");
add(panel);
add(label);
}
}
File 4:
import java.awt.event.*;
public class Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
GUI2.setVisible(true);
GUI1.dispose();
}
}
As you can see, the only function of the ActionListener is to set GUI2 to visible and dispose of GUI1, but it runs the error "non-static method (setVisible(boolean) and dispose()) cannot be referenced from a static context". I figure this is because both methods are trying to reference objects that were created in main, which is static. My confusion is how to get around this, WITHOUT combining everything into one class.
Any suggestions? Thanks!
EDIT:
Here's the above code compiled into one file... although it returns the exact same error.
import javax.swing.*;
import java.awt.event.*;
public class Test {
public static void main(String[] args) {
JFrame g1 = new GUI1();
g1.pack();
g1.setLocation(200,200);
g1.setVisible(true);
JFrame g2 = new GUI2();
g2.pack();
g2.setLocation(400,200);
g2.setVisible(false);
}
}
class GUI1 extends JFrame {
JPanel panel;
JButton button;
public GUI1() {
super("GUI1");
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new JPanel();
button = new JButton("Create GUI2");
button.addActionListener(new Listener());
add(panel);
add(button);
}
}
class GUI2 extends JFrame {
JPanel panel;
JLabel label;
public GUI2() {
super("GUI2");
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new JPanel();
label = new JLabel("I'm alive!");
add(panel);
add(label);
}
}
class Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
GUI2.setVisible(true);
GUI1.dispose();
}
}
You have to pass instances of frame1 and frame2 to your ActionListener.
import java.awt.event.*;
public class Listener implements ActionListener {
private JFrame frame1, frame2;
public Listener(JFrame frame1, JFrame frame2) {
this.frame1 = frame1;
this.frame2 = frame2;
}
public void actionPerformed(ActionEvent e) {
frame2.setVisible(true);
frame1.dispose();
}
}
This means you have to pass an instance of frame2 to your GUI1 class.
import javax.swing.*;
public class GUI1 extends JFrame {
JPanel panel;
JButton button;
public GUI1(JFrame frame2) {
super("GUI1");
setDefaultCloseOperation(EXIT_ON_CLOSE);
panel = new JPanel();
button = new JButton("Create GUI2");
button.addActionListener(new Listener(this, frame2));
add(panel);
add(button);
}
}
This means you have to create the frames in the reverse order.
import javax.swing.*;
public class Test {
public static void main(String[] args) {
JFrame g2 = new GUI2();
g2.pack();
g2.setLocation(400,200);
g2.setVisible(false);
JFrame g1 = new GUI1(g2);
g1.pack();
g1.setLocation(200,200);
g1.setVisible(true);
}
}

How to swap JPanel's from an action in a JPanel

I am new(ish) to Java Swing but I have not been able to find an elegant solution to my issue so I thought I'd raise a question here.
I am trying to make my current JPanel change to another JPanel based on a button click event from within the current JPanel. In essence just hiding one panel and displaying the other. I feel this can be done within my MainFrame class however I'm not sure how to communicate this back to it. Nothing I am trying simply seems to do as desired, I'd appreciate any support. Thanks
App.java
public static void main(final String[] args) {
MainFrame mf = new MainFrame();
}
MainFrame.java
public class MainFrame extends JFrame {
public MainFrame(){
setTitle("Swing Application");
setSize(1200, 800);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setVisible(true);
// First Page Frame switch
getContentPane().add(new FirstPage());
}
}
FirstPage.java
public class FirstPage extends JPanel {
public FirstPage() {
setVisible(true);
JButton clickBtn = new JButton("Click");
clickBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
// Change to SecondPage JPanel here.
}
});
add(clickBtn);
}
}
SecondPage.java
public class SecondPage extends JPanel {
public SecondPage() {
setVisible(true);
add(new JLabel("Welcome to the Second Page"));
}
}
Any more information needed, please ask thanks :)
I think the best way is to use CardLayout. It is created for such cases. Check my example:
public class MainFrame extends JFrame {
private CardLayout cardLayout;
public MainFrame() {
super("frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cardLayout = new CardLayout();
getContentPane().setLayout(cardLayout);
getContentPane().add(new FirstPage(this::showPage), Pages.FIRST_PAGE);
getContentPane().add(new SecondPage(this::showPage), Pages.SECOND_PAGE);
setLocationByPlatform(true);
pack();
}
public void showPage(String pageName) {
cardLayout.show(getContentPane(), pageName);
}
public static interface PageContainer {
void showPage(String pageName);
}
public static interface Pages {
String FIRST_PAGE = "first_page";
String SECOND_PAGE = "second_page";
}
public static class FirstPage extends JPanel {
public FirstPage(PageContainer pageContainer) {
super(new FlowLayout());
JButton button = new JButton("next Page");
button.addActionListener(e -> pageContainer.showPage(Pages.SECOND_PAGE));
add(button);
}
}
public static class SecondPage extends JPanel {
public SecondPage(PageContainer pageContainer) {
super(new FlowLayout());
add(new JLabel("This is second page."));
JButton button = new JButton("Go to first page");
button.addActionListener(e -> pageContainer.showPage(Pages.FIRST_PAGE));
add(button);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MainFrame().setVisible(true));
}
}
CardLayout is the right tool for the job.
You can simply create the ActionListener used to swap pages in JFrame class, and pass a reference of it to FirstPage:
import java.awt.CardLayout;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class MainFrame extends JFrame {
public MainFrame(){
setTitle("Swing Application");
setSize(1200, 800);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationByPlatform(true);
//Create card layout and set it to the content pane
CardLayout cLayout = new CardLayout();
setLayout(cLayout);
//create and add second page to the content pane
JPanel secondPage = new SecondPage();
add("SECOND",secondPage);
//create an action listener to swap pages
ActionListener listener = actionEvent ->{
cLayout.show(getContentPane(), "SECOND");
};
//use the action listener in FirstPage
JPanel firstPage = new FirstPage(listener);
add("FIRST", firstPage);
cLayout.show(getContentPane(), "FIRST");
setVisible(true);
}
public static void main(String[] args) {
new MainFrame();
}
}
class FirstPage extends JPanel {
public FirstPage(ActionListener listener) {
JButton clickBtn = new JButton("Click");
clickBtn.addActionListener(listener);
add(clickBtn);
}
}
class SecondPage extends JPanel {
public SecondPage() {
add(new JLabel("Welcome to the Second Page"));
}
}

JButton Wont Display JPanel

I want to call My JPanel with button. My Jpanel is actually a sub JPanel from main Panel with card layout.
to do that, i am using card layout api method HERE to show the JPanel after a button was clicked.
JButton btnCallPanel1 = new JButton("Call PanelOne");
btnCallPanel1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CardLayout card = (CardLayout)mainPanel.getLayout();
card.show(mainPanel, "PanelOne"); //call Panel One
}
output :
nothing appear, panel not called and no error pop out.
My Code is HERE
package wan.dev.sample.cardlayout;
import java.awt.CardLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
public class HowToUseCardLayout {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
HowToUseCardLayout window = new HowToUseCardLayout();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public HowToUseCardLayout() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 688, 358);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel mainPanel = new JPanel();
mainPanel.setBounds(0, 0, 672, 260);
frame.getContentPane().add(mainPanel);
mainPanel.setLayout(new CardLayout(0, 0));
JPanel PrePanel = new JPanel();
mainPanel.add(PrePanel, "name_246268073832057");
PrePanel.setLayout(null);
JLabel lblPanel_1 = new JLabel("Pre Panel");
lblPanel_1.setBounds(280, 115, 57, 20);
PrePanel.add(lblPanel_1);
JPanel panelOne = new JPanel();
mainPanel.add(panelOne, "name_246268067657434");
panelOne.setLayout(null);
JLabel lblPanel = new JLabel("panel 1");
lblPanel.setBounds(279, 118, 46, 14);
panelOne.add(lblPanel);
JButton btnPan1 = new JButton("Call PanelOne");
btnPan1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CardLayout card = (CardLayout) mainPanel.getLayout();
card.show(mainPanel, "PanelOne");
}
});
btnPan1.setBounds(262, 286, 144, 23);
frame.getContentPane().add(btnPan1);
}
}
ANSWER
The reason i cant call my panel because i did not call it by using identifier.
i have to give identifier name to my desire jpanel and use the identifier on my cardLayout.show(..)
Public Static final String PANEL_ONE = "panel one"; //Name of JPanel Identifier
//add panel to main panel and declare panelOne identifier
mainPanel.add(panelOne, PANEL_ONE); //PANEL_ONE function like
//an identifier
JButton btnCallPanel1 = new JButton("Call PanelOne");
btnCallPanel1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CardLayout card =
(CardLayout)mainPanel.getLayout();
card.show(mainPanel, PANEL_ONE); //call panelOne using PANEL_ONE
//instead of JPanel name
}
As I suspected — You're calling the CardLayout.show(...) method with the String parameter "PanelOne", but yet you've not added any component to the CardLayout-using container using this same String, so it makes sense that it won't work. Solution: don't do this. Use the Same String that you add the component to the CardLayout using container as the one that you use to display it.
i.e., If you want to display container foo and use the String "bar" to add it to the CardLayout-using container, then you must pass "bar" into the CardLayout's show(...) method. Again, use String constants for this so that you reduce the chances of messing up.
Other issues: You're using null layout and setBounds — Don't. Doing this makes for very inflexible GUI's that while they might look good on one platform look terrible on most other platforms or screen resolutions and that are very difficult to update and maintain.
e.g.,
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class CardLayoutFoo extends JPanel {
public static final String BAR = "bar";
public static final String BUTTON_PANEL = "button panel";
private CardLayout cardlayout = new CardLayout();
public CardLayoutFoo() {
setLayout(cardlayout);
JLabel fooLabel = new JLabel("Foo", SwingConstants.CENTER);
add(fooLabel, BAR); // added using String constant, BAR
JButton showFooBtn = new JButton(new AbstractAction("Show Foo") {
#Override
public void actionPerformed(ActionEvent evt) {
// use same String, BAR, to get the fooLabl shown
cardlayout.show(CardLayoutFoo.this, BAR);
}
});
JPanel btnPanel = new JPanel();
btnPanel.add(showFooBtn);
add(btnPanel, BUTTON_PANEL);
cardlayout.show(this, BUTTON_PANEL);
}
private static void createAndShowGui() {
CardLayoutFoo mainPanel = new CardLayoutFoo();
JFrame frame = new JFrame("CardLayoutFoo");
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();
}
});
}
}

How to send an ActionPerformed from an ActionListener to another ActionListener?

I've got a Frame (named here "MainApplication"), which mainly has a JPanel to show informations, depending on the context.
On startup, the MainApplication has an empty JPanel.
It then creates a "LoginRequest" class, which creates a simple login/password form, and send it back to the MainApplication, which displays it in its JPanel.
The "LoginRequest" class implements ActionListener, so when the user clicks on the "Login" button, it checks wheter or not the login/password is correct, and, if the user is granted, I want to unload that form, and display the main screen on the MainApplication Frame.
So, to do it, I came up with this :
public class LoginRequest implements ActionListener {
protected MainApplication owner_m = null;
public LoginRequest(MainApplication owner_p) {
owner_m = owner_p;
}
#Override
public void actionPerformed(ActionEvent event_p) {
// the user just clicked the "Login" button
if (event_p.getActionCommand().equals("RequestLogin")) {
// check if login/password are correct
if (getParameters().isUserGranted(login_l, password_l)) {
// send an ActionEvent to the "MainApplication", so as it will
// be notified to display the next screen
this.owner_m.actionPerformed(
new java.awt.event.ActionEvent(this, 0, "ShowSummary")
);
} else {
messageLabel_m.setForeground(Color.RED);
messageLabel_m.setText("Incorrect user or password");
}
}
}
}
Then, the "MainApplication" class (which extends JFrame) :
public class MainApplication extends JFrame implements ActionListener {
protected void load() {
// create the panel to display information
mainPanel_m = new JPanel();
// on startup, populate the panel with a login/password form
mainPanel_m.add(new LoginRequest(this).getLoginForm());
this.add(mainPanel_m);
}
#Override
public void actionPerformed(ActionEvent event_p) {
// show summary on request
if (event_p.getActionCommand().equals("ShowSummary")) {
// remove the previous information on the panel
// (which displayed the login form on this example)
mainPanel_m.removeAll();
// and populate the panel with other informations, from another class
mainPanel_m.add(...);
...
...
}
// and then refresh GUI
this.validate();
this.repaint();
this.pack();
}
}
When the ActionEvent is sent from the "LoginRequest" class to the "MainApplication" class, it executes the code, but at the end, nothing happens, as if the JFrame wasn't repainted.
Any ideas ?
Thanks,
The best way would be to use JDialog (main frame JFrame would be a parent component) for login form and CardLayout to switch between panels (so there is no need for removing, repainting and revalidating):
Your main form should look something like this:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MainFrame{
JFrame frame = new JFrame("Main frame");
JPanel welcomePanel = new JPanel();
JPanel workspacePanel = new JPanel();
JPanel cardPanel = new JPanel();
JButton btnLogin = new JButton("Login");
JLabel lblWelcome = new JLabel("Welcome to workspace");
CardLayout cl = new CardLayout();
LoginRequest lr = new LoginRequest(this);
public MainFrame() {
welcomePanel.add(btnLogin);
btnLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
lr.setVisible(true);
}
});
workspacePanel.add(lblWelcome);
cardPanel.setLayout(cl);
cardPanel.add(welcomePanel, "1");
cardPanel.add(workspacePanel, "2");
cl.show(cardPanel,"1");
frame.getContentPane().add(cardPanel);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setPreferredSize(new Dimension(320,240));
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String [] args){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MainFrame();
}
});
}
}
Your login form should look something like this:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginRequest extends JDialog{
/**You can add, JTextFields, JLabel, JPasswordField..**/
JPanel panel = new JPanel();
JButton btnLogin = new JButton("Login");
public LoginRequest(final MainFrame mf) {
setTitle("Login");
panel.add(btnLogin);
btnLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Put some login logic here
mf.cl.show(mf.cardPanel,"2");
dispose();
}
});
add(panel, BorderLayout.CENTER);
setModalityType(ModalityType.APPLICATION_MODAL);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
pack();
setLocationByPlatform(true);
}
}
EDIT:
Your way:
MainFrame class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MainFrame{
JFrame frame = new JFrame("Main frame");
JPanel welcomePanel = new JPanel();
JPanel workspacePanel = new JPanel();
JPanel cardPanel = new JPanel();
JButton btnLogin = new JButton("Login");
JLabel lblWelcome = new JLabel("Welcome");
LoginRequest lr = new LoginRequest(this);
public MainFrame() {
welcomePanel.add(btnLogin);
btnLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
lr.setVisible(true);
}
});
workspacePanel.add(lblWelcome);
frame.getContentPane().add(welcomePanel);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setPreferredSize(new Dimension(320,240));
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String [] args){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MainFrame();
}
});
}
}
LoginRequest class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginRequest extends JDialog{
/**You can add, JTextFields, JLabel, JPasswordField..**/
JPanel panel = new JPanel();
JButton btnLogin = new JButton("Login");
public LoginRequest(final MainFrame mf) {
setTitle("Login");
panel.add(btnLogin);
btnLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Put some login logic here
mf.frame.getContentPane().removeAll();
mf.frame.add(mf.workspacePanel);
mf.frame.repaint();
mf.frame.revalidate();
dispose();
}
});
add(panel, BorderLayout.CENTER);
setModalityType(ModalityType.APPLICATION_MODAL);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
pack();
setLocationByPlatform(true);
}
}

GUI multiple frames switch

I am writing a program for a black jack game. It is an assignment we are not to use gui's but I am doing it for extra credit I have created two frames ant they are working. On the second frame I want to be able to switch back to the first when a button is pressed. How do I do this?
first window.............
import javax.swing.* ;
import java.awt.event.* ;
import java.awt.* ;
import java.util.* ;
public class BlackJackWindow1 extends JFrame implements ActionListener
{
private JButton play = new JButton("Play");
private JButton exit = new JButton("Exit");
private JPanel pane=new JPanel();
private JLabel lbl ;
public BlackJackWindow1()
{
super();
JPanel pane=new JPanel();
setTitle ("Black Jack!!!!!") ;
JFrame frame = new JFrame("");
setVisible(true);
setSize (380, 260) ;
setLocation (450, 200) ;
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE) ;
setLayout(new FlowLayout());
play = new JButton("Start");
exit = new JButton("exit");
lbl = new JLabel ("Welcome to Theodores Black Jack!!!!!");
add (lbl) ;
add(play, BorderLayout.CENTER);
play.addActionListener (this);
add(exit,BorderLayout.CENTER);
exit.addActionListener (this);
}
#Override
public void actionPerformed(ActionEvent event)
{
// TODO Auto-generated method stub
BlackJackWindow2 bl = new BlackJackWindow2();
if (event.getSource() == play)
{
bl.BlackJackWindow2();
}
else if(event.getSource() == exit){
System.exit(0);
}
}
second window....
import javax.swing.* ;
import java.awt.event.* ;
import java.awt.* ;
import java.util.* ;
public class BlackJackWindow2 extends JFrame implements ActionListener
{
private JButton hit ;
private JButton stay ;
private JButton back;
//private JLabel lbl;
public void BlackJackWindow2()
{
// TODO Auto-generated method stub
JPanel pane=new JPanel();
setTitle ("Black Jack!!!!!") ;
JFrame frame = new JFrame("");
setVisible(true);
setSize (380, 260) ;
setLocation (450, 200) ;
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE) ;
setLayout(new FlowLayout());
hit = new JButton("Hit");
stay = new JButton("stay");
back = new JButton("return to main menu");
// add (lbl) ;
add(hit, BorderLayout.CENTER);
hit.addActionListener (this) ;
add(stay,BorderLayout.CENTER);
stay.addActionListener (this) ;
add(back,BorderLayout.CENTER);
back.addActionListener (this) ;
}
#Override
public void actionPerformed(ActionEvent event)
{
// TODO Auto-generated method stub
BlackJackWindow1 bl = new BlackJackWindow1();
if (event.getSource() == hit)
{
//code for the game goes here i will complete later
}
else if(event.getSource() == stay){
//code for game goes here i will comeplete later.
}
else
{
//this is where i want the frame to close and go back to the original.
}
}
}
The second frame needs a reference to the first frame so that it can set the focus back to the first frame.
Also your classes extend JFrame but they are also creating other frames in their constructors.
A couple of suggestions:
You're adding components to a JPanel that uses FlowLayout but are using BorderLayout constants when doing this which you shouldn't do as it doesn't make sense:
add(play, BorderLayout.CENTER);
Rather, if using FlowLayout, just add the components without those constants.
Also, rather than swap JFrames, you might want to consider using a CardLayout and swapping veiws in a single JFrame. For instance:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FooBarBazDriver {
private static final String INTRO = "intro";
private static final String GAME = "game";
private CardLayout cardlayout = new CardLayout();
private JPanel mainPanel = new JPanel(cardlayout);
private IntroPanel introPanel = new IntroPanel();
private GamePanel gamePanel = new GamePanel();
public FooBarBazDriver() {
mainPanel.add(introPanel.getMainComponent(), INTRO);
mainPanel.add(gamePanel.getMainComponent(), GAME);
introPanel.addBazBtnActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardlayout.show(mainPanel, GAME);
}
});
gamePanel.addBackBtnActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardlayout.show(mainPanel, INTRO);
}
});
}
private JComponent getMainComponent() {
return mainPanel;
}
private static void createAndShowUI() {
JFrame frame = new JFrame("Foo Bar Baz");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new FooBarBazDriver().getMainComponent());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
class IntroPanel {
private JPanel mainPanel = new JPanel();
private JButton baz = new JButton("Baz");
private JButton exit = new JButton("Exit");
public IntroPanel() {
mainPanel.setLayout(new FlowLayout());
baz = new JButton("Start");
exit = new JButton("exit");
mainPanel.add(new JLabel("Hello World"));
mainPanel.add(baz);
mainPanel.add(exit);
exit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Window win = SwingUtilities.getWindowAncestor(mainPanel);
win.dispose();
}
});
}
public void addBazBtnActionListener(ActionListener listener) {
baz.addActionListener(listener);
}
public JComponent getMainComponent() {
return mainPanel;
}
}
class GamePanel {
private static final Dimension MAIN_SIZE = new Dimension(400, 200);
private JPanel mainPanel = new JPanel();
private JButton foo;
private JButton bar;
private JButton back;
public GamePanel() {
foo = new JButton("Foo");
bar = new JButton("Bar");
back = new JButton("return to main menu");
mainPanel.add(foo);
mainPanel.add(bar);
mainPanel.add(back);
mainPanel.setPreferredSize(MAIN_SIZE);
}
public JComponent getMainComponent() {
return mainPanel;
}
public void addBackBtnActionListener(ActionListener listener) {
back.addActionListener(listener);
}
}
Since I had to test it myself if it is in fact so easy to implement, I built this simple example. It demonstrates a solution to your problem. Slightly inspired by #jzd's answer (+1 for that).
import java.awt.Color;
import java.awt.HeadlessException;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class FocusChangeTwoFrames
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createGUI();
}
});
}
private static void createGUI() throws HeadlessException
{
final JFrame f2 = new JFrame();
f2.getContentPane().setBackground(Color.GREEN);
final JFrame f1 = new JFrame();
f1.getContentPane().setBackground(Color.RED);
f1.setSize(400, 300);
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setVisible(true);
MouseListener ml = new MouseAdapter()
{
#Override
public void mousePressed(MouseEvent e)
{
if(f1.hasFocus())
f2.requestFocus();
else
f1.requestFocus();
}
};
f1.addMouseListener(ml);
f2.setSize(400, 300);
f2.setLocation(200, 150);
f2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f2.setVisible(true);
f2.addMouseListener(ml);
}
}
Enjoy, Boro.

Categories