Get Parent Frame object from JPanel object - java

Is it possible to get the parent JFrame object from JPanel class??
Actually I am trying to make a GUI using NetBeans.The GUI has a Frame and Two panels.
1) Login Panel (having two text field and button)
2) Second Panel
When JFrame loaded, I add LoginPanel in it initially.
public ParentJFrame() { //in constructor
initComponents();
this.setLayout(new BorderLayout());
this.setBounds(300,300, 300, 300);
this.getContentPane().add(new LoginPanel());
}
After click on button (of LoginPanel) , I am trying to remove LoginPanel from JFrame and adding SecondPanel.
Now I am removing LoginPanel and adding SecondPanel in LoginPanel class where I can access the username , password fields but here I am unable to get the JFrame object from which I have to remove this component.
If I try this in ParentJFrameClass then it is not possible for me to access username , password field's value. (As this is the structure provided by netbeans)
So what Should I do now? What would be the solution in this caseI hope I have explained the problem in detail but in case if anything is not clear please let me know
Experts Please help

To use cardlayout to change between the panels,like follwing code may help you,you need to modify it to meet your need:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
* replace the real panel of yours
* do the right process
*/
public class CardLayoutLoginDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
JFrame frame = new LoginFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class LoginFrame extends JFrame {
public LoginFrame() {
super("CardLayout Demo");
//Create the panel that contains the "cards".
mainPanel = new JPanel(new CardLayout());
mainPanel.add(getFirstPanel(), FIRST);
mainPanel.add(getSecondPanel(), SECOND);
this.setContentPane(mainPanel);
this.pack();
}
//use your first panel
private JPanel getFirstPanel() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3,2));
panel.add(new JLabel("Username: "));
panel.add(new JTextField(10));
panel.add(new JLabel("password: "));
panel.add(new JTextField(10));
JButton btnLogin = new JButton("Login");
JButton btnCancel = new JButton("Cancel");
btnLogin.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
CardLayout cl = (CardLayout)(mainPanel.getLayout());
cl.show(mainPanel, SECOND);
}
});
btnCancel.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
});
panel.add(btnLogin);
panel.add(btnCancel);
return panel;
}
//use the second panel
private JPanel getSecondPanel() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(2,2));
panel.add(new JLabel("Second panel"));
panel.add(new JLabel("other processs"));
JButton btnOther = new JButton("Ok");
JButton btnBack = new JButton("Back");
panel.add(btnOther);
panel.add(btnBack);
btnBack.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
CardLayout cl = (CardLayout)(mainPanel.getLayout());
cl.show(mainPanel, FIRST);
}
});
return panel;
}
private final String FIRST = "First panel";
private final String SECOND = "Second panel";
private static final long serialVersionUID = 1L;
private JPanel mainPanel;
}

Related

Creating a window - but buttons layout error

