我在将三个不同的面板放在框架顶部时遇到了真正的麻烦,因为我需要在每个面板上有不同的布局。我似乎无法让它工作,我已经连续尝试了 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/