我不重写paint方法,在其他方法里面使用
Graphics g = getGraphics();
g.setColor(Color.BLUE);
g.fillRect(0, 0, width, height);
为什么就显示不出来,因为需要所以不能用paint,求解决方法
Graphics g = getGraphics();
g.setColor(Color.BLUE);
g.fillRect(0, 0, width, height);
为什么就显示不出来,因为需要所以不能用paint,求解决方法
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;import javax.swing.JButton;
import javax.swing.JDialog;public class TestDialog extends JDialog implements ActionListener { JButton btnFillRect; public TestDialog() {
this.setSize(640, 480);
btnFillRect = new JButton("Fill Rect");
btnFillRect.addActionListener(this);
this.add(btnFillRect, BorderLayout.SOUTH);
this.getGraphics();
} public void actionPerformed(ActionEvent e) {
Graphics g = this.getGraphics();
g.setColor(Color.RED);
g.fillRect(50, 50, 200, 200);
} public static void main(String[] args) {
TestDialog dialog = new TestDialog();
dialog.setVisible(true);
}
}
而你写的那部分绘制代码不会被系统调用到。
2、不要直接重写JDialog的paint()函数,而是仅重写你自定义(或继承)的一个JPanel的paint();也就是缩小影响范围。
关于双缓冲参见这里:
http://developer.51cto.com/art/201105/259587.htm
JComponent 类在其 paint() 方法中实现了双缓冲,一般不建议重写 paint() 方法,除非你有特别的效果需求。建议的方式是重写 paintComponent() 方法:public void paintComponent(Graphics g) {
// super.paintComponent(g);
// ...
}除了双缓冲的问题之外,重写 paintComponent() 方法还保证了你不会影响到此控件内的子控件的绘製。