I made a small program with two buttons. I label
the buttons one exiting the program and the second importing files.
I actually let them both to exit the program when ever someone pressed on it
the problem is the buttons taking all the window, why?
I tried GridBagConstraints to resize the buttons some how but no luck anyway here's the full class without imports..
public class Window2 extends JFrame{
private static final long serialVersionUID = 1L;
public Window2(){
super ("ALANAZ imagtor");
setSize(600,400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel pnl1 = new JPanel(new GridLayout());
JPanel pnl2 = new JPanel();
//button
JButton butn1 = new JButton("EXIT");
JButton butn2 =new JButton("IMPORT");
butn1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JOptionPane.showMessageDialog(null, "exiting ... bye...");
System.exit(0);
}
});
butn2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
JOptionPane.showMessageDialog(null, "can't import now exiting");
System.exit(0);
}
});
GridBagConstraints gb1 = new GridBagConstraints();
gb1.insets = new Insets(15,15,15,15);
//Jlabel
JLabel lbl1 = new JLabel("exit or import an image");
pnl1.add(butn1);
pnl1.add(butn2);
pnl2.add(lbl1);
add(pnl2, BorderLayout.SOUTH);
add(pnl1, BorderLayout.CENTER);
}}
You are misusing your layout managers. Your pnl1 JPanel uses GridLayout (without any row or column constants?!), and if you only add one component to it, it will take up the entire JPanel. You seem to have GridBagConstraints in your code, but no GridBagLayout, which is confusing to me.
The solution is to read up on and understand how to use layout managers. Please have a look at the tutorial link: Laying Out Components Within a Container.
Key is to keep remembering that you can nest JPanels within JPanels. For example:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;
public class Window2 extends JFrame {
private static final long serialVersionUID = 1L;
private static final int PREF_W = 600;
private static final int PREF_H = 400;
public Window2() {
super("ALANAZ imagtor");
setDefaultCloseOperation(EXIT_ON_CLOSE);
int gap = 3;
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, gap, 0));
buttonPanel.setBorder(BorderFactory.createEmptyBorder(gap, gap, gap, gap));
JPanel pnl2 = new JPanel();
JButton butn1 = new JButton("EXIT");
JButton butn2 = new JButton("IMPORT");
butn1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "exiting ... bye...");
System.exit(0);
}
});
butn2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JOptionPane.showMessageDialog(null, "can't import now exiting");
System.exit(0);
}
});
JLabel lbl1 = new JLabel("exit or import an image");
buttonPanel.add(butn1);
buttonPanel.add(butn2);
JPanel centerPanel = new JPanel(new BorderLayout());
centerPanel.add(buttonPanel, BorderLayout.SOUTH);
pnl2.add(lbl1);
add(pnl2, BorderLayout.SOUTH);
add(centerPanel, BorderLayout.CENTER);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
public static void main(String[] args) {
Window2 win2 = new Window2();
win2.pack();
win2.setLocationRelativeTo(null);
win2.setVisible(true);
}
}
If you initialize your panel with a BorderLayout instead, and add your buttons using EAST, NORTH, WEST, SOUTH, you will have a quick fix - however I do also recommend reading up on layout managers
JPanel pnl1 = new JPanel(new BorderLayout());
pnl1.add(new JButton(), BorderLayout.SOUTH);

get set Text from one JFrame to another pop up JFrame with a textArea

