1

Sorry if its an obvious question.I have been trying to switch panels in the same window using cardlayout.But when i run my application nothing happens. System.out.println(mntmBookingStatus); the above statement does get printed on console.but not able to make out why cards arent switching when i click on menuitem "booking status" and "invoice entry".

public class StartDemo {
private JFrame frame;
private JPanel cards = new JPanel(new CardLayout());
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                StartDemo window = new StartDemo();
                window.initialize();
                window.frame.pack();
                window.frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}
private void initialize() {
    frame = new JFrame();
    frame.setBounds(100, 100, 772, 700);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //frame.setVisible(true);
    // main menu
    menuBar = new JMenuBar();
    frame.setJMenuBar(menuBar);

    // mainmenuoption-1
    mnNewMenu = new JMenu("Entries");
    menuBar.add(mnNewMenu);

    // option-1 items
    mntmBookingStatus = new JMenuItem("Booking Status");
    mnNewMenu.add(mntmBookingStatus);
    mntmBookingStatus.addActionListener(new MenuListenerAdapter());

mntmInvoiceEntry = new JMenuItem("Invoice Entry");
mnNewMenu.add(mntmInvoiceEntry);
mntmInvoiceEntry.addActionListener(new MenuListenerAdapter());
StartDemo demo = new StartDemo();
    demo.addComponentToPane(frame.getContentPane());

}

