您的代码中有几个问题:
MyFrame
类继承了Frame
,但在实现时却使用了JFrame
。这两者是不同的类,应该保持一致。在创建窗口时,将
panel
添加到了frame
上,但是又将其添加到了panel1
上,而后者并没有被添加到任何地方。因此,在创建窗口时只需将panel
添加到frame
中即可。您使用了 Swing 组件和 AWT 组件混合使用。虽然可以工作,但不建议这样做。建议您改用 Swing 组件来替换 AWT 组件。
修正后的代码如下:
import java.awt.*;
import javax.swing.*;
public class MyFrame {
public static void createAndShow() {
JFrame frame = new JFrame("推箱子游戏");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setBackground(new Color(10, 60, 70));
frame.setResizable(false);
JPanel panel = new JPanel();
panel.setBackground(Color.PINK);
JButton button1 = new JButton("开始游戏");
JButton button2 = new JButton("游戏规则");
JButton button3 = new JButton("选择关卡");
panel.add(button1);
panel.add(button2);
panel.add(button3);
JLabel label = new JLabel();
ImageIcon icon = new ImageIcon("IMG_20230607_191629.jpg");
Image img = icon.getImage().getScaledInstance(300, 150, Image.SCALE_DEFAULT);
icon.setImage(img);
label.setIcon(icon);
JLabel label2 = new JLabel("开始推箱子之旅吧!!!", JLabel.CENTER);
frame.add(label, BorderLayout.PAGE_START);
frame.add(panel, BorderLayout.PAGE_END);
panel.add(label2);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(MyFrame::createAndShow);
}
}