Java switch between cards using jbutton - java

I'm using a cardlayout and I want to make it so that the first card has a button and when clicked it will take it to card 2 which has a button that will take it back to card 1. Here is my current code, and I've tried putting a few things in the actionPerformed method but I haven't had any success in getting it to work. Also, I receive a syntax error on "this" on the lines with button1.addActionListener(this); and button2.addActionListener(this); which I assume is because my actionPerformed method isn't setup correctly. Any help on getting the buttons setup would be greatly appreciated.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Main implements ItemListener {
JPanel cards;
public void addComponentToPane(Container pane) {
//create cards
JPanel card1 = new JPanel();
JPanel card2 = new JPanel();
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
button1.addActionListener(this);
button2.addActionListener(this);
card1.add(button1);
card2.add(button2);
//create panel that contains cards
cards = new JPanel(new CardLayout());
cards.add(card1);
cards.add(card2);
pane.add(cards, BorderLayout.CENTER);
}
public void itemStateChanged(ItemEvent evt) {
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, (String)evt.getItem());
}
public static void createAndShowGUI() {
//create and setup window
JFrame frame = new JFrame("Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//create and setup content pane
Main main = new Main();
main.addComponentToPane(frame.getContentPane());
//display window
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
}
public static void main(String[] args) {
//set look and feel
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
//turn off metal's bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
//schedule job for the event dispatch thread creating and showing GUI
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardTest implements ActionListener {
private JPanel cards;
private JButton button1;
private JButton button2;
public void addComponentToPane(Container pane) {
// create cards
JPanel card1 = new JPanel();
JPanel card2 = new JPanel();
button1 = new JButton("Button 1");
button2 = new JButton("Button 2");
button1.addActionListener(this);
button2.addActionListener(this);
card1.add(button1);
card2.add(button2);
// create panel that contains cards
cards = new JPanel(new CardLayout());
cards.add(card1, "Card 1");
cards.add(card2, "Card 2");
pane.add(cards, BorderLayout.CENTER);
}
public void itemStateChanged(ItemEvent evt) {
CardLayout cl = (CardLayout) (cards.getLayout());
cl.show(cards, (String) evt.getItem());
}
public static void createAndShowGUI() {
// create and setup window
JFrame frame = new JFrame("Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create and setup content pane
CardTest main = new CardTest();
main.addComponentToPane(frame.getContentPane());
// display window
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == button1) {
CardLayout cl = (CardLayout) (cards.getLayout());
cl.show(cards, "Card 2");
} else if (ae.getSource() == button2) {
CardLayout cl = (CardLayout) (cards.getLayout());
cl.show(cards, "Card 1");
}
}
public static void main(String[] args) {
// set look and feel
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
// turn off metal's bold fonts
UIManager.put("swing.boldMetal", Boolean.FALSE);
// schedule job for the event dispatch thread creating and showing GUI
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

Related

Moving from one frame to another

I am new to JAVA swing , where i develop two different JFrame if I click on button frame should move to another frame and previous frame should close by opening of next frame.
I click on button a next frame open but data inside frame is not displaying and previous frame is not closed on button . Please help to find the problem in code.
Frame 1:---------------------------------
package com.demo.test;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import com.demo.gui.TestjigWindow;
public class TestjigWindowCheck extends JFrame{
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
public TestjigWindowCheck() {
initUI();
}
private void initUI() {
mainFrame = new JFrame("Fuse Test jig");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(500,500);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
public void showEventDemo(){
//TestjigWindow frame1 = new TestjigWindow();
headerLabel.setText("Fuse Test Jig");
headerLabel.setFont(new Font( "Arial", Font.BOLD, 25));
headerLabel.setBackground(Color.green);
JButton startButton = new JButton("Start");
startButton.setActionCommand("Start");
JButton closeButton = new JButton("Close");
closeButton.setActionCommand("close");
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try
{
if(e.getSource() == startButton)
{
TestjigWindow2 frame2 = new TestjigWindow2();
frame2.setVisible(true);
dispose();
}
else if(e.getSource() == closeButton)
{
System.exit(0);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
closeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try
{
System.exit(0);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
controlPanel.add(startButton);
controlPanel.add(closeButton);
mainFrame.setVisible(true);
}
public static void main(String[] args) {
TestjigWindowCheck test = new TestjigWindowCheck();
test.showEventDemo();
//test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Frame 2----------------------------------- .
package com.demo.test;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class TestjigWindow2 extends JFrame{
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
private JPanel controlPanel1;
public TestjigWindow2()
{
prepareGUI();
}
public static void main(String args[])
{
TestjigWindow2 test = new TestjigWindow2();
test.showRadioButton();
}
private void prepareGUI()
{
mainFrame = new JFrame("Fuse Test2 jig");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
headerLabel = new JLabel("", JLabel.CENTER);
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(500,500);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
public void showRadioButton()
{
headerLabel.setText("Fuse Mode");
final JRadioButton setting =new JRadioButton("Setting");
final JRadioButton testing =new JRadioButton("Testing");
setting.setBounds(75,50,100,30);
testing.setBounds(75,100,100,30);
setting.setMnemonic(KeyEvent.VK_S);
testing.setMnemonic(KeyEvent.VK_T);
ButtonGroup group = new ButtonGroup();
group.add(setting);
group.add(testing);
controlPanel.add(setting);
controlPanel.add(testing);
JButton button = new JButton("Next");
button.setActionCommand("Next");
controlPanel.add(button);
mainFrame.setVisible(true);
}
}
For this problem, I think it's a fairly simple solution, as Andrew commented, you don't need to keep creating JFrames, you can create your JFrame in your first program, and pass it to your second class through the constructor.
Why I think your program is closing is because you are calling dispose() after creating the new frame which might be destroying the components in your new frame.
You could take this approach, which uses only one frame creating in the opening class and carried over to the second class
For Example (using snipplets of your code):
Frame 1
//This is where you are moving to the second frame.
if(e.getSource() == startButton)
{
mainFrame.getContentPane().removeAll(); //removeAll() method wipes all components attached to the contentpane of the frame
//Frame can be reused when passed to second class
TestjigWindow2 frame2 = new TestjigWindow2(this.mainFrame);
}
Frame 2
//In your constructor you could have something like this
private JFrame mainFrame;
/*
* Other variables and constants go here
*
*/
public TestjigWindow2(JFrame mainFrame)
{
this.mainFrame = mainFrame;
prepareGUI();
}
And then in prepareGUI(), you would then be adding your components to your frame, without creating a new frame. With this, your first page will be closed, and the second frame will be open, without you having to creating mutiple JFrames.
You should just create a new Instance of TestjigWindow2 in the actionPerformed method within your first frame. Instead of adding actionPerformed on the startbutton and stopbutton seperately, implement ActionListener interface in your Frame1 class and just keep one method since you are checking for the source inside the method anyways.
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try
{
if(e.getSource() == startButton)
{
TestjigWindow2 frame2 = new TestjigWindow2();
//frame2.setVisible(true); do this inside the frame2 preparegui method
dispose();
}
else if(e.getSource() == closeButton)
{
System.exit(0);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
Also the code will have a more generalized flow if you have the main method inside Frame1 and instantiate the Frame1 in it.
And you don't need to use setVisible inside the actionPerformed of Frame1.

switch to an animation image in cardlayout

I want to create a login dialog. when user press login button it will show a animation image. with some search I find that use cardlayout can switch to another panel so I chose cardlayout for my login dialog. but when a switch to a panel contain a jlabel that have animation image jlabel just load text
here is my code:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author 20133_000
*/
public class Draft9 {
public static void main(String[] args) {
TestCardLayout test = new TestCardLayout();
}
}
class TestCardLayout extends JFrame {
private JPanel mainPanel;
private CardPanel panel1;
private JPanel panel2;
private CardLayout layout;
public TestCardLayout() {
mainPanel = new JPanel();
panel1 = new CardPanel();
panel2 = new JPanel();
layout = new CardLayout();
panel1.add(new JButton("here is panel 1"));
JLabel jLabel1 = new javax.swing.JLabel("here is panel 2",new javax.swing.ImageIcon( "E:\\programming\\programming java\\Netbean Projectr\\Project1\\src\\images\\loading3.gif") , JLabel.CENTER);
jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
//jLabel1.setIcon(new javax.swing.ImageIcon("/images/loading3.gif")); // NOI18N
// jLabel1.setIcon(new javax.swing.ImageIcon("E:\\programming\\programming java\\Netbean Projectr\\Project1\\src\\images\\loading3.gif"));
panel2.add(new JButton("here is panel 2"), BorderLayout.NORTH);
panel2.add(jLabel1, BorderLayout.CENTER);
mainPanel.setLayout(layout);
mainPanel.add("panel1", panel1);
mainPanel.add("panel2", panel2);
add(mainPanel, BorderLayout.CENTER);
setSize(400, 450);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
//layout.show(mainPanel, "panel2");
}
}
class CardPanel extends JPanel {
JButton btnChangePanel;
public CardPanel() {
btnChangePanel = new JButton("show panel 2");
btnChangePanel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
showPanel2();
calculateData();
}
});
add(btnChangePanel);
}
public void showPanel2() {
JPanel parentPanel = (JPanel) getParent();
CardLayout layout = (CardLayout) parentPanel.getLayout();
layout.show(parentPanel, "panel2");
}
public void showPanel1() {
JPanel parentPanel = (JPanel) getParent();
CardLayout layout = (CardLayout) parentPanel.getLayout();
layout.show(parentPanel, "panel1");
}
public void calculateData() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
System.out.println("calculating data...");
//doing some calculate here
Thread.sleep(3000);
System.out.println("done calculting");
//System.exit(0);
int res = 1;
if (res == 1) {
System.out.print("login ok");
showPanel2();
} else {
System.out.print("login failed");
showPanel1();
}
} catch (Exception ex) {
Logger.getLogger(CardPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
}
when i leave Thread.sleep(3000); comment it work but when i uncomment that line it doesn't work. How can i fix it ?
It's because your image is animated (would work with a normal one) and your Thread.sleep(3000) freezes the whole frame, note that you also can't click the button (or move frame). You could start a new thread to solve this:
public void calculateData() {
new Thread(new Runnable() {
public void run() {
try {
System.out.println("calculating data...");
// doing some calculate here
Thread.sleep(3000);
System.out.println("done calculting");
// System.exit(0);
int res = 1;
if (res == 1) {
System.out.print("login ok");
showPanel2();
} else {
System.out.print("login failed");
showPanel1();
}
} catch (Exception ex) {
Logger.getLogger(CardPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
}).start();
}

ActionEvent "Cannot Find Symbol"

I am making a program to wrap text, by words or by characters, depending on user input. I have everything working, except for my ActionEvent that's giving me a "Cannot Find Symbol" error. I'm sure it's something small that I've missed, but I can't seem to find it:
import javax.swing.*;
import java.awt.*;
import javax.swing.border.*;
public class JTextWrap extends JFrame
{
JScrollPane scroll = new JScrollPane();
JPanel panel = new JPanel();
JTextArea jta = new JTextArea();
TitledBorder tb;
JRadioButton jrb = new JRadioButton();
JRadioButton jrb2 = new JRadioButton();
ButtonGroup btg = new ButtonGroup();
JCheckBox jdb = new JCheckBox();
public JTextWrap()
{
tb = new TitledBorder("");
setSize(new Dimension(400, 300));
jta.setText("jTextArea1");
panel.setBorder(tb);
tb.setTitle("Wrap Options");
jrb.setText("Wrap Words");
jrb.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e) {
JTextWrap.jrb_actionPerformed(e);
}
});
jrb2.setText("Wrap Characters");
jrb2.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e) {
JTextWrap.jrb2_actionPerformed(e);
}
});
jdb.setText("Wrap");
jdb.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e) {
JTextWrap.jdb_actionPerformed(e);
}
});
add(scroll, "Center");
scroll.getViewport().add(jta, null);
add(panel, "South");
panel.add(jdb, null);
panel.add(jrb, null);
panel.add(jrb2, null);
btg.add(jrb);
btg.add(jrb2);
}
public static void main(String[] args)
{
JTextWrap frame = new JTextWrap();
frame.setTitle("JTextWrap");
frame.setDefaultCloseOperation(3);
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
void jdb_actionPerformed(ActionEvent e) {
jta.setLineWrap(jdb.isSelected());
if (jdb.isSelected()) {
jrb.setEnabled(true);
jrb2.setEnabled(true);
}
else {
jrb.setEnabled(false);
jrb2.setEnabled(false);
}
}
void jrb_actionPerformed(ActionEvent e) {
jta.setWrapStyleWord(jrb.isSelected());
jta.revalidate();
}
void jrb2_actionPerformed(ActionEvent e) {
jta.setWrapStyleWord(!jrb2.isSelected());
jta.revalidate();
}
}
ActionEvent class is in java.awt.event package and you have not imported this package.

How to override windowsClosing event in JFrame

i'm developing a JFrame which has a button to show another JFrame. On the second JFrame i want to override WindowsClosing event to hide this frame but not close all the application. So i do like this:
On second JFrame
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
private void formWindowClosing(java.awt.event.WindowEvent evt) {
this.dispose();
}
but application still close when i click x button on the windows. why? can you help me?
I can't use
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
because i need to show again that JFrame with some information added in it during operations from first JFrame. So i init second JFrame with attribute visible false. if i use dispose i lose the information added in a second moment by the other JFrame. so i use
private void formWindowClosing(java.awt.event.WindowEvent evt) {
this.setVisible(false);
}
but it still continue to terminate my entire app.
don't create a new JFrame, for new container use JDialog, if you want to hide the JFrame then better would be override proper e.g DefaultCloseOperations(JFrame.HIDE_ON_CLOSE), method JFrame.EXIT_ON_CLOSE teminating current JVM instance simlair as calll for System.exit(int)
EDIT
but it still continue to terminate my entire app.
1) then there must be another issue, your code maybe call another JFrame or formWindowClosing <> WindowClosing, use implemented method from API
public void windowClosing(WindowEvent e) {
2) I'b preferred DefaultCloseOperations(JFrame.HIDE_ON_CLOSE),
3) use JDialog instead of JFrame
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ClosingFrame extends JFrame {
private JMenuBar MenuBar = new JMenuBar();
private static JFrame frame = new JFrame();
private static JFrame frame1 = new JFrame("DefaultCloseOperation(JFrame.HIDE_ON_CLOSE)");
private static final long serialVersionUID = 1L;
private JMenu File = new JMenu("File");
private JMenuItem Exit = new JMenuItem("Exit");
public ClosingFrame() {
File.add(Exit);
MenuBar.add(File);
Exit.addActionListener(new ExitListener());
WindowListener exitListener = new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
frame.setVisible(false);
/*int confirm = JOptionPane.showOptionDialog(frame,
"Are You Sure to Close this Application?",
"Exit Confirmation", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
if (confirm == JOptionPane.YES_OPTION) {
System.exit(1);
}*/
}
};
JButton btn = new JButton("Show second JFrame");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame1.setVisible(true);
}
});
frame.add(btn, BorderLayout.SOUTH);
frame.addWindowListener(exitListener);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setJMenuBar(MenuBar);
frame.setPreferredSize(new Dimension(400, 300));
frame.setLocation(100, 100);
frame.pack();
frame.setVisible(true);
}
private class ExitListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
int confirm = JOptionPane.showOptionDialog(frame,
"Are You Sure to Close this Application?",
"Exit Confirmation", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
if (confirm == JOptionPane.YES_OPTION) {
System.exit(1);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ClosingFrame cf = new ClosingFrame();
JButton btn = new JButton("Show first JFrame");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(true);
}
});
frame1.add(btn, BorderLayout.SOUTH);
frame1.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame1.setPreferredSize(new Dimension(400, 300));
frame1.setLocation(100, 400);
frame1.pack();
frame1.setVisible(true);
}
});
}
}
Adding a New Code with no WindowListener part as explained by #JBNizet, the very right thing. The default behaviour just hides the window, nothing is lost, you simply have to bring it back, every value inside it will remain as is, below is the sample program for further help :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TwoFrames
{
private SecondFrame secondFrame;
private int count = 0;
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("JFRAME 1");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
secondFrame = new SecondFrame();
secondFrame.createAndDisplayGUI();
secondFrame.tfield.setText("I will be same everytime.");
JPanel contentPane = new JPanel();
JButton showButton = new JButton("SHOW JFRAME 2");
showButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
secondFrame.tfield.setText(secondFrame.tfield.getText() + count);
count++;
if (!(secondFrame.isShowing()))
secondFrame.setVisible(true);
}
});
frame.add(contentPane, BorderLayout.CENTER);
frame.add(showButton, BorderLayout.PAGE_END);
frame.setSize(200, 200);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TwoFrames().createAndDisplayGUI();
}
});
}
}
class SecondFrame extends JFrame
{
private WindowAdapter windowAdapter;
public JTextField tfield;
public void createAndDisplayGUI()
{
setLocationByPlatform(true);
JPanel contentPane = new JPanel();
tfield = new JTextField(10);
addWindowListener(windowAdapter);
contentPane.add(tfield);
getContentPane().add(contentPane);
setSize(300, 300);
}
}
Is this what you want, try this code :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TwoFrames
{
private SecondFrame secondFrame;
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("JFRAME 1");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
secondFrame = new SecondFrame();
secondFrame.createAndDisplayGUI();
secondFrame.tfield.setText("I will be same everytime.");
JPanel contentPane = new JPanel();
JButton showButton = new JButton("SHOW JFRAME 2");
showButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (!(secondFrame.isShowing()))
secondFrame.setVisible(true);
}
});
frame.add(contentPane, BorderLayout.CENTER);
frame.add(showButton, BorderLayout.PAGE_END);
frame.setSize(200, 200);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TwoFrames().createAndDisplayGUI();
}
});
}
}
class SecondFrame extends JFrame
{
private WindowAdapter windowAdapter;
public JTextField tfield;
public void createAndDisplayGUI()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
JPanel contentPane = new JPanel();
tfield = new JTextField(10);
windowAdapter = new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
}
};
addWindowListener(windowAdapter);
contentPane.add(tfield);
getContentPane().add(contentPane);
setSize(300, 300);
}
}
You could avoid the listener completely and use
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
Note that the default value is HIDE_ON_CLOSE, so the behavior you want should be the default behavior. Maybe you registered another listener that exits the application.
See http://docs.oracle.com/javase/6/docs/api/javax/swing/JFrame.html#setDefaultCloseOperation%28int%29
It's hard to pinpoint exactly why you are experiencing the behavior stated without seeing a little more of the set-up code, however it may be due to defaultCloseOperation set to EXIT_ON_CLOSE.
Here's a link to a demo displaying the properties you are looking for although the structure is a bit different. Have a look: http://docs.oracle.com/javase/tutorial/uiswing/examples/components/FrameworkProject/src/components/Framework.java

