I want to have a menu bar in my GUI. The menu is not visible.
public class GUI extends JPanel implements ItemListener{
final static String RUN_TEST = "Test 4G";
final static String SETTINGS = "Settings";
JPanel p;
JPanel cards = new JPanel(new CardLayout());
public GUI(){
JFrame window = new JFrame();
TestRun runTest = new TestRun();
cards.add(runTest , RUN_TEST);
cards.add(runTest , SETTINGS);
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, RUN_TEST);
window.setContentPane(cards);
window.pack();
window.setVisible(true);
}
#Override
public void itemStateChanged(ItemEvent evt) {
CardLayout cl = (CardLayout)(cards.getLayout());
cl.show(cards, (String)evt.getItem());
}
}
How can I show to the user the menu "Test 4G" and "settings" so that they can change the JPanel?
Thanks for your help
This is an example of using JMenuBar in JFrame and JPopupMenu in JPanel (view).
public class MainFrame extends JFrame {
final static String RUN_TEST = "Test 4G";
final static String SETTINGS = "Settings";
private JPanel viewPanel = new JPanel();
public MainFrame() throws HeadlessException {
super("MainFrame");
cretaeGUI();
}
private void cretaeGUI() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLayout(new BorderLayout());
setJMenuBar(cretaeMenuBar());
setMinimumSize(new Dimension(800, 600));
viewPanel.setLayout(new CardLayout());
viewPanel.add(new Test4GView(this), RUN_TEST);
viewPanel.add(new SettingsView(this), SETTINGS);
add(viewPanel, BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
}
private JMenuBar cretaeMenuBar() {
JMenuItem testMenuItem = new JMenuItem("Test 4G");
testMenuItem.addActionListener(this::showTest4GView);
JMenuItem settingsMenuItem = new JMenuItem("Settings");
settingsMenuItem.addActionListener(this::showSettingsView);
JMenu viewMenu = new JMenu("View");
viewMenu.add(testMenuItem);
viewMenu.add(settingsMenuItem);
JMenuBar menuBar = new JMenuBar();
menuBar.add(viewMenu);
return menuBar;
}
private void showView(String name) {
((CardLayout)viewPanel.getLayout()).show(viewPanel, name);
}
public void showTest4GView(ActionEvent event) {
showView(RUN_TEST);
}
public void showSettingsView(ActionEvent event) {
showView(SETTINGS);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MainFrame().setVisible(true));
}
}
аnd these are both views
public class Test4GView extends JPanel {
private MainFrame mainFrame;
public Test4GView(MainFrame mainFrame) {
this.mainFrame = mainFrame;
add(new JLabel("Test 4G"));
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
showPopupMenu(e);
}
#Override
public void mouseReleased(MouseEvent e) {
showPopupMenu(e);
}
private void showPopupMenu(MouseEvent e) {
if(!e.isPopupTrigger()) {
return;
}
JMenuItem showSettingsView = new JMenuItem("Settings");
showSettingsView.addActionListener(mainFrame::showSettingsView);
JPopupMenu popupMenu = new JPopupMenu();
popupMenu.add(showSettingsView);
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
});
}
}
public class SettingsView extends JPanel {
private MainFrame mainFrame;
public SettingsView(MainFrame mainFrame) {
this.mainFrame = mainFrame;
add(new JLabel("Settings"));
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
showPopupMenu(e);
}
#Override
public void mouseReleased(MouseEvent e) {
showPopupMenu(e);
}
private void showPopupMenu(MouseEvent e) {
if(!e.isPopupTrigger()) {
return;
}
JMenuItem showSettingsView = new JMenuItem("Test 4G");
showSettingsView.addActionListener(mainFrame::showTest4GView);
JPopupMenu popupMenu = new JPopupMenu();
popupMenu.add(showSettingsView);
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
});
}
}
Related
I have a question regarding custom tab components in swing.
The following code will add 3 custom tab components:
public class TabbedExample extends JPanel {
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
#Override public void run() {
createUI();
}
}
}
public static void createUI() {
try {
for(LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch(Exception e) {}
JFrame frame = new JFrame("Tab Test");
frame.setMinimumSize(new Dimension(256,200));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new TabbedExample());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public TabbedExample() {
super(new BorderLayout());
JTabbedPane pane = new JTabbedPane();
pane.addTab("tmp", new JTextField());
pane.addTab("tmp", new JTextField());
pane.addTab("tmp", new JTextField());
for(int i = 0; i < 3; i++) {
JPanel tabPanel = new JPanel();
tabPanel.setBackground(new Color(0,0,0,0));
tabPanel.setLayout(new BoxLayout(tabPanel, BoxLayout.X_AXIS));
JTextField textField = new JTextField("Tab " + i);
textField.setOpaque(false);
textField.setBackground(new Color(0,0,0,0));
textField.setBorder(new EmptyBorder(0,0,0,0));
tabPanel.add(label);
tabPanel.add(new JButton(Integer.toString(i)));
pane.setTabComponentAt(i, tabPanel);
}
add(pane, BorderLayout.CENTER);
}
}
the problem now is that the default tab behaviour stops working. normally, when you move your mouse over a tab, it automagically gets highlight by changing the background color. but as soon as the JTextField is hit, the tab most likely registers a mouseExited Event and stops the highlighting of the tab. so the tab will flicker when you move your mouse over the tab.
my question now is:
Is there a way (without implementing a new highlighting mechanism) to highlight the tab, where the custom tabComponent is located?
Here's my attempt:
Using a JLayer to dispatch the MouseMotionEvent from the tabs to the parent JTabbedPane:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.plaf.*;
public class TabbedExample2 extends JPanel {
public static void main(String... args) {
EventQueue.invokeLater(() -> {
createUI();
});
}
public static void createUI() {
try {
for (UIManager.LookAndFeelInfo laf: UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(laf.getName())) {
UIManager.setLookAndFeel(laf.getClassName());
}
}
} catch (Exception e) {
e.printStackTrace();
}
JFrame frame = new JFrame("Tab Test");
frame.setMinimumSize(new Dimension(256, 200));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new TabbedExample2());
frame.setSize(320, 240);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public TabbedExample2() {
super(new BorderLayout());
JTabbedPane pane = new JTabbedPane();
pane.addTab("tmp", new JTextField(16));
pane.addTab("tmp", new JTextField(16));
pane.addTab("tmp", new JTextField(16));
for (int i = 0; i < 3; i++) {
JPanel tabPanel = new JPanel();
tabPanel.setOpaque(false);
//tabPanel.setBackground(new Color(0,0,0,0));
tabPanel.setLayout(new BoxLayout(tabPanel, BoxLayout.X_AXIS));
JTextField textField = new JTextField("Tab " + i);
//textField.setBackground(new Color(0,0,0,0));
//textField.setBorder(new EmptyBorder(0,0,0,0));
//tabPanel.add(label); //???
tabPanel.add(textField);
tabPanel.add(new JButton(Integer.toString(i)));
pane.setTabComponentAt(
i, new JLayer<JPanel>(tabPanel, new DispatchEventLayerUI()));
}
add(pane);
}
}
class DispatchEventLayerUI extends LayerUI<JPanel> {
#Override
public void installUI(JComponent c) {
super.installUI(c);
if (c instanceof JLayer) {
((JLayer) c).setLayerEventMask(AWTEvent.MOUSE_MOTION_EVENT_MASK);
//TEST:
//((JLayer) c).setLayerEventMask(
// AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK);
}
}
#Override
public void uninstallUI(JComponent c) {
if (c instanceof JLayer) {
((JLayer) c).setLayerEventMask(0);
}
super.uninstallUI(c);
}
// //TEST:
// #Override
// protected void processMouseEvent(MouseEvent e, JLayer<? extends JPanel> l) {
// dispatchEvent(e);
// }
#Override
protected void processMouseMotionEvent(MouseEvent e, JLayer<? extends JPanel> l) {
dispatchEvent(e);
}
private void dispatchEvent(MouseEvent e) {
Component src = e.getComponent();
Container tgt = SwingUtilities.getAncestorOfClass(JTabbedPane.class, src);
tgt.dispatchEvent(SwingUtilities.convertMouseEvent(src, e, tgt));
}
}
I am using a self made toolbar to navigate through my application and the toolbar is present on all pages. Each time a new page is displayed I am closing the current frame and opening a new one, using the following code:
java.awt.Window win[] = java.awt.Window.getWindows();
for(int i=0;i<win.length;i++){
win[i].dispose();
}
I am doing it this way as the ActionListeners are declared in the toolbar class, whilst the frames for each page are declared at runtime and are not static.
This all works fine except for one particular case-the "cancel" button, where the first time the frame is accessed it will close once. The second time it will close and re open 2 times, the third 3 and so on. I have tracked this using the "counter" in the code.
I have minimised the code to recreate the same behaviour, as below:
Toolbar Class
public class Toolbar {
static JButton buttonCancel = new JButton("Cancel");
static int counter;
public static JPanel Toolbar(String panelname){
FlowLayout layout = new FlowLayout();
JPanel Toolbar = new JPanel(new BorderLayout());
Toolbar.setLayout(layout);
GridLayout GLayout = new GridLayout(2,1);
GLayout.setVgap(0);
JPanel container2 = new JPanel();
if(panelname.matches("Customers")){
container2.setLayout(GLayout);
JButton buttonAddCust = new JButton("Add Cust");
container2.add(buttonAddCust, BorderLayout.PAGE_START);
buttonAddCust.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
java.awt.Window win[] = java.awt.Window.getWindows();
for(int i=0;i<win.length;i++){
win[i].dispose();
}
Customers.AddCustomersGui();
}
});
}
JPanel container21 = new JPanel();
if(panelname.matches("Add Customers")){
container21.setLayout(GLayout);
container21.add(buttonCancel, BorderLayout.PAGE_START);
buttonCancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
counter ++;
java.awt.Window win[] = java.awt.Window.getWindows();
for(int i=0;i<win.length;i++){
win[i].dispose();
}
System.out.println("Coutner " + counter);
Customers.CustomersGui();
}
});
}
Toolbar.add(container2);
Toolbar.add(container21);
return Toolbar;
}
}
GUI class
public class Customers extends Toolbar{
public static void CustomersGui(){
final JFrame frame = new JFrame("Customers");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel customers = new JPanel();
customers.add(Toolbar.Toolbar(frame.getTitle()));
frame.setContentPane(customers);
frame.setSize(1200,500);
frame.setVisible(true);
}
public static void AddCustomersGui(){
final JFrame frame1 = new JFrame("Add Customers");
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel Addcustomers = new JPanel();
Addcustomers.add(Toolbar.Toolbar(frame1.getTitle()));
frame1.setContentPane(Addcustomers);
frame1.setSize(1200,500);
frame1.setVisible(true);
}
}
main class
public static void main(String[] args) {
Customers.CustomersGui();
}
You are adding a new ActionListener to the buttonCancel, with each iteration of your code and this is the reason for your program's behavior.
Also, as per my comment, you state,
Each time a new page is displayed I am closing the current frame and opening a new one.
A better design is probably not to swap windows which can be annoying, but rather to swap JPanel views using a CardLayout. Please read The Use of Multiple JFrames, Good/Bad Practice?.
For example, add this line of code to your program:
if (panelname.matches("Add Customers")) {
container21.setLayout(GLayout);
container21.add(buttonCancel, BorderLayout.PAGE_START);
buttonCancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
counter++;
java.awt.Window win[] = java.awt.Window.getWindows();
for (int i = 0; i < win.length; i++) {
win[i].dispose();
}
System.out.println("Coutner " + counter);
Customers.CustomersGui();
}
});
// ***** add this here **********
System.out.println("buttonCancel ActionListener count: "
+ buttonCancel.getListeners(ActionListener.class).length);
}
and you'll see that the ActionListeners get added multiple times to this button.
An example of swapping views:
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class SwapPanels extends JPanel {
public static final String CUSTOMER = "customer";
public static final String ADD_CUSTOMER = "Add Customer";
protected static final int PREF_W = 800;
protected static final int PREF_H = 600;
public static final String CANCEL = "Cancel";
private CardLayout cardLayout = new CardLayout();
public SwapPanels() {
setLayout(cardLayout);
add(createCustomerPanel(CUSTOMER), CUSTOMER);
add(createAddCustomerPanel(ADD_CUSTOMER), ADD_CUSTOMER);
}
public void showCard(String key) {
cardLayout.show(this, key);
}
public JPanel createAddCustomerPanel(String name) {
JPanel addCustPanel = new JPanel() {
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
};
addCustPanel.setName(name);
addCustPanel.setBorder(BorderFactory.createTitledBorder(name));
addCustPanel.add(new JButton(new AbstractAction(CANCEL) {
{
int mnemonic = (int)getValue(NAME).toString().charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
if (CANCEL.equals(e.getActionCommand())) {
SwapPanels.this.showCard(CUSTOMER);
}
}
}));
return addCustPanel;
}
private JPanel createCustomerPanel(String name) {
JPanel custPanel = new JPanel() {
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
};
custPanel.setName(name);
custPanel.setBorder(BorderFactory.createTitledBorder(name));
custPanel.add(new JButton(new AbstractAction(ADD_CUSTOMER) {
{
int mnemonic = (int)getValue(NAME).toString().charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
if (ADD_CUSTOMER.equals(e.getActionCommand())) {
SwapPanels.this.showCard(ADD_CUSTOMER);
}
}
}));
return custPanel;
}
private static void createAndShowGui() {
JFrame frame = new JFrame("SwapPanels");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new SwapPanels());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I'm using webcam-capture libraries and AWT to develop a simple interface for taking pictures from a webcam. The buttons and the combobox in my JFrame disappear after minimizing the window or after moving another window on top of it. Moving the pointer over the frame restores the components' visibility. I'm not skilled with Java UI, I can't figure out what's wrong with my code.
#SuppressWarnings("serial")
public class ImageCaptureManager extends JFrame {
private class SkipCapture extends AbstractAction {
public SkipCapture() {
super(“Skip”);
}
#Override
public void actionPerformed(ActionEvent e) {
/*SOME CODE HERE*/
}
}
private class SnapMeAction extends AbstractAction {
public SnapMeAction() {
super(“Snap”);
}
#Override
public void actionPerformed(ActionEvent e) {
/*SOME CODE HERE*/
}
}
private class captureCompleted extends AbstractAction {
public captureCompleted() {
super(“Completed”);
}
#Override
public void actionPerformed(ActionEvent e) {
/*SOME CODE HERE*/
}
}
private class saveImage extends AbstractAction {
public saveImage() {
super(“Save”);
}
#Override
public void actionPerformed(ActionEvent e) {
/*SOME CODE HERE*/
}
}
private class deleteImage extends AbstractAction {
public deleteImage() {
super(“Delete”);
}
#Override
public void actionPerformed(ActionEvent e) {
/*SOME CODE HERE*/
}
}
private class StartAction extends AbstractAction implements Runnable {
public StartAction() {
super(“Start”);
}
#Override
public void actionPerformed(ActionEvent e) {
btStart.setEnabled(false);
btSnapMe.setEnabled(true);
executor.execute(this);
}
#Override
public void run() {
panel.start();
}
}
private Executor executor = Executors.newSingleThreadExecutor();
private Dimension captureSize = new Dimension(640, 480);
private Dimension displaySize = new Dimension(640, 480);
private Webcam webcam = Webcam.getDefault();
private WebcamPanel panel;
private JButton btSnapMe = new JButton(new SnapMeAction());
private JButton btStart = new JButton(new StartAction());
private JButton btComplete = new JButton(new captureCompleted());
private JButton btSave = new JButton(new saveImage());
private JButton btDelete = new JButton(new deleteImage());
private JButton btSkip = new JButton(new SkipCapture());
private JComboBox comboBox = new JComboBox();
public ImageCaptureManager() {
super(“Frame”);
this.addWindowListener( new WindowAdapter()
{
#Override
public void windowDeiconified(WindowEvent arg0) {
}
public void windowClosing(WindowEvent e)
{
}
});
List<Webcam> webcams = Webcam.getWebcams();
for (Webcam webcam : webcams) {
System.out.println(webcam.getName());
if (webcam.getName().startsWith("USB2.0 Camera 1")) {
this.webcam = webcam;
break;
}
}
panel = new WebcamPanel(webcam, displaySize, false);
webcam.setViewSize(captureSize);
panel.setFPSDisplayed(true);
panel.setFillArea(true);
btSnapMe.setEnabled(false);
btSave.setEnabled(false);
btDelete.setEnabled(false);
setLayout(new FlowLayout());
Panel buttonPanel = new Panel();
buttonPanel.setLayout(new GridLayout(10, 1));
buttonPanel.add(Box.createHorizontalStrut(20));
buttonPanel.add(btSnapMe);
buttonPanel.add(Box.createHorizontalStrut(20));
buttonPanel.add(btSave);
buttonPanel.add(Box.createHorizontalStrut(20));
buttonPanel.add(btDelete);
buttonPanel.add(Box.createHorizontalStrut(20));
buttonPanel.add(btComplete);
buttonPanel.add(Box.createHorizontalStrut(20));
buttonPanel.add(btSkip);
JLabel label1 = new JLabel("Test");
label1.setText(“Bla bla bla”);
JLabel label2 = new JLabel("Test");
label2.setText(" ");
Panel captionAndWebcamPanel = new Panel();
captionAndWebcamPanel.add(label1);
captionAndWebcamPanel.add(label2);
captionAndWebcamPanel.add(panel);
captionAndWebcamPanel.add(label2);
captionAndWebcamPanel.add(comboBox);
captionAndWebcamPanel.setLayout(new BoxLayout(captionAndWebcamPanel, BoxLayout.Y_AXIS));
add(captionAndWebcamPanel);
add(buttonPanel);
pack();
setVisible(true);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
btStart.doClick();
setSize(900,600);
}
}
You are mixing AWT and Swing components.
"Historically, in the Java language, mixing heavyweight and lightweight components in the same container has been problematic."
http://www.oracle.com/technetwork/articles/java/mixing-components-433992.html
I suggest you try using JPanels instead of Panels for captionAndWebcamPanel and buttonPanel, I'd also set layout to captionAndWebcamPanel before adding components.
I have problem with this code
when I click on file and click on new ,new panel comes to screen and when I want to change JRadioBox status to change Label status,Label status changes but also the panel goes away :(
public class MainClass {
public static void main(String[] args) {
new MainFrame();
}
}
class Toolbar extends JPanel {
private JRadioButton Status1;
private JRadioButton Status2;
private ButtonGroup radioButtonGroup;
public Toolbar() {
super();
setLayout(new FlowLayout());
Status1 = new JRadioButton("Status1");
Status2 = new JRadioButton("Status2");
radioButtonGroup = new ButtonGroup();
radioButtonGroup.add(Status2);
radioButtonGroup.add(Status1);
Status1.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
MainFrame m = new MainFrame();
m.l.setText("Status1");
}
});
Status2.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
MainFrame m = new MainFrame();
m.l.setText("Status2");
}
});
add(Status1);
add(Status2);
}
}
class Panel extends JPanel {
public Panel() {
super();
setBackground(Color.MAGENTA);
}
}
class MenuBar extends JMenuBar {
private JMenu menu;
private JMenuItem fileItems;
public boolean panel = false;
public MenuBar() {
super();
menu = new JMenu("File");
add(menu);
fileItems = new JMenuItem("New");
menu.add(fileItems);
fileItems.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
MainFrame mf = new MainFrame();
Panel p = new Panel();
mf.addPanel(p);
mf.add(new Toolbar(), BorderLayout.NORTH);
repaint();
}
});
}
}
class MainFrame extends JFrame {
public static JLabel l;
public MainFrame() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400, 400);
l = new JLabel("No Status");
add(l, BorderLayout.SOUTH);
MenuBar mb = new MenuBar();
setJMenuBar(mb);
setVisible(true);
}
public void addPanel(Panel p) {
add(p, BorderLayout.CENTER);
}
}
Stop making new MainFrames all over the place. Create it once and maintain a handle to it for whenever you need it.
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);