3个面板ontop 1框架

use*_*127 1 java swing

我在将三个不同的面板放在框架顶部时遇到了麻烦,因为我需要在每个面板上放置不同的布局.我似乎无法让它工作,我已经连续4天尝试了.我无法在此代码中找到我出错的地方.

我这样做是最好的方式吗?任何想法或帮助将不胜感激!!!!!

我的代码:

    public Mem() {
    super("3 panels on 1 frame");       

    JFrame frame = new JFrame();

    setSize(500, 500);      
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    JPanel p1 = new JPanel();
    JPanel p2 = new JPanel();
    JPanel p3 = new JPanel();

    //Adding three different panels with borderlayout
    frame.setLayout(new BorderLayout());  

    //Panel 1 is the Player Panel with labels
    JLabel ply1 = new JLabel("Player 1");
    JLabel ply2 = new JLabel("Player 2");
    JLabel ply3 = new JLabel("Player 3");
    JLabel ply4 = new JLabel("Player 4");
    p1.add(ply1); p1.add(ply2); p1.add(ply3); p1.add(ply4);

    //Panel 2 is the game panel with playingcards on it. (Clickable buttons)
    JButton card1 = new JButton("Card");
    p2.add(card1); p2.add(card1); p2.add(card1); p2.add(card1); p2.add(card1); p2.add(card1); p2.add(card1);
    p2.add(card1); p2.add(card1); p2.add(card1); p2.add(card1); p2.add(card1); p2.add(card1); p2.add(card1);

    //Panel 3 is the lower panel with the buttons new game & close on it. 
    JButton newGame = new JButton("New Game");
    newGame.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            startGame();
        }
    });
    JButton endGame = new JButton("Close");
    endGame.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            closeGame();
        }
    });
    p3.add(newGame);  
    p3.add(endGame);


    frame.add(p1, BorderLayout.EAST);  
    frame.add(p2, BorderLayout.CENTER);  
    frame.add(p3, BorderLayout.SOUTH);

    setVisible(true);   
}
Run Code Online (Sandbox Code Playgroud)

Nic*_*ppe 5

有几件事:

1)您多次添加一个swing组件将不会复制它 - 它将被删除并添加到新位置.所以这:

JButton card1 = new JButton("Card");
p2.add(card1); p2.add(card1); p2.add(card1); p2.add(card1); p2.add(card1); p2.add(card1); p2.add(card1);
p2.add(card1); p2.add(card1); p2.add(card1); p2.add(card1); p2.add(card1); p2.add(card1); p2.add(card1);
Run Code Online (Sandbox Code Playgroud)

与此相同:

JButton card1 = new JButton("Card");
p2.add(card1);
Run Code Online (Sandbox Code Playgroud)

2)你的班级似乎延伸了JFrame.如果是,请删除所有这些引用JFrame frame = new JFrame();.通过使用frame变量,您将创建一个框架,您正在添加面板,但不显示.所以你看到的每个地方都frame.删除它

例:

frame.setLayout(new BorderLayout());  
Run Code Online (Sandbox Code Playgroud)

setLayout(new BorderLayout());  
Run Code Online (Sandbox Code Playgroud)

3)我确定你之前提出的一些问题有可接受的答案,或者你自己想出了一个可接受的答案.您可以奖励那些人帮助,或者您可以提供您找到的答案并接受.然后会有更多人花时间为您提供一个好的答案.这对你来说更好,对我们来说更好,对于那个跟你一样问题的随机人来说更好.