2011-04-18 40 views
0
public class my_gui extends JFrame { 
    public my_gui() { 
     setTitle("Broscute 1.0 :p"); 
     setSize(954, 320); 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 
     setResizable(false); 
     setIconImage(Toolkit.getDefaultToolkit().getImage("src/img/test.png")); 
     setVisible(true); 
     initUI(); 
    } 
    public final void initUI() { //ui here 
     setLayout(null); 
     setLocationRelativeTo(null); 
     JPanel panel = new JPanel(); 
     panel.setLayout(null); 
     panel.setBounds(0, 0, 954, 320); 
     getContentPane().add(panel); 
     JButton button = new JButton("Start!"); 
     button.setBounds(0, 0, 954, 40); 
     final ImagePanel[] label = new ImagePanel[4]; 
     int i, j; 
     for(i=40, j=0;i<=220;i+=60, j++){ 
      label[j] = new ImagePanel(0, i); 
      label[j].setBounds(0, 0, 954, 320); 
      panel.add(label[j]); 
     } 
     button.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent event) { 
       label[3].X += 100; 

      } 
     }); 
     panel.add(button); 
    } 
} 
class ImagePanel extends JComponent{ 
    public int X, Y; 
    float v = 10; 
    private BufferedImage image; 
    ImagePanel(){} 
    public ImagePanel(int x, int y) { 
     X = x; Y = y; 
     try {     
      image = ImageIO.read(new File("src/img/broasca.png")); 
     } catch (IOException ex) { 
      // handle exception... 
     } 
    } 
    @Override 
    public void paintComponent(Graphics g) { 
     super.paintChildren(g); //a friend told me I should put it here 
     g.drawImage(image, X, Y, this); // see javadoc for more info on the parameters 
     repaint(); //I think this should go here 
    } 
} 

出错了。Java代码,需要快速查看(swing,图形2D)

如果我从netbeans运行它,它有时会按照预期绘制图像..但有时候我只能看到主窗口和移动鼠标后的“开始”按钮。

在IDE之外运行它,它无法找到图像。

我在这里做错了什么?任何意见是极大的赞赏。 谢谢你的时间。

+0

在Code Review上问你可能会更好:http://codereview.stackexchange.com/ – DJClayworth 2011-04-18 20:17:10

+0

不错,我不知道Code Review。从现在开始我会记住,谢谢。 – sdadffdfd 2011-04-18 20:22:23

回答

2

在完成所有初始化之前不显示对话框,即将setVisible移动到构造函数中的最后一个方法。

为了更好的重用,根本没有JFrame派生类的调用setVisible(true),让客户端去做。

问题是,一旦你显示窗口,你对窗口所做的任何修改都必须在GUI线程上完成,否则你会看到像你所看到的虚假问题。

+0

就像一个魅力,非常感谢你 – sdadffdfd 2011-04-18 20:00:37

+0

任何想法,我将如何获得图像加载一次,我建立它.JAR文件? – sdadffdfd 2011-04-18 20:05:00

+0

new ImageIcon(my_gui.class.getResource(“/ img/test.png”)); – MeBigFatGuy 2011-04-18 20:10:55

1

您通常在paintComponent中做的第一件事是通过super.paintComponent()清除屏幕外位图 - 我敢打赌这是您的问题。

+0

刚试过用super.paintComponent()而不是super.paintChildren()..结果相同,有时它会绘制图像,有时候不会。 – sdadffdfd 2011-04-18 19:53:18