public void addComponentToPane(Container pane) {
JPanel booking_status = new JPanel();
    JPanel invoice_entry = new JPanel();
    JPanel customer_ledger = new JPanel();
    JPanel create_user = new JPanel();

    try {

        JPanelWithBackground panelWithBackground = new       JPanelWithBackground(
                "D:\\Kepler Workspace\\WEDemo\\images\\abc.jpg");
        cards.add(panelWithBackground, "name_282751308799");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

 //the layout code for all the panels is written here.
//its to big to post here

cards.add(booking_status, BOOKINGPANEL);
    cards.add(invoice_entry, INVOICEPANEL);
    cards.add(customer_ledger, CUSTOMERLEDGER);
    cards.add(create_user, CREATEUSER);

    pane.add(cards, BorderLayout.CENTER);

}

public class MenuListenerAdapter implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {

        CardLayout c = (CardLayout) (cards.getLayout());

        if (e.getSource() == mntmBookingStatus) {
            c.show(cards, BOOKINGPANEL);
            System.out.println(mntmBookingStatus);

        } else if (e.getSource() == mntmInvoiceEntry) {
            c.show(cards, INVOICEPANEL);
            System.out.println(mntmInvoiceEntry);

        }

    }

This is my JPanelWithBackground class

public class JPanelWithBackground extends JPanel {

private Image backgroungImage;
private Image scaledBackgroundImage;


  // Some code to initialize the background image.
  // Here, we use the constructor to load the image. This
  // can vary depending on the use case of the panel.

public JPanelWithBackground(String fileName) throws IOException {
    backgroungImage = ImageIO.read(new File(fileName));
}


public void paintComponent(Graphics g){
    super.paintComponent(g);

    // Draw the backgroung image
    g.drawImage(backgroungImage, 0, 0,getWidth(),getHeight(),null);
}
sanedroid
  • 1,036
  • 4
  • 16
  • 27
  • 1
    Why do so many newbs feel like it's necessary to set the frame visible before adding any components. Doesn't make sense to me how such logic could be overlooked :/ – Paul Samsotha Feb 18 '14 at 13:39
  • Back on topic. Please post a compilable runnable example. From first glance, I don't see much wrong with the code above. – Paul Samsotha Feb 18 '14 at 13:41
  • @peeskillet -- have edited my post.. Please check.. – sanedroid Feb 18 '14 at 13:49
  • 1
    Why `frame.setBounds()`? Why not a simple call like `frame.setLocationByPlatform(true) or frame.setLocationRelativeTo(null)` is enough? Moreover, use [Actions](http://docs.oracle.com/javase/tutorial/uiswing/misc/action.html), if the `JMenuItem` as well as the `JButton` are doing the same thingy, to avoid redundant code snippets. – nIcE cOw Feb 18 '14 at 13:54
  • 1
    @nIcEcOw - thanx for your suggestions.. i did modified my code with setLocationRelativeto(null).. and also i am not using buttons to perform similar menu actions.. so havent used Actions.. though the information was helpful.. would use it in future if the scenario suits.. :) – sanedroid Feb 19 '14 at 10:04
  • @user3061692 : You're MOST WELCOME and KEEP SMILING :-) Do have a look at this post, regarding how to [Best position Swing GUIs](http://stackoverflow.com/q/7143287/1057230), for making a choice between which of the two methods should be selected :-) – nIcE cOw Feb 19 '14 at 13:02

1 Answers1

1

It's these two lines right here

 StartDemo demo = new StartDemo();
 demo.addComponentToPane(frame.getContentPane());

Since your initialize() method isn't static I think it's safe to assume that you instantiate youe StartDemo again in the main method. In that case, the above code truly is your problem and would totally explain why it doesn't work. Just do this

 //StartDemo demo = new StartDemo();          <-- get rid of this.
 addComponentToPane(frame.getContentPane());

Tested with code additions only to get it running. Also please not my comments above. setVisible(true) generally is the last thing you should do after adding all components.

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class StartDemo {

    private JFrame frame;
    private JPanel cards = new JPanel(new CardLayout());
    JMenuBar menuBar;
    JMenu mnNewMenu;
    JMenuItem mntmBookingStatus;
    JMenuItem mntmInvoiceEntry;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                new StartDemo().initialize();
            }
        });
    }

    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 772, 700);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        // main menu
        menuBar = new JMenuBar();
        frame.setJMenuBar(menuBar);

        // mainmenuoption-1
        mnNewMenu = new JMenu("Entries");
        menuBar.add(mnNewMenu);

        // option-1 items
        mntmBookingStatus = new JMenuItem("Booking Status");
        mnNewMenu.add(mntmBookingStatus);
        mntmBookingStatus.addActionListener(new MenuListenerAdapter());

        //StartDemo demo = new StartDemo();
        addComponentToPane(frame.getContentPane()); mntmInvoiceEntry = new JMenuItem("Invoice Entry");
        mnNewMenu.add(mntmInvoiceEntry);
        mntmInvoiceEntry.addActionListener(new MenuListenerAdapter());

        frame.setVisible(true);

    }

    public void addComponentToPane(Container pane) {
        JPanel booking_status = new JPanel();
        JPanel invoice_entry = new JPanel();
        //JPanel customer_ledger = new JPanel();
        //JPanel create_user = new JPanel();

        try {

            JPanelWithBackground panelWithBackground = new JPanelWithBackground(
                    "/resources/stackoverflow5.png");
            cards.add(panelWithBackground, "name_282751308799");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        cards.add(booking_status, "booking");
        cards.add(invoice_entry, "invoice");
        //cards.add(customer_ledger, CUSTOMERLEDGER);
        //cards.add(create_user, CREATEUSER);

        pane.add(cards, BorderLayout.CENTER);

    }


    class JPanelWithBackground extends JPanel {
        Image img; 
        public JPanelWithBackground(String path) throws IOException {
            img = ImageIO.read(getClass().getResource(path));
        }

        @Override 
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(300, 300);
        }
    }

    public class MenuListenerAdapter implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {

            CardLayout c = (CardLayout) (cards.getLayout());

            if (e.getSource() == mntmBookingStatus) {
                c.show(cards,"booking");
                System.out.println(mntmBookingStatus);

            } else if (e.getSource() == mntmInvoiceEntry) {
                c.show(cards, "invoice");
                System.out.println(mntmInvoiceEntry);

            }

        }
    }
}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720