Changing the active "card" in a Java card layout, from another class

I'm trying to build a small inventory application in Java, that switches views (or pages) based on the card layout. For the standard change the user will use the menu at the top of the app, and that works fine.
But, one one of my screens the user will enter an item ID number to check. If that ID number is not found in the database, the app should switch to the New Item page. This is where I'm at a loss. I've tried to change the currently viewed card but nothing seems to be getting it.
Forgive me if this is a basic question (as well as poorly written Java :) ), I'm teaching myself Java as I write this app. Attached I'm adding part of the main class (InventoryTrackingSystem) and the GUI class (the one that is trying to change the view).
/***** The MAIN class **********/
package inventorytrackingsystem;
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.rmi.*;
public class InventoryTrackingSystem implements ItemListener {
JPanel mainPanel;
JFrame frame;
JPanel cards = new JPanel(new CardLayout());; //a panel that uses CardLayout
final static String MAINPANEL = "Main";
final static String CHECKITEMSPANEL = "Check Items";
final static String NEWITEMPANEL = "New Item";
final static String CHECKOUTITEMPANEL = "Check Out Item";
final static String ITEMINFOPANEL = "Item Information";
final static String LISTALLITEMSPANEL = "List All Items";
JPanel comboBoxPane;
private JComboBox cb;
static String comboBoxItems[] = {MAINPANEL,CHECKITEMSPANEL,NEWITEMPANEL,CHECKOUTITEMPANEL,ITEMINFOPANEL,LISTALLITEMSPANEL};
public static void main(String[] args) {
InventoryTrackingSystem ITS = new InventoryTrackingSystem();
/* Use an appropriate Look and Feel */
try {
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
} catch (IllegalAccessException ex) {
ex.printStackTrace();
} catch (InstantiationException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
/* Turn off metal's use of bold fonts */
UIManager.put("swing.boldMetal", Boolean.FALSE);
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
// javax.swing.SwingUtilities.invokeLater(new Runnable() {
// public void run() {
ITS.createAndShowGUI();
// }
// });
}
public void addComponentToPane(Container pane){
//Put the JComboBox in a JPanel to get a nicer look.
comboBoxPane = new JPanel(); //use FlowLayout
cb = new JComboBox(comboBoxItems);
cb.setEditable(false);
cb.addItemListener(this);
comboBoxPane.add(cb);
cb.setVisible(false);
//Create the "cards".
JPanel main = new guiBuilder().buildGui("main");
JPanel checkItems = new guiBuilder().buildGui("checkItems");
JPanel newItems = new guiBuilder().buildGui("newItems");
JPanel checkOutItems = new guiBuilder().buildGui("checkOutItems");
JPanel itemInfo = new guiBuilder().buildGui("itemInfo");
JPanel listAllItems = new guiBuilder().buildGui("listAllItems");
//Create the panel that contains the "cards".
cards = new JPanel(new CardLayout());
cards.add(main, MAINPANEL);
cards.add(checkItems, CHECKITEMSPANEL);
cards.add(newItems, NEWITEMPANEL);
cards.add(checkOutItems, CHECKOUTITEMPANEL);
cards.add(itemInfo, ITEMINFOPANEL);
cards.add(listAllItems, LISTALLITEMSPANEL);
pane.add(comboBoxPane, BorderLayout.PAGE_START);
pane.add(cards, BorderLayout.CENTER);
}
public void itemStateChanged(ItemEvent evt) {
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, (String)evt.getItem());
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event dispatch thread.
*/
private void createAndShowGUI() {
//Create and set up the window.
frame = new JFrame("Inventory Tracking System");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
Menu m1 = new Menu("Options");
MenuItem mi1_0 = new MenuItem("Main Page");
mi1_0.setActionCommand("main");
mi1_0.addActionListener(new menuListener());
MenuItem mi1_1 = new MenuItem("Check Item");
mi1_1.setActionCommand("checkItem");
mi1_1.addActionListener(new menuListener());
MenuItem mi1_2 = new MenuItem("Add New Item");
mi1_2.setActionCommand("addItem");
mi1_2.addActionListener(new menuListener());
MenuItem mi1_3 = new MenuItem("List All Items");
mi1_3.setActionCommand("listAllItems");
mi1_3.addActionListener(new menuListener());
MenuItem mi1_4 = new MenuItem("Check Out Item");
mi1_4.setActionCommand("checkOutItem");
mi1_4.addActionListener(new menuListener());
MenuItem mi1_5 = new MenuItem("Exit");
mi1_5.setActionCommand("exit");
mi1_5.addActionListener(new menuListener());
Menu m2 = new Menu("Help");
MenuItem mi2_0 = new MenuItem("About");
mi2_0.setActionCommand("about");
mi2_0.addActionListener(new menuListener());
m1.add(mi1_0);
m1.add(mi1_1);
m1.add(mi1_2);
m1.add(mi1_3);
m1.add(mi1_4);
m1.add(mi1_5);
m2.add(mi2_0);
MenuBar mb = new MenuBar();
frame.setMenuBar(mb);
mb.add(m1);
mb.add(m2);
//Create and set up the content pane.
//InventoryTrackingSystem setGUI = new InventoryTrackingSystem();
addComponentToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
frame.setSize(780, 830);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
public void windowClosed(WindowEvent we){
System.exit(0);
}
});
}
class menuListener implements ActionListener{
public void actionPerformed(ActionEvent ev){
String thisAction=ev.getActionCommand();
if(thisAction.equals("main")){
cb.setSelectedItem(MAINPANEL);
}else if(thisAction.equals("checkItem")){
//change GUI
cb.setSelectedItem(CHECKITEMSPANEL);
}else if(thisAction.equals("addItem")){
//change GUI
cb.setSelectedItem(NEWITEMPANEL);
}else if(thisAction.equals("checkOutItem")){
//change GUI
cb.setSelectedItem(CHECKOUTITEMPANEL);
}else if(thisAction.equals("listAllItems")){
//change GUI
cb.setSelectedItem(LISTALLITEMSPANEL);
}else if(thisAction.equals("exit")){
System.exit(0);
}else if(thisAction.equals("about")){
JOptionPane.showMessageDialog(frame, "About This App");
}
}
}
public void swapView(String s){
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, s);
}
}
/***** The GUI class **********/
package inventorytrackingsystem;
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Image.*;
import java.awt.image.BufferedImage.*;
import javax.imageio.*;
import com.sun.jimi.core.*;
public class guiBuilder {
JLabel itemIdLabel;
JTextField itemID;
JButton checkIt;
JButton getSignature;
mySqlStuff sql=new mySqlStuff();
public JPanel buildGui(String guiType){
JPanel thisGUI;
if(guiType.equals("main")){
thisGUI=mainGUI();
}else if(guiType.equals("checkItems")){
thisGUI=checkItemsGUI();
}else if(guiType.equals("newItems")){
thisGUI=newItemsGUI();
}else if(guiType.equals("checkOutItems")){
thisGUI=checkOutItemsGUI();
}else if(guiType.equals("itemInfo")){
thisGUI=itemInfoGUI();
}else if(guiType.equals("listAllItems")){
thisGUI=listAllItemsGUI();
}else{
thisGUI=mainGUI();
}
return thisGUI;
} /* close buildGui() Method */
private JPanel mainGUI(){
JPanel thisPanel = new JPanel();
return thisPanel;
}
private JPanel checkItemsGUI(){
JPanel thisPanel = new JPanel();
JPanel itemSection=new JPanel();
JPanel exitSection=new JPanel();
itemIdLabel=new JLabel("Enter/Scan Item ID");
itemID=new JTextField(4);
itemID.addKeyListener(new myItemIdListener());
checkIt=new JButton("Check Item");
checkIt.addActionListener(new myItemCheckListener());
itemSection.add(itemIdLabel);
itemSection.add(itemID);
itemSection.add(checkIt);
JButton exitButton=new JButton("Exit");
exitButton.addActionListener(new exitButtonListener());
exitSection.add(exitButton);
thisPanel.add(itemSection);
thisPanel.add(exitSection);
return thisPanel;
}
private JPanel newItemsGUI(){
JPanel thisPanel = new JPanel();
return thisPanel;
}
private JPanel checkOutItemsGUI(){
JPanel thisPanel = new JPanel();
return thisPanel;
}
private JPanel itemInfoGUI(){
JPanel thisPanel = new JPanel();
return thisPanel;
}
private JPanel listAllItemsGUI(){
JPanel thisPanel = new JPanel();
return thisPanel;
}
class myItemIdListener implements KeyListener{
boolean keyGood=false;
public void keyPressed(KeyEvent keyEvent){
int keyCode=keyEvent.getKeyCode();
if((keyCode>=48 && keyCode<=57) || (keyCode>=96 && keyCode<=105)){
keyGood=true;
}
}
public void keyReleased(KeyEvent keyEvent){
int keyCode=keyEvent.getKeyCode();
if((keyCode>=48 && keyCode<=57) || (keyCode>=96 && keyCode<=105)){
printIt("Released",keyEvent);
}else if(keyCode==10){
checkIt.doClick();
}
}
public void keyTyped(KeyEvent keyEvent){
int keyCode=keyEvent.getKeyCode();
if((keyCode>=48 && keyCode<=57) || (keyCode>=96 && keyCode<=105)){
printIt("Typed",keyEvent);
}
}
private void printIt(String title,KeyEvent keyEvent){
int keyCode=keyEvent.getKeyCode();
String keyText=KeyEvent.getKeyText(keyCode);
String currentData;
if(title.equals("Pressed")){
keyGood=true;
}else if(title.equals("Released")){
System.out.println(title+ " -> "+keyCode+" / "+keyText);
}else if(title.equals("Typed")){
System.out.println(title+ " -> "+keyCode+" / "+keyText);
}
try{
String text=itemID.getText();
if(text.length()==4){
checkIt.doClick();
}else{
System.out.println("currentlLength: "+itemID.getText().length());
}
}catch(Exception ex){
ex.printStackTrace();
}
}
}
/**** THIS IS WHERE THE SWAP VIEW IS CALLED ****/
class myItemCheckListener implements ActionListener{
public void actionPerformed(ActionEvent ev){
String itemNum=itemID.getText();
itemID.setText("");
System.out.println("Checking ID#: "+itemNum);
ArrayList checkData=new ArrayList(sql.checkInventoryData(itemNum));
if(checkData.get(0).toString().equals("[NULL]")){
System.out.println("New Item -> "+checkData.get(0).toString());
InventoryTrackingSystem ITS = new InventoryTrackingSystem();
ITS.swapView("NEWITEMPANEL");
}else{
System.out.println("Item Exists -> "+checkData.get(0).toString());
}
System.out.println(checkData);
}
}
class signaturePadButtonListener implements ActionListener{
public void actionPerformed(ActionEvent ev){
signaturePadStuff signature = new signaturePadStuff();
while(signature.imageFileMoved==false){
// wait for the signature to be collected and the image moved to the server.
}
System.out.println(signature.newFileName);
}
}
class exitButtonListener implements ActionListener{
public void actionPerformed(ActionEvent ev){
System.exit(0);
}
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected ImageIcon createImageIcon(String path, String description) {
java.net.URL imgURL = getClass().getResource(path);
if(imgURL != null){
return new ImageIcon(imgURL, description);
}else{
System.err.println("Couldn't find file: " + path);
return null;
}
}
class submitItemButtonListener implements ActionListener{
public void actionPerformed(ActionEvent ev){
String errorMsg = "";
String[] formResults = new String[25];
}
}
class clearFormButtonListener implements ActionListener{
public void actionPerformed(ActionEvent ev){
return;
}
}
}
With this code in your actionPerformed method...
InventoryTrackingSystem ITS = new InventoryTrackingSystem();
ITS.swapView("NEWITEMPANEL");
...you are calling swapView on a new instance of InventoryTrackingSystem (which is not the one you created in main and for which the UI is showing on the screen).
-edited-
you need an instance of InventoryTrackingSystem in your action listener
you can for example store it in a member variable of myItemCheckListener like this:
class myItemCheckListener implements ActionListener{
private InventoryTrackingSystem its;
// constructor takes its instance as argument
public myItemCheckListener(InventoryTrackingSystem its){
// ...assigns it to the member variable
this.its = its;
}
public void actionPerformed(ActionEvent ev){
// call swapView on the correct instance of InventoryTrackingSystem
its.swapView()
}
}
Of course, since your action listener is created in guiBuilder.buildGui() / checkItemsGUI() you will need the ITS instance there, too.
BTW:
It is not really necessary to create new guiBuilder instances like this:
JPanel main = new guiBuilder().buildGui("main");
...
JPanel listAllItems = new guiBuilder().buildGui("listAllItems");
instead you could:
guiBuilder builder = new guiBuilder();
builder.buildGui("main");
builder.build("whatever");

Categories