I need to take all the textField, comboBox, jlst, and jslider input from the first frame and make it into a summary in the second frame after the Submit button is picked. I can't figure out the best way to do this. My assignment requires a popup second frame with a textArea and exit button that brings you back to the first frame.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Hashtable;
public class Ch10Asg extends JFrame
{
private String[] flightNames = {"342", "4324", "939", "104", "222"};
private String[] cardTypes ={"Mastercard", "Visa", "American Express", "Discover"};
private String[] Dates ={"8/1/2013", "8/2/2013", "8/3/2013", "8/4/2013", "8/5/2013"};
private JTextField jtfFirst = new JTextField(10);
private JTextField jtfLast = new JTextField(10);
private JTextField jtfAddress = new JTextField(15);
private JTextField jtfCity = new JTextField(15);
private JTextField jtfState = new JTextField(2);
private JTextField jtfZip = new JTextField(5);
private JTextField jtfCard = new JTextField(16);
private JComboBox jcbo = new JComboBox(flightNames);
private JComboBox jcbcctype = new JComboBox(cardTypes);
private JList jlst = new JList(Dates);
private JSlider jsldHort = new JSlider(JSlider.HORIZONTAL,0,4,0);
private JButton jbtExit = new JButton ("EXIT");
private JButton jbtClear = new JButton ("CLEAR");
private JButton jbtSubmit = new JButton ("SUBMIT");
private JTextField jtfStart = new JTextField();
private JTextField jtfEnd = new JTextField();
public Ch10Asg()
{
JPanel p1 = new JPanel(new GridLayout(3,1));
p1.add(new JLabel("First Name"));
p1.add(jtfFirst);
p1.add(new JLabel("Last Name"));
p1.add(jtfLast);
p1.add(new JLabel("Address"));
p1.add(jtfAddress);
p1.add(new JLabel("City"));
p1.add(jtfCity);
p1.add(new JLabel("State"));
p1.add(jtfState);
p1.add(new JLabel("ZIP"));
p1.add(jtfZip);
JPanel p2 = new JPanel(new GridLayout(3,1));
p2.add(new JLabel("Select Flight Number"));
p2.add(jcbo);
p2.add(new JLabel("Select Date"));
p2.add(jlst);
p2.add(new JLabel("Select Time"));
jsldHort.setMajorTickSpacing(1);
jsldHort.setPaintTicks(true);
Hashtable<Integer, JLabel> labels = new Hashtable<Integer, JLabel>();
labels.put(0, new JLabel("4:00am"));
labels.put(1, new JLabel("5:00am"));
labels.put(2, new JLabel("8:00am"));
labels.put(3, new JLabel("11:00am"));
labels.put(4, new JLabel("5:00pm"));
jsldHort.setLabelTable(labels);
jsldHort.setPaintLabels(true);
p2.add(jsldHort);
JPanel p4 = new JPanel(new GridLayout(3,1));
p4.add(new JLabel("Starting City"));
p4.add(jtfStart);
p4.add(new JLabel("Ending City"));
p4.add(jtfEnd);
p4.add(new JLabel("Select Card Type"));
p4.add(jcbcctype);
p4.add(new JLabel("Enter Number"));
p4.add(jtfCard);
p4.add(jbtExit);
p4.add(jbtClear);
p4.add(jbtSubmit);
add(p1, BorderLayout.NORTH);
add(p2, BorderLayout.CENTER);
add(p4, BorderLayout.SOUTH);
jbtExit.addActionListener(new ActionListener()
{#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
System.exit(0);
}});
jbtClear.addActionListener(new ActionListener()
{#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
jtfFirst.setText("");
jtfLast.setText("");
jtfAddress.setText("");
jtfCity.setText("");
jtfState.setText("");
jtfZip.setText("");
jtfCard.setText("");
}});
jbtSubmit.addActionListener(new ActionListener()
{#Override
public void actionPerformed(ActionEvent arg0) {
new Infopane(jtfFirst.getText());
//dispose();
}});
}//ENDOFCONSTRUCTOR
public static void main(String[] args)
{
Ch10Asg frame = new Ch10Asg();
frame.pack();
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Flights");
frame.setVisible(true);
frame.setSize(700,450);
}//ENDOFMAIN
}//ENDOFCLASS
class Infopane extends JFrame
{
private JTextArea Info = new JTextArea();
private JButton jbtExit1 = new JButton ("EXIT");
public Infopane(String jtfFirst)
{
JPanel s1 = new JPanel();
add(Info, BorderLayout.NORTH);
//Info.setFont(new Font("Serif", Font.PLAIN, 14));
Info.setEditable(false);
JScrollPane scrollPane = new JScrollPane(Info);
//setLayout(new BorderLayout(5,5));
add(scrollPane);
add(jbtExit1, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null); // Center the frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Flight Summary");
setVisible(true);
setSize(700,450);
jbtExit1.addActionListener(new ActionListener()
{#Override
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}});
}
}
Suggestions:
The second window shouldn't be a second JFrame but rather a modal JDialog since it truly is a dialog of the first window. This way, you don't have to fret about the second window closing the entire application when it is closed.
You already have an idea of what you should be doing -- passing information from one object to another -- since you're passing the String held by the first window's first name's JTextField into the second class: jtfFirst.getText()
Instead of passing just one JTextField's text, consider creating a third data class that holds all the information that you want to pass from one class to the other, create an object of this in the submit's ActionListener, and pass it into the new class.
Alternatively, you could give your first class getter methods, and just pass an instance of the first object into the second object, allowing the second object to extract info from the first by calling its getter methods.
Edit
For example here are snippets of a code example that works. The main JPanel is called MainPanel:
class MainPanel extends JPanel {
// my JTextFields
private JTextField fooField = new JTextField(10);
private JTextField barField = new JTextField(10);
public MainPanel() {
add(new JLabel("Foo:"));
add(fooField);
add(new JLabel("Bar:"));
add(barField);
add(new JButton(new AbstractAction("Submit") {
{
putValue(MNEMONIC_KEY, KeyEvent.VK_S);
}
#Override
public void actionPerformed(ActionEvent evt) {
DialogPanel dialogPanel = new DialogPanel(MainPanel.this);
// code deleted....
// create and show a JDialog here
}
}));
add(new JButton(new AbstractAction("Exit") {
{
putValue(MNEMONIC_KEY, KeyEvent.VK_X);
}
#Override
public void actionPerformed(ActionEvent e) {
Window win = SwingUtilities.getWindowAncestor((JButton)e.getSource());
win.dispose();
}
}));
}
// getter methods to get information held in the fields.
public String getFooText() {
return fooField.getText();
}
public String getBarText() {
return barField.getText();
}
}
And in the dialog panel:
class DialogPanel extends JPanel {
private JTextArea textarea = new JTextArea(10, 15);
private MainPanel mainPanel;
public DialogPanel(MainPanel mainPanel) {
this.mainPanel = mainPanel; // actually don't even need this in your case
// extract the information from the origianl class
textarea.append("Foo: " + mainPanel.getFooText() + "\n");
textarea.append("Bar: " + mainPanel.getBarText() + "\n");
add(new JScrollPane(textarea));
add(new JButton(new AbstractAction("Exit") {
{
putValue(MNEMONIC_KEY, KeyEvent.VK_X);
}
#Override
public void actionPerformed(ActionEvent e) {
Window win = SwingUtilities.getWindowAncestor((JButton)e.getSource());
win.dispose();
}
}));
}
}

