从你的问题来看,很难确切地理解你想要实现的目标。您只是想更改框架的背景颜色或执行一些自定义绘画吗???
This 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();
}
}
}