import java.awt.Color;
import java.awt.Graphics;
import java.awt.Panel;import javax.swing.JFrame;public class test {
private JFrame f = new JFrame(" Hello Out There!");
private Panel p = new Panel();
public void paintComponent() {
f.add(p);
f.setSize(170, 170);
f.setBackground(Color.blue);
f.setVisible(true); //如果把这句话放到Graphics g = p.getGraphics(); 后面
p.setForeground(Color.red); //g为什么在运行的时候就变成空的了呢?
Graphics g = p.getGraphics();
f.setVisible(true);
g.drawArc(30, 40, 50, 60, 70, 80);
g.fillArc(30, 40, 50, 60, 70, 80);
} public static void main(String args[]) {
test guiWindow = new test();
guiWindow.paintComponent();
}}为什么图片一闪后就消失了?
希望高手把原因说的明白点,谢谢!
import java.awt.Graphics;
import java.awt.Panel;import javax.swing.JFrame;public class test {
private JFrame f = new JFrame(" Hello Out There!");
private Panel p = new Panel();
public void paintComponent() {
f.add(p);
f.setSize(170, 170);
f.setBackground(Color.blue);
f.setVisible(true); //如果把这句话放到Graphics g = p.getGraphics(); 后面
p.setForeground(Color.red); //g为什么在运行的时候就变成空的了呢?
Graphics g = p.getGraphics();
f.setVisible(true);
g.drawArc(30, 40, 50, 60, 70, 80);
g.fillArc(30, 40, 50, 60, 70, 80);
} public static void main(String args[]) {
test guiWindow = new test();
guiWindow.paintComponent();
}}为什么图片一闪后就消失了?
希望高手把原因说的明白点,谢谢!
你应该重写jpanel的paint方法,把g.draw....()放到paint方法里。
个人意见。
import java.awt.Color;
import java.awt.Graphics;import javax.swing.JFrame;
import javax.swing.JPanel;public class Test
{
private JFrame frame = new JFrame(" Hello Out There!"); private MyPane pane = new MyPane(); public void initGUI()
{
pane.setOpaque(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(pane);
frame.setSize(170, 170);
frame.setLocationRelativeTo(null);
frame.getContentPane().setBackground(Color.BLUE);
frame.setVisible(true);
} public static void main(String args[])
{
Test guiWindow = new Test();
guiWindow.initGUI();
}
}
class MyPane extends JPanel
{
private static final long serialVersionUID = -147774397142687220L;
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.RED);
g.drawArc(30, 40, 50, 60, 70, 80);
g.fillArc(30, 40, 50, 60, 70, 80);
}
}
你的Panel是放在JFrame上的,但是在你调用setvisible(true)之前,
Panel是不可见的,不在屏幕上显示出来的,所以调用getGraphics()获得是null。
重绘时调用paint(Graphics g)方法,会先清除组件的显示区域。
而你画出的图像是在paint()方法之外,所以一旦组件重绘,上面的图像便便被清除了。
楼主的例子中,是在调用JFrame的paint方法是绘画Panel,而在调用Panel的paint方法时会把在JFrame中描画的给覆盖了,
所以你会看到闪一下的情况。