我刚刚开始编码,我想我忘记了如何加倍缓冲。这是我现在的代码,我不确定我缺少什么。当我开始它时,只有一个白色的屏幕,没有椭圆形。
渲染中的错误是什么?
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.JFrame;
public class Graphs extends JFrame {
private Image dbImage;
private Graphics dbg;
public static void main(String[] args) {
new Graphs();
}
public Graphs() {
setSize(1000, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setTitle("Graphs");
setLocationRelativeTo(null);
setVisible(true);
}
public void paint(Graphics g) {
dbImage = createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
paintComponent(dbg);
dbg.drawImage(dbImage, 0, 0, this);
}
public void paintComponent(Graphics g) {
g.drawOval(200, 200, 200, 200);
repaint();
}
}
@Override
The method paintComponent(Graphics) of type Graphs must override or implement a supertype method.
1 quick fix available:
-> Remove '@Override' annotation
答案 0 :(得分:5)
您没有看到椭圆形的原因是您正在将图像绘制到自己的Graphics
对象上。替换:
dbg.drawImage(dbImage, 0, 0, this);
与
g.drawImage(dbImage, 0, 0, this);
最好不要覆盖顶级容器中的paint
,而是覆盖子类paintComponent
中的JComponent
。还记得打电话
super.paintComponent(g);
答案 1 :(得分:3)
paint
方法
组件(如JFrame
),主要问题是它们是
不是双缓冲的,就像从JComponent
super.paint
非常非常糟糕。你基本上阻止了框架绘制任何子组件...... paint
方法中加载图片,它会减慢将来的重绘速度repaint
方法调用paintXxx
,这会导致无限循环的绘制,快速吞噬您的CPU周期JFrame
没有paintComponent
方法。JComponent
方法执行JPanel
(例如paintComponent
)。使用示例更新
public class BadPaint10 {
public static void main(String[] args) {
new BadPaint10();
}
public BadPaint10() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new PaintPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class PaintPane extends JPanel {
private BufferedImage background;
public PaintPane() {
try {
background = ImageIO.read(new File("C:/Users/shane/Dropbox/pictures/436px-Work_with_exotic_creatures.jpg"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
@Override
public Dimension getPreferredSize() {
return background == null ? super.getPreferredSize() : new Dimension(background.getWidth(), background.getHeight());
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (background != null) {
int x = (getWidth() - background.getWidth()) / 2;
int y = (getHeight() - background.getHeight()) / 2;
g.drawImage(background, x, y, this);
x = (getWidth() - 200) / 2;
y = (getHeight() - 200) / 2;
g.setColor(Color.RED);
g.drawOval(x, y, 200, 200);
}
}
}
}
正如已经指出的那样,优先权很重要。元素绘制的顺序将影响结果。
您可能会找到
有用的。