我的应用程序不是面向 JFrame 的,它只使用一个用于输出。我只需要能够告诉它在这里画一个矩形,现在清除屏幕,几百次。为此,我在 main 中编写了以下代码,根据我的理解,它应该将整个 JFrame 清除为漂亮的蓝色背景色。
JFrame frame = new JFrame("Maze Master Premium Super-Deluxe V199.39");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int resolution = 20;
int frameWidth = horiz * resolution;
int frameHeight = vert * resolution;
frame.setMinimumSize(new Dimension(frameWidth, frameHeight));
frame.setSize(frameWidth, frameHeight);
frame.pack();
frame.setVisible(true);
frame.toFront();
Graphics g = frame.getGraphics();
g.setPaintMode();
g.setColor(Color.BLUE);
//Clear background
g.fillRect(0, 0, frameWidth, frameHeight);
frame.update(g);
但是当我运行它时,JFrame 以其默认的浅灰色背景色显示。我是否必须让我的类扩展 JFrame,或者使用 frame.update(g) 就足够了,我只是遇到了其他问题?
最佳答案
从您的问题中,很难准确理解您要实现的目标。您只是想更改框架的背景颜色还是执行一些自定义绘画???
这个 Graphics g = frame.getGraphics()
从来都不是一个好主意。除了 getGraphics
可能返回 null
之外,图形在 Java 中是无状态的,这意味着您用来绘制的图形上下文可能会在绘制周期之间发生变化,您永远不应该依赖或维护对它的引用。
除了错误的方法外,JFrame
包含一些组件,这些组件在其之上呈现,因此即使此方法有效,您也看不到任何区别,因为框架实际上被其他组件覆盖(JRootPane
及其内容 Pane )
自定义绘画应该在 Component
绘画方法之一中进行。
以下示例使用多种技术来更改和更新框架的内容。
首先,它用我们自己的组件替换了内容面板。这始终是必需的,但因为我在框架上执行自定义绘画,所以这是最简单的。我本可以简单地将 PaintPane
添加到框架中以获得类似的结果。
其次,我使用 setBackground
更改组件的背景。
第三,我覆盖了 paintComponent
以在我的组件上执行自定义绘制。
public class SimplePaint01 {
public static void main(String[] args) {
new SimplePaint01();
}
public SimplePaint01() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.setContentPane(new PaintPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class PaintPane extends JPanel {
private int angle = 0;
private Rectangle shape = new Rectangle(0, 0, 100, 100);
public PaintPane() {
setBackground(Color.RED);
Timer timer = new Timer(16, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
angle += 5;
repaint();
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int x = ((getWidth() - shape.width) / 2);
int y = ((getHeight() - shape.height) / 2);
shape.x = x;
shape.y = y;
g2d.setColor(Color.BLUE);
g2d.setTransform(AffineTransform.getRotateInstance(Math.toRadians(angle), x + (shape.width / 2), y + (shape.height / 2)));
g2d.fill(shape);
g2d.dispose();
}
}
}
关于java - 在不扩展的情况下在 JFrame 上绘画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13849184/