Why is the public class name wrong?(Card Layout) - java

The program doesn't work still after I fixed the selling error. It says in the console. "Error: Main method not found in class help.MyCardLayout, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application" I don't know what that means.
package help;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyCardLayout implements ItemListener {
JPanel cards;
final static String BUTTONPANEL1 = "Card1";
final static String BUTTONPANEL2 = "Card2";
public void addComponentToPane(Container pane){
JPanel comboBoxPane = new JPanel();
String comboBoxItems[] = { BUTTONPANEL1, BUTTONPANEL2 };
JComboBox cb = new JComboBox(comboBoxItems);
cb.setEditable(false);
cb.addItemListener(this);
comboBoxPane.add(cb);
JPanel card1 = new JPanel();
card1.add(new JButton("Button 1"));
JPanel card2 = new JPanel();
card2.add(new JButton("Button 2"));
cards = new JPanel(new CardLayout());
cards.add(card1, BUTTONPANEL1);
cards.add(card2, BUTTONPANEL2);
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());
}
private static void createAndShowGUI(){
JFrame frame = new JFrame("CardLayoutDemo");
frame.setSize(300,200);
frame.setTitle("CardLayout");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CardLayoutDemo demo = new CardLayoutDemo();
demo.addComponentToPane(frame.getContentPane());
frame.pack();
frame.setVisible(true);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

You wrote:
public void itemStateChange(ItemEvent evt) {
^ d is missing
The name is itemStateChanged and not itemStateChange

You've misspelt itemStateChanged() as itemStateChange() (there's a d missing at the end):
public void itemStateChange(ItemEvent evt){
↑ here

Related

Get text field information from one class and show it on a JTextArea on another class

I have a class BasicInfoWindow that gets the user information such as name, address, etc. I then have another class ReviewandSubmit where it show the the texts the user entered from BasicInfoWindow in the JTextArea. I am using card layout to switch between each panel. I am not sure how to send the info from BasicInfoWindow and receive it from ReviewandSubmit. Here is my code so far:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main extends JPanel
{
private static void createAndShowGUI()
{
final Main test = new Main();
JPanel buttonPanel = new JPanel(new BorderLayout());
JPanel southPanel = new JPanel();
buttonPanel.add(southPanel, BorderLayout.SOUTH);
final JButton btnNext = new JButton("NEXT");
final JButton btnPrev = new JButton("PREVIOUS");
buttonPanel.add(btnNext, BorderLayout.EAST);
buttonPanel.add(btnPrev, BorderLayout.WEST);
btnNext.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
test.nextCard();
}
});
btnPrev.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
test.prevCard();
}
});
JFrame frame = new JFrame("Employment Application");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(test);
frame.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
//frame.setSize(750,500);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
}
public static void main(String [] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createAndShowGUI();
}
});
}
private CardLayout cardLayout = new CardLayout();
private JPanel cardShowingPanel = new JPanel(cardLayout);
public Main()
{
BasicInfoWindow window1 = new BasicInfoWindow();
cardShowingPanel.add(window1, "1");
EmploymentHistoryWindow window2 = new EmploymentHistoryWindow();
cardShowingPanel.add(window2, "2");
EducationAndAvailbleWindow window3 = new EducationAndAvailbleWindow();
cardShowingPanel.add(window3, "3");
ReviewAndSubmitWindow window4 = new ReviewAndSubmitWindow();
cardShowingPanel.add(window4, "4");
setLayout(new BorderLayout());
add(cardShowingPanel, BorderLayout.CENTER);
}
public void nextCard()
{
cardLayout.next(cardShowingPanel);
}
public void prevCard()
{
cardLayout.previous(cardShowingPanel);
}
public void showCard(String key)
{
cardLayout.show(cardShowingPanel, key);
}
}
BasicInfo Class
ommitted some methods
public class BasicInfoWindow extends JPanel
{
private JTextField txtName, txtAddress, txtCity, txtState, txtZipCode, txtPhoneNumber, txtEmail;
private JComboBox cbDate, cbYear, cbMonth;
private JLabel labelName, labelAddress, labelCity, labelState, labelZipCode, labelPhoneNumber, labelEmail, labelDOB;
private JButton btnClear;
public BasicInfoWindow()
{
createView();
}
private void createView()
{
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
add(panel);
northPanel(panel);
centerPanel(panel);
southPanel(panel);
}
public ArrayList<HiringPersonInfo> sendInfo()
{
String name = txtName.getText();
String address = txtAddress.getText();
String city = txtCity.getText();
String state = txtState.getText();
String zip = txtZipCode.getText();
String phone = txtPhoneNumber.getText();
String email = txtEmail.getText();
String DOB = cbMonth.getSelectedItem() + " " + cbDate.getSelectedItem() + " " + cbYear.getSelectedItem();
HiringPersonInfo addNewInfo = new HiringPersonInfo(name, address, city, state, zip, phone, email, DOB);
ArrayList<HiringPersonInfo> personInfo = new ArrayList();
personInfo.add(addNewInfo);
return personInfo;
}
ReviewAndSubmit class
public class ReviewAndSubmitWindow extends JPanel
{
private JButton btnSubmit;
public ReviewAndSubmitWindow()
{
createView();
}
private void createView()
{
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
add(panel);
northPanel(panel);
centerPanel(panel);
southPanel(panel);
}
private void northPanel(JPanel panel)
{
JPanel northPanel = new JPanel();
panel.add(northPanel, BorderLayout.NORTH);
JLabel labelMessage = new JLabel("Review and Submit");
labelMessage.setFont(new Font("Serif", Font.BOLD, 25));
northPanel.add(labelMessage, BorderLayout.CENTER);
}
private void centerPanel(JPanel panel)
{
JPanel centerPanel = new JPanel();
JTextArea showReview = new JTextArea();
showReview.setLineWrap(true);
showReview.setWrapStyleWord(true);
showReview.setEditable(false);
JScrollPane scrollPane = new JScrollPane(showReview);
scrollPane.setPreferredSize(new Dimension(600, 385));
centerPanel.add(scrollPane, BorderLayout.CENTER);
BasicInfoWindow getInfo = new BasicInfoWindow();
showReview.append(getInfo.sendInfo().toString());
panel.add(centerPanel);
}
private void southPanel(JPanel panel)
{
JPanel southPanel = new JPanel();
panel.add(southPanel, BorderLayout.SOUTH);
btnSubmit = new JButton("SUBMIT");
// creates a new file
southPanel.add(btnSubmit);
}
}
You could use a Singleton Pattern in the HiringPersonInfo class to instantiate one instance of the class and then during the submit you could add that instance of that class to an ArrayList.
Singleton Patterns can be used to create one instance of the object that can be shared by all the classes in that package. You can think of it like a "global" variable in a way for OOP.

pass JFrame.getText() from one class member to other?

In this code , I have used 3 classes all of them which extend the JPanel class , whose instances are added to a JFrame in the JForm3 class's constructor.
I am wondering if there's a way to display the text present in the text field(instance of JTextField declared in TextPanel class) in the printTextOnConsole() method in the ButtonPanel class.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JForm3
{
JFrame frame;
ButtonPanel bP;
TextPanel tP;
LabelPanel lP;
public JForm3()
{
frame = new JFrame("Java Window.");
bP = new ButtonPanel();
tP = new TextPanel();
lP = new LabelPanel();
frame.setSize(500,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(BorderLayout.CENTER,tP);
frame.getContentPane().add(BorderLayout.EAST,bP);
frame.getContentPane().add(BorderLayout.WEST,lP);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args)
{
new JForm3();
}
}
class ButtonPanel extends JPanel implements ActionListener
{
JButton quitButton;
JButton printButton;
public ButtonPanel()
{
quitButton = new JButton("Quit");
printButton = new JButton("Print");
quitButton.addActionListener(this);
printButton.addActionListener(this);
this.setLayout(new BoxLayout(this,BoxLayout.Y_AXIS));
this.add(quitButton);
this.add(printButton);
}
public void actionPerformed(ActionEvent event)
{
if(event.getSource() == quitButton)
System.exit(0);
else
printTextOnConsole();
}
public void printTextOnConsole()
{
}
}
class LabelPanel extends JPanel
{
JLabel label;
public LabelPanel()
{
this.setLayout(new BorderLayout());
label = new JLabel("Enter Some Text :");
this.add(BorderLayout.CENTER,label);
this.setVisible(true);
}
}
class TextPanel extends JPanel
{
JTextField textField;
public TextPanel()
{
this.setLayout(new BorderLayout());
textField = new JTextField("Enter text here");
this.add(BorderLayout.CENTER,textField);
this.requestFocus();
textField.select(0,textField.getText().length());
this.setVisible(true);
}
}
Use an interface to loose couple the text functionality between JPanels.
interface TextRetriever {
String getText();
}
Then pass the instance of the TextRetriever (TextPanel) to ButtonPanel
class ButtonPanel extends JPanel implements ActionListener {
private TextRetriever textRetriever;
public ButtonPanel(TextRetriever textRetriever) {
this.textRetriever = textRetriever
...
}
public void printTextOnConsole() {
String text = textRetriever.getText();
}
}

I can use getActionCommand to change the label content, but I can't use it to change the color?

So with the help of others here I finally managed to code a button that alternates the label "Hello World!" to "Hello Universe!" and back again. I used the code below, and used the same way to try and change the color, but it didn't work as expected. I've been searching for hours on this, but with no avail. Thank you for reading, anything helps!
Code:
package game;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Javagame extends JPanel implements ActionListener{
protected JButton changetext;
protected JButton red;
protected JButton green;
private JLabel label;
public Javagame() {
add(changetext = new JButton("Button!"));
changetext.setPreferredSize(new Dimension(50, 50));
changetext.setActionCommand("change");
add(red = new JButton("Red"));
red.setPreferredSize(new Dimension(50, 50));
red.setActionCommand("changecolorRed");
add(green = new JButton("Green"));
green.setPreferredSize(new Dimension(50, 50));
green.setActionCommand("changecolorGreen");
changetext.addActionListener(this);
label = new JLabel("Hello World!", SwingConstants.CENTER);
label.setFont(new Font("Arial", Font.BOLD, 20));
label.setForeground(new Color(0x009900));
setLayout(new BorderLayout());
add(label, BorderLayout.CENTER);
add(changetext, BorderLayout.NORTH);
add(red, BorderLayout.WEST);
add(green, BorderLayout.EAST);
}
public void actionPerformed(ActionEvent e) {
if ("change".equals(e.getActionCommand())) {
label.setText("Hello Universe!");
changetext.setActionCommand("changeBack");
}
if ("changeBack".equals(e.getActionCommand())) {
label.setText("Hello World!");
changetext.setActionCommand("change");
}
if ("changecolorRed".equals(e.getActionCommand())) {
label.setForeground(new Color(0xFF0000));
}
if ("changecolorGreen".equals(e.getActionCommand())) {
label.setForeground(new Color(0x009900));
}
}
private static void createWindow(){
JFrame frame = new JFrame("Javagame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(500,500));
JPanel panel = new JPanel(new BorderLayout());
Javagame newContentPane = new Javagame();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
createWindow();
}
}
You need to add ActionListeners to buttons for them to work.
This is usually done via a simple method call: red.addActionListener(someListener);
Also:
get rid of your setPreferredsize(...) method calls, and instead let components set their own size. At the most you can override getPreferredSize() if need be, but try to limit that.
Avoid having your GUI code implement your listener interfaces as that leads to confusing and difficult to manage code. Better to use anonymous inner listeners or private inner classes or stand alone listener classes.
For example:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class JavaGame2 extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = 400;
private static final Font LABEL_FONT = new Font("Arial", Font.BOLD, 20);
private static final Color[] FOREGROUNDS = { new Color(0x009900),
new Color(0x990000), new Color(0x000099), new Color(0x999900),
new Color(0x990099), new Color(0x009999) };
private static final String[] LABEL_TEXTS = { "Hello World!",
"Goodbye World!", "Hola Todo el Mundo!", "Hasta la Vista Baby!",
"Whatever!!" };
private JButton changetextButton;
private JButton changeColorButton;
private JLabel label;
private int labelTextIndex = 0;
private int foregroundIndex = 0;
public JavaGame2() {
label = new JLabel(LABEL_TEXTS[labelTextIndex], SwingConstants.CENTER);
label.setFont(LABEL_FONT);
label.setForeground(FOREGROUNDS[foregroundIndex]);
// example of anonymous inner ActionListener:
changetextButton = new JButton("Change Text");
changetextButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
labelTextIndex++;
labelTextIndex %= LABEL_TEXTS.length;
label.setText(LABEL_TEXTS[labelTextIndex]);
}
});
// example of use of an anonymous AbstractAction:
changeColorButton = new JButton(new AbstractAction("Change Color") {
#Override
public void actionPerformed(ActionEvent e) {
foregroundIndex++;
foregroundIndex %= FOREGROUNDS.length;
label.setForeground(FOREGROUNDS[foregroundIndex]);
}
});
setLayout(new BorderLayout());
add(changetextButton, BorderLayout.NORTH);
add(changeColorButton, BorderLayout.SOUTH);
add(label, BorderLayout.CENTER);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
JavaGame2 mainPanel = new JavaGame2();
JFrame frame = new JFrame("Java Game 2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

How do I add a class in to a JPanel?

This is the JPanel
public class DisplayBoard {
public static void main (String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//The main panel
JPanel main = new JPanel();
main.setPreferredSize(new Dimension(600,800) );
main.setLayout(new BorderLayout());
//The title panel
JPanel title = new JPanel();
title.setPreferredSize(new Dimension(400, 120));
title.setBackground(Color.YELLOW);
JLabel test1 = new JLabel("Title goes here");
title.add(test1);
//The side bar panel
JPanel sidebar = new JPanel();
sidebar.setPreferredSize(new Dimension(200, 800));
sidebar.add(AddSubtract);
sidebar.setBackground(Color.GREEN);
JLabel test2 = new JLabel("Sidebar goes here");
sidebar.add(test2);
//The panel that displays all the cards
JPanel cardBoard = new JPanel();
cardBoard.setPreferredSize(new Dimension(400,640) );
//adding panels to the main panel
main.add(cardBoard, BorderLayout.CENTER);
main.add(title, BorderLayout.NORTH);
main.add(sidebar, BorderLayout.WEST);
frame.setContentPane(main);
frame.pack();
frame.setVisible(true);
}
}
and I want to add this class into the sidebar panel
public class AddSubtract {
int Number = 0;
private JFrame Frame = new JFrame("Math");
private JPanel ContentPane = new JPanel();
private JButton Button1 = new JButton("Add");
private JButton Button2 = new JButton("Subtract");
private JLabel Num = new JLabel ("Number: " + Integer.toString (Number));
public AddSubtract() {
Frame.setContentPane(ContentPane);
ContentPane.add(Button1);
ContentPane.add(Button2);
ContentPane.add(Num);
Button1.addActionListener(new Adding());
Button2.addActionListener(new Subtracting());
}
public class Adding implements ActionListener {
public void actionPerformed(ActionEvent e) {
Number++;
Num.setText ("Number: " + Integer.toString (Number));
}
}
public class Subtracting implements ActionListener {
public void actionPerformed(ActionEvent e) {
Number--;
Num.setText ("Number: " + Integer.toString (Number));
}
}
public void launchFrame(){
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.pack();
Frame.setVisible(true);
}
public static void main(String args[]){
AddSubtract Test = new AddSubtract();
Test.launchFrame();
}
}
Can someone explain to me how I can do this ?
I have a feeling that this is not going to work, but I really want to learn the way to do it.
This definately is not going to work. For starters, you have two main() methods. Second, if you want to add a class to your Frame, it should extend from JComponent. Basically, your code should look like this:
public class MainFrame extends JFrame {
public MainFrame() {
this.add(new MainPanel())
//insert all settings here.
}
}
public class MainPanel extends JPanel {
public MainPanel() {
this.add(new AddSubtract());
this.add(/*more panels*/)
}
}
public class AddSubtract extends JPanel {
public AddSubtract() {
//add buttons and stuff here
}
}
and variables do NOT start with capitals.
Edit: And when you have some JFrame, it's usually best to have a main() method with just one line:
public static void main(String[] args) {
new MainFrame();
}
just set the settings and configuration of the JFrame in the constructor.

Can't get CardLayout/button ActionListeners to Work

I know it's something to do with how I've set it up and the actionlistener not being correctly set to the frame or something but I just can't get my hear around it. If someone could point me in the right direction I'd be much obliged. Sorry for noob question.
Here's what I have:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Main implements ActionListener {
JPanel cardHolder;
public static final String HOME_CARD = "Home";
public static final String BLUE_PANEL = "Blue Panel";
public static final String RED_PANEL = "Red Panel";
public static final String ORANGE_PANEL = "Orange Panel";
public static JButton home = new JButton("Home");
public static JButton bluePanel = new JButton("Blue Card");
public static JButton redPanel = new JButton("Red Panel");
public static JButton orangePanel = new JButton("Orange Panel");
public static JPanel createCardHolderPanel() {
JPanel cardHolder = new JPanel(new CardLayout());
cardHolder.setBorder(BorderFactory.createTitledBorder("Card Holder Panel"));
cardHolder.add(createHomeCard(), HOME_CARD);
cardHolder.add(createBluePanel(), BLUE_PANEL);
cardHolder.add(createRedPanel(), RED_PANEL);
cardHolder.add(createOrangePanel(), ORANGE_PANEL);
return cardHolder;
}
private static JPanel createOrangePanel() {
JPanel orangePanel = new JPanel();
orangePanel.setBackground(Color.orange);
return orangePanel;
}
private static Component createRedPanel() {
JPanel redPanel = new JPanel();
redPanel.setBackground(Color.red);
return redPanel;
}
private static Component createBluePanel() {
JPanel bluePanel = new JPanel();
bluePanel.setBackground(Color.blue);
return bluePanel;
}
private static Component createHomeCard() {
JPanel homePanel = new JPanel();
homePanel.setBackground(Color.GRAY);
return homePanel;
}
public static JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel(new GridLayout(4, 0, 5, 5));
buttonPanel.setBorder(BorderFactory.createTitledBorder("Button Panel"));
buttonPanel.add(home);
buttonPanel.add(bluePanel);
buttonPanel.add(redPanel);
buttonPanel.add(orangePanel);
return buttonPanel;
}
public static JPanel createContentPane() {
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.setBorder(BorderFactory.createTitledBorder("Main Content Pane"));
contentPane.setBackground(Color.WHITE);
contentPane.setPreferredSize(new Dimension(499, 288));
contentPane.add(createButtonPanel(), BorderLayout.WEST);
contentPane.add(createCardHolderPanel(),BorderLayout.CENTER);
return contentPane;
}
public static JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu file = new JMenu("File");
JMenu users = new JMenu("Users");
JMenu options = new JMenu("Options");
JMenu help = new JMenu("Help");
menuBar.add(file);
menuBar.add(users);
menuBar.add(options);
menuBar.add(help);
return menuBar;
}
public static void createAndShowGUI() {
JFrame frame = new JFrame("Simple CardLayout Program");
frame.setContentPane(createContentPane());
frame.setJMenuBar(createMenuBar());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == home) {
CardLayout cardLayout = (CardLayout) (cardHolder.getLayout());
cardLayout.show(cardHolder, HOME_CARD);
}
if (e.getSource() == bluePanel) {
CardLayout cardLayout = (CardLayout) (cardHolder.getLayout());
cardLayout.show(cardHolder, BLUE_PANEL);
}
if (e.getSource() == redPanel) {
CardLayout cardLayout = (CardLayout) (cardHolder.getLayout());
cardLayout.show(cardHolder, RED_PANEL);
}
if (e.getSource() == orangePanel) {
CardLayout cardLayout = (CardLayout) (cardHolder.getLayout());
cardLayout.show(cardHolder, ORANGE_PANEL);
}
}
}
Others have suggested listening to the buttons; in addition:
Prefer the lowest accessibility consistent with use, e.g. private rather than public.
Don't make everything static.
Use static for immutable constants used throughout the class.
Use class variables rather than static members for content.
Don't repeat your self, e.g. initialize cardLayout just once in your actionPerformed)().
Use parameters rather than separate methods for each color, e.g.
private JPanel createColorPanel(Color color) {...}
Revised code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Main implements ActionListener {
private static final String HOME_CARD = "Home";
private static final String BLUE_PANEL = "Blue Panel";
private static final String RED_PANEL = "Red Panel";
private static final String ORANGE_PANEL = "Orange Panel";
private JPanel cardHolder;
private JButton homeButton = new JButton("Home");
private JButton blueButton = new JButton("Blue Card");
private JButton redButton = new JButton("Red Panel");
private JButton orangeButton = new JButton("Orange Panel");
public JPanel createCardHolderPanel() {
cardHolder = new JPanel(new CardLayout());
cardHolder.setBorder(BorderFactory.createTitledBorder("Card Holder Panel"));
cardHolder.add(createColorPanel(Color.gray), HOME_CARD);
cardHolder.add(createColorPanel(Color.blue), BLUE_PANEL);
cardHolder.add(createColorPanel(Color.red), RED_PANEL);
cardHolder.add(createColorPanel(Color.orange), ORANGE_PANEL);
return cardHolder;
}
private JPanel createColorPanel(Color color) {
JPanel panel = new JPanel();
panel.setBackground(color);
return panel;
}
public JPanel createButtonPanel() {
JPanel buttonPanel = new JPanel(new GridLayout(4, 0, 5, 5));
buttonPanel.setBorder(BorderFactory.createTitledBorder("Button Panel"));
buttonPanel.add(homeButton);
buttonPanel.add(blueButton);
buttonPanel.add(redButton);
buttonPanel.add(orangeButton);
homeButton.addActionListener(this);
blueButton.addActionListener(this);
redButton.addActionListener(this);
orangeButton.addActionListener(this);
return buttonPanel;
}
public JPanel createContentPane() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createTitledBorder("Main Content Pane"));
panel.setBackground(Color.WHITE);
panel.setPreferredSize(new Dimension(499, 288));
panel.add(createButtonPanel(), BorderLayout.WEST);
panel.add(createCardHolderPanel(), BorderLayout.CENTER);
return panel;
}
public JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu file = new JMenu("File");
JMenu users = new JMenu("Users");
JMenu options = new JMenu("Options");
JMenu help = new JMenu("Help");
menuBar.add(file);
menuBar.add(users);
menuBar.add(options);
menuBar.add(help);
return menuBar;
}
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cardLayout = (CardLayout) (cardHolder.getLayout());
if (e.getSource() == homeButton) {
cardLayout.show(cardHolder, HOME_CARD);
}
if (e.getSource() == blueButton) {
cardLayout.show(cardHolder, BLUE_PANEL);
}
if (e.getSource() == redButton) {
cardLayout.show(cardHolder, RED_PANEL);
}
if (e.getSource() == orangeButton) {
cardLayout.show(cardHolder, ORANGE_PANEL);
}
}
public static void createAndShowGUI() {
JFrame frame = new JFrame("Simple CardLayout Program");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Main main = new Main();
frame.setJMenuBar(main.createMenuBar());
frame.add(main.createContentPane());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGUI();
}
});
}
}
You have not set an action listener for any of the buttons. Implementing the actionPerformed method of the interface does not automatically set an action listener for the buttons. You have to call the addActionListener method which in your case would look like the following since your class implements the ActionListener Interface.
public static JButton home = new JButton("Home").addActionListener(this);
public static JButton bluePanel = new JButton("Blue Card").addActionListener(this);
public static JButton redPanel = new JButton("Red Panel").addActionListener(this);
public static JButton orangePanel = new JButton("Orange Panel").addActionListener(this);

Categories

Resources