java - 1 个框架上的 3 个面板

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

最佳答案

有几点:

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

与此相同:

JButton card1 = new JButton("Card");
p2.add(card1);

2) 您的类似乎扩展了 JFrame。如果是这样,请删除所有对 JFrame frame = new JFrame(); 的引用。通过使用 frame 变量,您正在创建一个要向其添加面板但不显示的框架。所以到处都是 frame. 删除它。

例子:

frame.setLayout(new BorderLayout());  

成为

setLayout(new BorderLayout());  

3) 我确信您之前提出的一些问题有可接受的答案,或者您自己想出了一个可接受的答案。你可以奖励那些帮助过你的人,或者你可以提供你找到的答案并接受它。然后会有更多人花时间为您提供好的答案。这对你更好,对我们更好,对随机遇到与你有相同问题的人更好。

关于java - 1 个框架上的 3 个面板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13571173/

相关文章:

Java Swing(ActionListener 问题)

java - 自定义 JFileChooser 以将预览器设置在文件列表下方

java - 如何显示所有卡片布局

java - 如何在空自动完成字段中返回 arrayList 的整个值

java - 设置一个变量来维护方法的返回并相应地更新自身

java - 如何保留文件中最长的行,同时保持它们出现的顺序?

java - 相同的 Activity 堆叠

java - 当另一个组件更新时,自定义 JPanel 中出现奇怪的点和线

java - 如何在 JPanel 中绘图? ( Swing/图形Java)

java - 从网站提取数据时出现异常