From my action listener which I believe is static, im trying to call a non static method from a class. How can i call my method from my class?
public class addContent {
User Darryl = new User();
public static void addStuff(){
//Panel and Frame
JPanel panel = new JPanel(new BorderLayout());
JFrame frame = new JFrame("PandaHunterV3");
Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Setup labels
JLabel label = new JLabel("Label");
frame.getContentPane().add(label);
//Setup buttons
JButton button = new JButton("Button");
frame.getContentPane().add(button);
//Action listener
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
Darryl.showHealth(); // HERE IS THE PROBLEM.
}
});
//Crap
frame.pack();
frame.setVisible(true);
}
}
and my class from which i am trying to call the methods from
public class User {
int health;
User(){
health = 50;
}
public void showHealth(){
System.out.print(health);
}
public void incHealth(){
health += 20;
}
}
EDIT:
Mark the Daryl instance as static or the method addStuff() as non-static.
btw. use low case for naming the variables / instances and upper-case for class names.
public class AddContent {
private User darryl = new User();
public void addStuff(){
//Panel and Frame
JPanel panel = new JPanel(new BorderLayout());
JFrame frame = new JFrame("PandaHunterV3");
Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Setup labels
JLabel label = new JLabel("Label");
frame.getContentPane().add(label);
//Setup buttons
JButton button = new JButton("Button");
frame.getContentPane().add(button);
//Action listener
button.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
AddContent.this.darryl.showHealth(); // SHOULD BE FINE
}
});
//Crap
frame.pack();
frame.setVisible(true);
}
}
Related
Please help me to understand how this works. I'm having difficulties to understand how, for example, JButton in one class can alter text in JTextArea that is in another class of a same package. I've made a simple app just to ask a question here, I need this for a bigger school project where I need to implement this to work with multiple classes.
When I put everything in the same class it works but I need it in separate classes.
Here is the simple code.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class Button extends JPanel {
private JButton button;
private Panel panel;
public Button() {
button = new JButton("BUTTON");
panel = new Panel();
add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton clicked = (JButton) e.getSource();
String input = clicked.getText();
panel.setTextArea(input);
//System.out.println(input);
}
});
}
}
class Panel extends JPanel {
private JTextArea textArea;
public Panel() {
setLayout(new BorderLayout());
textArea = new JTextArea();
add(textArea, BorderLayout.CENTER);
}
public JTextArea getTextArea() {
return textArea;
}
void setTextArea(String text) {
this.textArea.setText(text);
}
}
public class Java extends JFrame {
private Button dugme;
private JFrame frame;
private Panel panel;
public Java() {
frame = new JFrame();
dugme = new Button();
panel = new Panel();
//super("test");
frame.setLayout(new BorderLayout());
frame.setTitle("test");
frame.setSize(300, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(dugme, BorderLayout.NORTH);
frame.add(panel, BorderLayout.CENTER);
}
public static void main(String[] args) {
Java app = new Java();
}
}
I want action listener to alter the text in the panel, sys-out works so the listener listens the button but I can't make it to alter the text in text area.
As already mentioned by #XtremeBaumer you have two different instances of Panel class. You need to remove the secode one.
public class Button extends JPanel {
private JButton button;
private Panel panel;
public Button(Panel panel) { // we need already created instance of panel here.
this.panel = panel;
button = new JButton("BUTTON");
// panel = new Panel(); <-- this line must be deleted.
// ...
}
}
public class Java extends JFrame {
private Button dugme;
private JFrame frame;
private Panel panel;
public Java(){
frame = new JFrame();
panel = new Panel();
dugme = new Button(panel);
// ...
}
}
Please also replace the line
add(textArea, BorderLayout.CENTER);
by
add(new JScrollPane(textArea), BorderLayout.CENTER);
This allows you to get the scrool bars when text goes larger than the text ara size.
Here is your reworked example
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class Button extends JPanel {
private JButton button;
private Panel panel;
public Button(Panel panel) {
this.panel = panel;
button = new JButton("BUTTON");
add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton clicked = (JButton) e.getSource();
String input = clicked.getText();
panel.setTextArea(input);
//System.out.println(input);
}
});
}
}
class Panel extends JPanel {
private JTextArea textArea;
public Panel() {
setLayout(new BorderLayout());
textArea = new JTextArea();
add(new JScrollPane(textArea), BorderLayout.CENTER);
}
public JTextArea getTextArea() {
return textArea;
}
void setTextArea(String text) {
this.textArea.setText(text);
}
}
public class Java extends JFrame {
private Button dugme;
private JFrame frame;
private Panel panel;
public Java() {
frame = new JFrame();
panel = new Panel();
dugme = new Button(panel);
//super("test");
frame.setLayout(new BorderLayout());
frame.setTitle("test");
frame.setSize(300, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(dugme, BorderLayout.NORTH);
frame.add(panel, BorderLayout.CENTER);
}
public static void main(String[] args) {
Java app = new Java();
}
}
I have used cardlayout in my main class. I have added first panel in that cardlayout. I'm trying to hide the image in frame from first panel. So I have used interface like below code,
My Main class,
public class HomePage implements OptionMenuListener{
private static void createAndShowGUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Already there
frame.setUndecorated(true);
frame.setLocationRelativeTo(null);
JPanel contentPane = new JPanel();
contentPane.setLayout(new CardLayout(20, 20));
File file = new File(jsonFilePath);
if(!file.exists()) {
LoginPage login = new LoginPage();
contentPane.add(login, Constants.CARD_LOGIN);
ConfigueBranch configureBranch = new ConfigueBranch(false);
contentPane.add(configureBranch, Constants.CARD_CONFIGURE_BRANCH);
ConfigureSystem configureSystem = new ConfigureSystem(false);
contentPane.add(configureSystem, Constants.CARD_CONFIGURE_SYSTEM);
ConfigureCustomer configureCustomer = new ConfigureCustomer(false);
contentPane.add(configureCustomer, Constants.CARD_CONFIGURE_CUSTOMER);
}
MainPage mainPage = new MainPage(HomePage.this);
contentPane.add(mainPage, Constants.CARD_MAINPAGE);
// SettingsPage configureExpinContainer = new SettingsPage();
// contentPane.add(configureExpinContainer, Constants.CARD_SETTINGS_PAGE);
JPanel buttonPanel = new JPanel();
buttonPanel.setBorder(new EmptyBorder(50, 10, 10, 10));
Image image = MyUtil.loadImage("/logo.png"); // transform it
Image newimg = image.getScaledInstance(244, 80, java.awt.Image.SCALE_SMOOTH);
ImageIcon icon = new ImageIcon(newimg); // transform it back
JLabel label = new JLabel("", icon, JLabel.LEFT);
label.setFont(new java.awt.Font("Arial", Font.BOLD, 24));
label.setOpaque(true);
label.setForeground(Color.BLACK);
label.setBounds(0, 60, 300, 200);
buttonPanel.add(label);
frame.add(contentPane, BorderLayout.CENTER);
frame.add(buttonPanel, BorderLayout.PAGE_START);
frame.pack();
frame.setSize(1000, 700);
centeredFrame(frame);
frame.setVisible(true);
frame.setResizable(false);
}
public static void centeredFrame(javax.swing.JFrame objFrame) {
Dimension objDimension = Toolkit.getDefaultToolkit().getScreenSize();
int iCoordX = (objDimension.width - objFrame.getWidth()) / 2;
int iCoordY = (objDimension.height - objFrame.getHeight()) / 2;
objFrame.setLocation(iCoordX, iCoordY);
}
public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
#Override
public void onMenuSelect(boolean isShow) {
}
}
I'm using for interface to provide communication to frame from panel,
public interface OptionMenuListener {
void onMenuSelect(boolean isShow);
}
I'm using the below panel in cardlayout,
public class MainPage extends JPanel{
JButton inputOutputFilesBtn, syncBtn, tsBtn, settingsBtn;
public MainPage(HomePage homePage){
homePage.onMenuSelect(true);
init();
}
public void init(){
JTabbedPane jtbExample = new JTabbedPane();
JPanel jplInnerPanel1 = createInnerPanel("No device connected");
jtbExample.addTab("Input and Output Files", jplInnerPanel1);
jtbExample.setSelectedIndex(0);
JPanel jplInnerPanel2 = createInnerPanel("No device connected");
jtbExample.addTab("Sync", jplInnerPanel2);
JPanel jplInnerPanel3;
if(configuredSystem.equalsIgnoreCase("Expeditors")) {
jplInnerPanel3 = createInnerPanel("No device connected");
jtbExample.addTab("TS", jplInnerPanel3);
}
JPanel jplInnerPanel4 = new SettingsPage();
jtbExample.addTab("Settings", jplInnerPanel4);
JPanel jplInnerPanel5 = new LogoutPage();
jtbExample.addTab("Logout", jplInnerPanel5);
this.setLayout(new BorderLayout());
this.setPreferredSize(new Dimension(620, 400));
this.add(jtbExample, BorderLayout.CENTER);
add(jtbExample);
}
protected JPanel createInnerPanel(String text) {
JPanel jplPanel = new JPanel();
JLabel jlbDisplay = new JLabel(text);
jlbDisplay.setHorizontalAlignment(JLabel.CENTER);
jplPanel.setLayout(new GridLayout(1, 1));
jplPanel.add(jlbDisplay);
return jplPanel;
}
But i'm getting Cannot use this in a static context error in this below line
MainPage mainPage = new MainPage(HomePage.this);
Now i want to send some information from panel to the frame which have cardlayout. Could you please suggest me an idea to do this? Thanks in advance.
You can't use this in a static context like since this represent the class instance that is executing a method. Here, you are in a static context, so you don't have an instance.
private static void createAndShowGUI() {
MainPage mainPage = new MainPage(HomePage.this);
}
You either need to declare a variable
private static void createAndShowGUI() {
HomePage homePage = /*initialize or get it from somewhere */
MainPage mainPage = new MainPage(homePage);
}
Or move that logic outside the static context
private void createAndShowGUI() {
MainPage mainPage = new MainPage(HomePage.this);
}
This questions has been asked a few times but mine is a little different. I created a small application and in the view I added a few JPanels to a JFrame. I then try to add actionListeners in the controller which is where the problem happened.
The code below gives me the following error:
The method addActionListener(new ActionListener(){})
is undefined for the type JPanel
The view class
public class MainMenuGUI {
JTabbedPane tabbedPane = new JTabbedPane();
JPanel findUserPanel;
JPanel deleteUserPanel;
JPanel addUserPanel;
JFrame frame = new JFrame();
JPanel tabbedPanel = new JPanel();
//Controller class for tabbedPanel
ControllerTabbedPane listen = new ControllerTabbedPane(this);
//Controller class for findUserPanel
FindUserPanelController findUserController = new FindUserPanelController(findUserPanel);
public MainMenuGUI() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
findUserPanel = createFindUserPanel();
deleteUserPanel = createDeleteUserPanel();
addUserPanel = createAddUserPanel();
tabbedPane.addTab("Find User", findUserPanel);
tabbedPane.addTab("Delete User", deleteUserPanel);
tabbedPane.addTab("Add User", addUserPanel);
tabbedPanel.add(tabbedPane);
frame.add(tabbedPanel);
frame.pack();
// opens frame in the center of the screen
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
JPanel createFindUserPanel() {
findUserPanel = new JPanel();
findUserPanel.setPreferredSize(new Dimension(300, 300));
findUserPanel.setLayout(new GridLayout(5, 7));
JLabel firstlbl = new JLabel("First Name");
JLabel lastlbl = new JLabel("Last Name");
JLabel addresslbl = new JLabel("Address");
JLabel agelbl = new JLabel("Age");
JTextField firstNametxt = new JTextField(15);
JTextField lastNametxt = new JTextField(15);
JTextField addresstxt = new JTextField(30);
JTextField age = new JTextField(3);
JButton btn = new JButton("Submit");
JScrollPane window = new JScrollPane();
window.setViewportBorder(new LineBorder(Color.RED));
window.setPreferredSize(new Dimension(150, 150));
findUserPanel.add(firstlbl);
findUserPanel.add(firstNametxt);
findUserPanel.add(lastlbl);
findUserPanel.add(lastNametxt);
findUserPanel.add(addresslbl);
findUserPanel.add(addresstxt);
findUserPanel.add(agelbl);
findUserPanel.add(age);
findUserPanel.add(window, BorderLayout.CENTER);
findUserPanel.add(btn);
return findUserPanel;
}
Controller Class
public class ControllerTabbedPane {
MainMenuGUI mainMenuGUI;
int currentTabbedIndex = 0;
ControllerTabbedPane(MainMenuGUI mainMenuGUI){
this.mainMenuGUI = mainMenuGUI;
addTabbedPaneListeners();
}
private void addTabbedPaneListeners() {
mainMenuGUI.tabbedPane.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent ce) {
currentTabbedIndex = mainMenuGUI.tabbedPane.getSelectedIndex();
System.out.println("Current tab is:" + currentTabbedIndex);
}
});
}
/*ERROR saying The method addActionListener(new ActionListener(){})
is undefined for the type JPanel*/
private void findPanelListeners() {
mainMenuGUI.findUserPanel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
});
}
This is the way to achieve your request:
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JButton bt1 = new JButton();
JButton bt2 = new JButton();
panel1.add(bt1);
panel2.add(bt2);
bt1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Bt1 on panel1 pressed");
}
});
bt2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Bt2 on panel2 pressed");
}
});
You can modify variables or other objects into the listeners to store which panel was "pressed".
I think its not possible to add addActionListner() to JPanel
Instead
You can use,
JPanel p1=new JPanel();
p1.addMouseListener(this);
And override
public void mouseClicked(MouseEvent me)
{
int x=me.getX();
int y=me.getY();
System.out.println(x+","+y);
//By using x AND y you can identify the panel
}
NB: extends MouseAdapter
On the event of clicking a button how would I get the JPanel it is in currently?
I know how to make a button and add an actionlistener and do event handling. I don't know how to select the current panel.
The code from the post above modified to avoid using final variables
public void buildUI() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton button = new JButton("Button");
panel.add(button);
button.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("The current panel is " + ((JButton)e.getComponent()).getParent());
}
});
frame.add(panel);
frame.pack();
frame.setDefaultCloseBehavior(JFrame.CLOSE_ON_EXIT);
frame.setVisible(true);
}
public void buildUI() {
JFrame frame = new JFrame();
final JPanel panel = new JPanel();
JButton button = new JButton("Button");
panel.add(button);
button.addActionListener( new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("The current panel is " + panel);
}
});
frame.add(panel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
EDIT: Adding example where listener code is not in the same class as GUI code.
//PanelPrintingListener.java
public class PanelPrintingListener implements ActionListener {
private JPanel panel;
public PanelPrintingListener(JPanel panel) {
this.panel = panel;
}
public void actionPerformed(ActionEvent e) {
System.out.println("The current panel is " + panel);
}
}
//OtherFoo.java
public void buildUI() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JButton button = new JButton("Button");
panel.add(button);
button.addActionListener( new PanelPrintingListener(panel) );
frame.add(panel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
If you are looking for the panel that is currently active (meaning that it is the top one in the stack), then you can use the getComponent() method.
Component active = parentPanel.getComponent(0);
Now the "active" object will have the currently active or displayed panel.Note that "parentPanel" is the panel on which the required sub-panels are placed.
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.