感谢您提供有关Frame未显示原因的建议。我现在用以下代码显示内容(在main方法的子类中没有任何扩展,尽管具有main方法的类扩展了JPanel),但不正确:
case start:
JPanel mapFrame = new JPanel();
mapFrame.setPreferredSize(new Dimension(950, 950));
mapFrame.setBackground(Color.CYAN);
mapFrame.setVisible(true);
mapFrame.add(new Main());
JPanel statBar = new JPanel();
statBar.setBackground(Color.BLACK);
statBar.setPreferredSize(new Dimension(400, 950));
JFrame fullBox = new JFrame();
fullBox.getContentPane().setLayout(new BorderLayout());
fullBox.setPreferredSize(new Dimension(1350, 950));
fullBox.getContentPane().add(statBar, BorderLayout.EAST);
fullBox.getContentPane().add(mapFrame, BorderLayout.WEST);
fullBox.setResizable(true);
fullBox.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fullBox.setVisible(true);
fullBox.pack();
以前,我有以下代码,而不是我上面包含的代码(在main方法的子类中),它完美地显示了背景图像和播放器,其位置通过键输入更新:
case start:
JFrame mapFrame = new JFrame();
mapFrame.pack();
mapFrame.setSize(1350, 1000);
mapFrame.setResizable(false);
mapFrame.setLocationRelativeTo(null);
mapFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mapFrame.add(new Main());
mapFrame.setVisible(true);
我对背景和播放器的绘制方法如下(在扩展JPanel的类中):
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(getBackgroundImage(), 0, 0, this);
((Penguin)player).draw(g2d);
public BufferedImage getBackgroundImage(){
ImageIcon i = new ImageIcon(getClass().getResource(background));
Image image = i.getImage();
BufferedImage scaledImage = new BufferedImage(950, 950, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = scaledImage.createGraphics();
g2.drawImage(image, 0, 0, 950, 950, null);
g2.dispose();
return scaledImage;
}
fullBox Frame需要连续重新绘制,因为mapFrame包含玩家角色和要收集的点,而statBar稍后将包含也将更新时间和点数的文本。我尝试删除mapFrame的背景颜色,它只是JPanel的默认颜色。当我包含颜色时,有一个小的白色盒子固定在青色上方的位置 - 有点奇怪。
答案 0 :(得分:0)
class MenuActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
switch (e.getActionCommand()) {
case startGame:
JFrame fullBox = new JFrame();
fullBox.getContentPane().setLayout(new BorderLayout());
JPanel mapFrame = new JPanel();
mapFrame.setSize(950, 950);
mapFrame.setVisible(true);
mapFrame.add(new Main());
fullBox.getContentPane().add(mapFrame, BorderLayout.WEST);
JPanel statBar = new JPanel();
statBar.setSize(400, 950);
fullBox.getContentPane().add(statBar, BorderLayout.EAST);
fullBox.setResizable(false);
fullBox.setLocationRelativeTo(null);
fullBox.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fullBox.pack();
fullBox.setVisible(true);
break;
case loadLog:
System.out.println("load game");
break;
case aboutGame:
System.out.println("about game");
break;
case exitGame:
System.out.println("exit game");
System.exit(0);