【问题标题】:Not able to switch cards in cardlayout in single jframe无法在单个 jframe 的卡片布局中切换卡片
【发布时间】:2014-02-18 13:30:20
【问题描述】:

对不起,如果这是一个明显的问题。我一直在尝试使用 cardlayout 在同一个窗口中切换面板。但是当我运行我的应用程序时没有任何反应。 System.out.println(mntmBookingStatus); 上面的语句确实打印在控制台上。但是当我点击菜单项“预订状态”和“发票条目”时,无法弄清楚为什么卡没有切换。

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);

        }

    }

这是我的 JPanelWithBackground 类

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);
}

【问题讨论】:

  • 为什么这么多新手觉得有必要在添加任何组件之前设置框架可见。对我来说如何忽略这种逻辑没有意义:/
  • 回到主题。请发布一个可编译的可运行示例。乍一看,我看不出上面的代码有什么问题。
  • @peeskillet -- 编辑了我的帖子.. 请检查..
  • 为什么是frame.setBounds()?为什么像frame.setLocationByPlatform(true) or frame.setLocationRelativeTo(null) 这样的简单电话就足够了?此外,如果JMenuItemJButton 正在做同样的事情,请使用Actions,以避免冗余代码sn-ps。
  • @nIcEcOw - 感谢您的建议.. 我确实用 setLocationRelativeto(null) 修改了我的代码.. 而且我没有使用按钮来执行类似的菜单操作.. 所以没有使用 Actions.. 虽然该信息很有帮助..如果场景适合,将来会使用它.. :)

标签: java swing jframe jpanel cardlayout


【解决方案1】:

就是这两行

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

由于您的initialize() 方法不是static,我认为假设您在main 方法中实例化您StartDemo 再次 是安全的。在这种情况下,上面的代码确实是你的问题,并且可以完全解释为什么它不起作用。就这样做

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

测试添加代码只是为了让它运行。也请不要我上面的cmets。 setVisible(true) 通常是您添加所有组件之后应该做的最后件事。

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);

            }

        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-21
    • 2016-04-21
    • 2016-10-24
    • 1970-01-01
    • 2021-08-08
    • 2019-12-24
    相关资源
    最近更新 更多