【发布时间】:2022-01-12 20:13:32
【问题描述】:
您好,我正在尝试使用 JPanel 和 JFrame 创建一个 java 游戏。但是我无法让 JPanel 显示我对其所做的更改。我想知道我是否可能设置错误的 JFrame 或不正确地添加到它或类似的东西。
这是我的窗口类:
import javax.swing.*;
import java.awt.*
public class Window extends Canvas {
public static final int ScreenWidth = 1000;
public static final int ScreenHeight = 700;
public static JFrame frame;
Window(int ScreenWidth, int ScreenHeight, JFrame frame) {
this.frame = frame;
displaywindow();
frame.add(this);
}
public void paint(Graphics g) {
super.paint(g);
}
public void displaywindow() {
this.frame.setPreferredSize(new Dimension(ScreenWidth,ScreenHeight));
this.frame.setMaximumSize(new Dimension(ScreenWidth,ScreenHeight));
this.frame.setMinimumSize(new Dimension(ScreenWidth,ScreenHeight));
this.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.frame.setResizable(false);
this.frame.setBackground(Color.pink);
this.frame.setLocationRelativeTo(null);
}
public JFrame getFrame() {
return this.frame;
}
}
这是我正在处理的 Menu 类:
public class Menu extends JPanel implements ActionListener, KeyListener {
private Window win = new Window(Window.ScreenWidth, Window.ScreenHeight, Window.frame);
private int width = Window.frame.getContentPane().getWidth();
private int height = Window.frame.getContentPane().getHeight();
BufferedImage bg;
Menu(JPanel panel) {
this.panel = panel;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.fillRect(110, 110, 20, 20);
}
public void init() throws IOException {
this.panel.setBackground(Color.cyan);
this.panel.setPreferredSize(new Dimension(width, height));
this.panel.setMaximumSize(new Dimension(width, height));
this.panel.setMinimumSize(new Dimension(width, height));
JLabel start = new JLabel("Start");
start.setFont(new Font("Verdana", Font.PLAIN, 50));
start.setLocation(500, 400);
this.panel.add(new JLabel("Exit"));
this.panel.add(start);
this.panel.revalidate();
this.panel.repaint();
this.panel.setVisible(true);
}
enter code here
public static void main(String[] args) throws IOException {
Window win = new Window(Window.ScreenWidth, Window.HEIGHT, new JFrame());
Menu mene = new Menu();
mene.init();
win.getFrame().getContentPane().add(mene);
win.getFrame().setVisible(true);
}
我尝试向paintComponent 添加一个矩形,以确保面板实际上已添加到框架中并且它显示它确实如此,但我在init() 中所做的任何更改都没有真正显示出来。任何帮助将不胜感激。
`
【问题讨论】:
-
你从来没有真正将菜单面板添加到任何东西。您希望它显示在哪里?
-
1) 不要扩展 Canvas,它是一个 AWT 组件。使用 Swing,您可以扩展 JPanel 以进行自定义绘画。我什至不确定你为什么需要“Window”类。仅在向组件添加功能时才扩展组件。添加组件不是添加功能。 2) 查看Custom Painting 了解自定义绘画的工作示例以及如何使用鼠标在给定位置绘制矩形。工作示例将向您展示如何更好地构建代码。
-
此外,在框架可见之前,组件没有大小。因此,您确定菜单宽度/高度的语句将始终为 0。
-
@Maya 这会将菜单添加到窗口中,但您永远不会将
menupanel添加到init()的菜单中。您在init()中所做的任何更改都不会被显示,因为您没有将在那里创建的任何内容放入正在显示的内容中。 -
阅读 How to Use Card Layout 上的 Swing 教程部分。保留所有 Swing 基础知识的教程链接。