问题
i have two Panels and want them to be shown in my JFrame, but when i try it like this, i can only see the second one. Can someone please help me? :(
import javax.swing.JFrame;
public class MainWindow {
CardLayout layout;
JFrame frame;
Player panel1;
Block panel2;
public MainWindow() {
frame = new JFrame("Rechteck");
panel1 = new Player();
panel2 = new Block();
panel1.addKeyListener(new KeyListen(panel1));
frame.add(panel1);
frame.add(panel2);
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}}
回答1:
You have added both your panels to the BorderLayout.CENTER
of your JFrame
—only one can occupy that location,. This will be the last one added, panel2
in this case.
To allow the panels occupy the space evenly, you could use GridLayout
:
frame.setLayout(new GridLayout(2, 1));
Aside: Better to use Key Bindings when registering key events for components in Swing.
回答2:
Create a JPanel add that to the JFrame. Add panel1 and panel2 to the new panel. JFrame can only have one child, usually set by calling JFrame.setContentPane().
来源:https://stackoverflow.com/questions/14203714/two-panels-in-one-jframe