从您的问题中,很难准确地了解您想要实现什么。您只是想更改框架的背景颜色还是执行一些自定义绘画吗?
这个 Graphics g = frame.getGraphics() 不是一个好方法。除了 getGraphics 可能返回 null 之外,Java 中的图形是无状态的,这意味着您用来绘制的图形上下文可能会在绘制周期之间更改,您永远不应该依赖于它或保留对其的引用。
除了方法错误之外,JFrame 包含多个组件,这些组件在其上方呈现,因此即使此方法有效,您也看不到任何区别,因为实际上其他组件(JRootPane 和其内容窗格)覆盖了该框架。
自定义绘画应在 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();
}
}
}
PaintListener
的目的是在重新绘制时得到通知。 - f4lcoPaintListener
是什么?以前从未见过。 - MadProgrammer