尝试将使用CardLayout的JPanel添加到JFrame

时间:2015-01-22 15:49:23

标签: java swing layout-manager cardlayout

我无法发现错误,当我跑步时,我得到一个空白框架

我正在尝试创建一个applet,其中您看到的第一个屏幕包含4个按钮,每个按钮都需要实现一个,然后一旦单击按钮,它就会转到一个新的面板,其中包含一个图形表示正在排序的数组(我已经在一个较小的applet中完成了这个)

这是我的代码:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class newCLayoutTest extends JPanel{

    private JPanel holderPanel, mainPanel, bubblePanel, selectionPanel, mergePanel, quickPanel;
    private JButton bubbleButton, selectionButton, mergeButton, quickButton;

    private CardLayout cardLayout = new CardLayout();

    public newCLayoutTest()
    {
        JLabel label = new JLabel("Label");
        holderPanel = new JPanel();
        mainPanel = new JPanel();
        bubblePanel = new JPanel();
        selectionPanel = new JPanel();
        mergePanel = new JPanel();
        quickPanel = new JPanel();

        holderPanel.setLayout(cardLayout);

        bubbleButton = new JButton();
        selectionButton = new JButton();
        mergeButton = new JButton();
        quickButton = new JButton();

        //mainPanel.setLayout(new GridLayout(2,2));
        mainPanel.add(bubbleButton);
        mainPanel.add(selectionButton);
        mainPanel.add(mergeButton);
        mainPanel.add(quickButton);

        bubblePanel.add(label);

        holderPanel.add(mainPanel, "1");
        holderPanel.add(bubblePanel, "2");

        cardLayout.show(holderPanel,"2");




    }

}

控制器类:

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class testControl extends JFrame{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable() {


        public void run() {

            newCLayoutTest panel = new newCLayoutTest();
            JFrame frame = new JFrame("LET THIS WORK");

        //  frame.setLayout(new BorderLayout());

            frame.add(panel);
            //frame.getContentPane().add(panel);

            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            frame.setSize(600, 400);
            frame.setVisible(true);
        }
    });
}
}

1 个答案:

答案 0 :(得分:2)

holderPanel尚未添加到包含组件newCLayoutTest

的面板中
add(holderPanel);

请注意,由于您没有向面板添加任何新功能,因此无需继承JPanel。您只需创建一个面板并添加组件即可。也遵循Java命名约定,即对类名使用大写的首字母,例如: NewCLayoutTest