NullPointerException continues

When I am trying to call JPanel panel2 of Panel2 class on triggering of action event from Next JButton of Panel1 class, I am getting NullPointerException. How to resolve this? plzz help.
public class PanelEventTest
{
/**
* #param args
*/
JFrame frame;
void originalFrame()
{
frame = new JFrame();
frame.setSize(500, 300);
frame.setVisible(true);
frame.setLayout(new FlowLayout());
frame.add(new TestPanel1().panel1());
frame.add(new TestPanel2().panel2());
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new PanelEventTest().originalFrame();
}
}
public class TestPanel1
{
JPanel panel1;
JButton next;
JPanel panel1()
{
panel1 = new JPanel();
next = new JButton("Next");
next.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
// TODO Auto-generated method stub
new TestPanel2().panel2.removeAll();
}
});
panel1.add(next);
return panel1;
}
}
public class TestPanel2
{
JPanel panel2;
JList jlist;
String[] list = {"Sachin","Tarun","Vipin"};
JPanel panel2()
{
panel2 = new JPanel();
jlist = new JList(list);
panel2.add(jlist);
panel2.add(new JLabel("Test"));
return panel2;
}
}
My last question Nullpointerexception with JPanel was successfully resolved by you guys. Plz help in this. This exception is eating my head.
If you try changing this line:
new TestPanel2().panel2.removeAll();
To:
new TestPanel2().panel2().removeAll();
Will solve the problem, but the current logic is flawed.
A better solution is:
Change TestPanel2 to:
public class TestPanel2 {
JPanel panel2;
JList jlist;
String[] list = { "Sachin", "Tarun", "Vipin" };
public TestPanel2() { // was: JPanel panel2() {
panel2 = new JPanel();
jlist = new JList(list);
panel2.add(jlist);
panel2.add(new JLabel("Test"));
// was: return panel2;
}
}
And then modify TestPanel1 to:
public class TestPanel1 {
JPanel panel1;
JButton next;
public TestPanel1(final JFrame frame, TestPanel2 tp2) { // was: JPanel panel1() {
panel1 = new JPanel();
next = new JButton("Next");
final JPanel panel2 = tp2.panel2; // line created
next.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
panel2.removeAll(); // was: new TestPanel2().panel2.removeAll();
frame.validate(); // line created
frame.paint(); // line created
}
});
panel1.add(next);
// was: return panel1;
}
}
Finally, on PanelEventTest.originalFrame(), change:
frame.add(new TestPanel1().panel1());
frame.add(new TestPanel2().panel2());
to:
TestPanel2 tp2 = new TestPanel2();
frame.add(new TestPanel1(frame, tp2).panel1);
frame.add(tp2.panel2);
frame.validate();
frame.repaint();
Explanation
You are creating methods, when you needed constructors. You must read this: Understanding constructors.
Also, you need to pass TestPanel2 and the frame to TestPanel1:
Your code was creating a new TestPanel2 (attached to no one) and then calling removeAll() on it's pannel. This has no effect at all (as this panel is not shown anywhere).
The changed then code will call removeAll() on TestPanel1's panel.
Also, you need to revalidate/repaint the components everytime you make a change on them.
Currently you change them when you create the frame (adding the panels) and when you remove the panel2 (in the "Next" button's action).

Java Swing Removing Jpanel while clicking on Jbutton which is present in that jpanel which I want to remove

I am creating a GUI using Netbeans and my question is "how to remove the jpanel"...the hierarchical order as it is present Jframe->Jscrollpane->Jpanel->Jbutton. By clicking on the Jbutton I want to remove all components of the jpanel including the Jbutton(on which I am clicking) and the panel itself. Please do help.Urgent.THanks in advance
-Sayantan
private void b4ActionPerformed(java.awt.event.ActionEvent evt) {
final JPanel jp;
JTextField tf,of1,of2,xf,yf;
int i=1;
int m=(int)sp3.getValue();
JButton jb;
jp=new JPanel();
//jp.setLayout(new GridBagLayout());
DesignGridLayout layout = new DesignGridLayout(jp);
jsp2.getViewport().add(jp);
while(i<=m){
tf=new JTextField(5);
of1=new JTextField(5);
of2=new JTextField(5);
layout.row().grid(new JLabel("Type:")).indent(9).add(tf).grid(new JLabel("Length:")).indent().add(of1).grid(new JLabel("Breadth:")).indent().add(of2).empty();
fields1.add(tf);
fields1.add(of1);
fields1.add(of2);
xf=new JTextField(5);
yf=new JTextField(5);
layout.row().grid(new JLabel("X-axis:")).indent(9).add(xf).grid(new JLabel("Y-axis:")).indent().add(yf).empty(2);
fields1.add(xf);
fields1.add(yf);
i++;
}
jb=new JButton("Submit");
jb.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
for(JTextField field: fields1){
String s=field.getText();
lbr.setText(lbr.getText()+s);
}
lb3.setVisible(false);
sp3.setVisible(false);
b4.setVisible(false);
//jp.setVisible(false);
//jp.removeAll();
// jp.revalidate();
//jp.repaint();
// jsp2.remove(jp);
//jsp2.revalidate();
//jsp2.repaint();
}
});
layout.emptyRow();
layout.row().right().add(jb);
jp.revalidate();
jp.repaint();
// jsp2.revalidate();
//jsp2.repaint();
}
Note: I am using DesignGridLayout package.
This works:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ScratchSpace {
public static void main(String[] args) {
final JPanel panel = new JPanel();
panel.setOpaque(true);
panel.setBackground(Color.YELLOW);
panel.add(new JButton(new AbstractAction("Kill me") {
#Override
public void actionPerformed(ActionEvent e) {
panel.removeAll();
panel.revalidate();
panel.repaint();
}
}));
final JFrame frame = new JFrame();
frame.setContentPane(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
I want to remove all components of the jpanel including the Jbutton(on which I am clicking) and the panel itself.
Then you need code something like:
JButton button = (JButtton)event.getSource();
JPanel grandparent = button.getParent().getParent();
grandparent.removeAll();
grandparent.revalidate();
grandparent.repaint();
Although I question any code where I see a removeAll(). You might look into using a Card Layout.

Adding JPanels from other classes to the cardLayout

I've got 3 windows in 3 separate classes and I would like to use cardLayout so that when you click the next button, the next window will appear. How do I add JPanels containing different elements to one cardLayout? This is the first window: (the only difference is the background though - but it represents the idea of how I got it actually)
public class Window1 extends JPanel implements ActionListener {
static CardLayout cardLayout = new CardLayout();
public Window1() {
init();
}
private void init() {
JPanel jp = new JPanel(new BorderLayout());
JPanel jp2 = new Window2();
//JPanel jp3 = new Window3();
JLabel textLabel = new JLabel("Window1");
jp.setBackground(Color.GREEN);
jp.add(textLabel, BorderLayout.CENTER);
JButton nextButton = new JButton("NEXT");
nextButton.setActionCommand("next");
nextButton.addActionListener(this);
jp.add(nextButton, BorderLayout.EAST);
setLayout(cardLayout);
add(jp, "string");
add(jp2, "string");
//add(jp3, "string");
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equalsIgnoreCase("next")) {
// go to the next window
cardLayout.next(this);
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("test");
frame.getContentPane().setLayout(Window1.cardLayout);
frame.getContentPane().add(new Window1(), "Center");
frame.getContentPane().add(new Window2(), "Center");
frame.getContentPane().add(new Window3(), "Center");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(550, 450);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
The second window:
public class Window2 extends JPanel implements ActionListener {
//static CardLayout cardLayout = new CardLayout();
public Window2() {
init();
}
private void init() {
setLayout(new BorderLayout());
JLabel textLabel = new JLabel("Window2");
setBackground(Color.RED);
add(textLabel, BorderLayout.CENTER);
JButton nextButton = new JButton("NEXT");
nextButton.setActionCommand("next");
nextButton.addActionListener(this);
add(nextButton, BorderLayout.EAST);
//setLayout(cardLayout);
//JPanel jp3 = new Window3();
//add(jp3, "string");
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equalsIgnoreCase("next")) {
// go to the next window??
System.out.println("window2");
Window1.cardLayout.next(this);
}
}
}
And the last one:
public class Window3 extends JPanel implements ActionListener {
public Window3() {
init();
}
private void init() {
setLayout(new BorderLayout());
JLabel textLabel = new JLabel("Window3");
setBackground(Color.BLUE);
add(textLabel, BorderLayout.CENTER);
JButton nextButton = new JButton("NEXT");
nextButton.setActionCommand("next");
nextButton.addActionListener(this);
add(nextButton, BorderLayout.EAST);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equalsIgnoreCase("next")) {
// go to the next window
// Window1.cardLayout.next(this);
}
}
}
I had made a small program, hopefully the comments written in the program, might be able to guide you, to understand how to use CardLayout.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/* Here we are first declaring our class that will act as the
* base for other panels or in other terms the base for CardLayout.
*/
public class CardLayoutTest
{
private static final String CARD_JBUTTON = "Card JButton";
private static final String CARD_JTEXTFIELD = "Card JTextField";
private static final String CARD_JRADIOBUTTON = "Card JRadioButton";
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Card Layout Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
// This JPanel is the base for CardLayout for other JPanels.
final JPanel contentPane = new JPanel();
contentPane.setLayout(new CardLayout(20, 20));
/* Here we be making objects of the Window Series classes
* so that, each one of them can be added to the JPanel
* having CardLayout.
*/
Window1 win1 = new Window1();
contentPane.add(win1, CARD_JBUTTON);
Window2 win2 = new Window2();
contentPane.add(win2, CARD_JTEXTFIELD);
Window3 win3 = new Window3();
contentPane.add(win3, CARD_JRADIOBUTTON);
/* We need two JButtons to go to the next Card
* or come back to the previous Card, as and when
* desired by the User.
*/
JPanel buttonPanel = new JPanel();
final JButton previousButton = new JButton("PREVIOUS");
previousButton.setBackground(Color.BLACK);
previousButton.setForeground(Color.WHITE);
final JButton nextButton = new JButton("NEXT");
nextButton.setBackground(Color.RED);
nextButton.setForeground(Color.WHITE);
buttonPanel.add(previousButton);
buttonPanel.add(nextButton);
/* Adding the ActionListeners to the JButton,
* so that the user can see the next Card or
* come back to the previous Card, as desired.
*/
previousButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.previous(contentPane);
}
});
nextButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
CardLayout cardLayout = (CardLayout) contentPane.getLayout();
cardLayout.next(contentPane);
}
});
// Adding the contentPane (JPanel) and buttonPanel to JFrame.
frame.add(contentPane, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.PAGE_END);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
class Window1 extends JPanel
{
/*
* Here this is our first Card of CardLayout, which will
* be added to the contentPane object of JPanel, which
* has the LayoutManager set to CardLayout.
* This card consists of Two JButtons.
*/
private ActionListener action;
public Window1()
{
init();
}
private void init()
{
final JButton clickButton = new JButton("CLICK ME");
final JButton dontClickButton = new JButton("DON\'T CLICK ME");
action = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource() == clickButton)
{
JOptionPane.showMessageDialog(null, "Hello there dude!"
, "Right Button", JOptionPane.INFORMATION_MESSAGE);
}
else if (ae.getSource() == dontClickButton)
{
JOptionPane.showMessageDialog(null, "I told you not to click me!"
, "Wrong Button", JOptionPane.PLAIN_MESSAGE);
}
}
};
clickButton.addActionListener(action);
dontClickButton.addActionListener(action);
add(clickButton);
add(dontClickButton);
}
}
class Window2 extends JPanel implements ActionListener
{
/*
* Here this is our second Card of CardLayout, which will
* be added to the contentPane object of JPanel, which
* has the LayoutManager set to CardLayout.
* This card consists of a JLabel and a JTextField
* with GridLayout.
*/
private JTextField textField;
public Window2()
{
init();
}
private void init()
{
setLayout(new GridLayout(1, 2));
JLabel userLabel = new JLabel("Your Name : ");
textField = new JTextField();
textField.addActionListener(this);
add(userLabel);
add(textField);
}
public void actionPerformed(ActionEvent e)
{
if (textField.getDocument().getLength() > 0)
JOptionPane.showMessageDialog(null, "Your Name is : " + textField.getText()
, "User\'s Name : ", JOptionPane.QUESTION_MESSAGE);
}
}
class Window3 extends JPanel
{
/*
* Here this is our third Card of CardLayout, which will
* be added to the contentPane object of JPanel, which
* has the LayoutManager set to CardLayout.
* This card consists of Two JLabels and two JCheckBox
* with GridLayout.
*/
private ActionListener state;
public Window3()
{
init();
}
public void init()
{
setLayout(new GridLayout(2, 2));
JLabel maleLabel = new JLabel("MALE", JLabel.CENTER);
final JCheckBox maleBox = new JCheckBox();
JLabel femaleLabel = new JLabel("FEMALE", JLabel.CENTER);
final JCheckBox femaleBox = new JCheckBox();
state = new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (maleBox == (JCheckBox) ae.getSource())
{
femaleBox.setSelected(false);
JOptionPane.showMessageDialog(null, "Congrats you are a Male"
, "Gender : ", JOptionPane.INFORMATION_MESSAGE);
}
else if (femaleBox == (JCheckBox) ae.getSource())
{
maleBox.setSelected(false);
JOptionPane.showMessageDialog(null, "Congrats you are a Female"
, "Gender : ", JOptionPane.INFORMATION_MESSAGE);
}
}
};
maleBox.addActionListener(state);
femaleBox.addActionListener(state);
add(maleLabel);
add(maleBox);
add(femaleLabel);
add(femaleBox);
}
}
There are a couple things:
As your program can only run 1 main method, each class doesnt need one, but whichever you do run should create an instance of each panel you want to add to your CardLayout.
You also do not seem to add your Windows to your CardLayout at all. You could try the following (uncomplied). This would only be needed in one class:
private static void createAndShowGUI() {
JFrame frame = new JFrame("test");
frame.getContentPane().setLayout(Window1.cardLayout);
frame.getContentPane().add(new Window1());
frame.getContentPane().add(new Window2());
frame.getContentPane().add(new Window3());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(550, 450);
frame.setVisible(true);
}
Further (and this might just be due to the simplicity of your example), I would just have 1 class, and it would take the name of the panel and the color of the background to the constructor. These could be passed into your init() method and your design would be somewhat streamlined.

Categories