Java代码不按顺序执行

时间:2014-03-07 18:58:38

标签: java netbeans awt

我有以下代码,其中我真正想要的是当我点击按钮时,jLabel应该显示'1',然后单击它的图像并保存然后为'2','3'等等上...

private void StartActionPerformed(java.awt.event.ActionEvent evt) {                                      
        for(int i=0; i<5; i++){
            Numbers.setText(""+i);
            System.out.println("Begin"+i);
            BufferedImage image = null;
            try {
                image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
            } catch (AWTException ex) {
                Logger.getLogger(Flash_Cards.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                ImageIO.write(image, "png", new File("E:/Data/Card_" + i + ".png"));
            } catch (IOException ex) {
                Logger.getLogger(Flash_Cards.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println("End"+i);
        }
    }

但我得到的是这些图片: enter image description here enter image description here enter image description here enter image description here enter image description here

更新:我的文件结构:

enter image description here

2 个答案:

答案 0 :(得分:0)

编辑:我认为我的解决方案也不起作用。

如果您使用

更新标签
 Numbers.setText(""+i);

然后您需要在包含标签

的面板上调用revalidate/repaint
 panel.revalidate();
 panel.repaint();

答案 1 :(得分:0)

我不做awt / swing所以我可能错了,但实际的布局&amp;退出Numbers.setText(""+i);方法后,会发现StartActionPerformed的图形。因此,您必须在发生这种情况后捕获图像。要做多次,你必须在多个步骤中执行setText,screenCapture,setText,..据我所知,SwingUtilities.invokeLater可以通过将行动按顺序排列来实现。下面的代码可能有效

private void StartActionPerformed(java.awt.event.ActionEvent evt) {
    for (int i = 0; i < 5; i++) {
        final int number = i;
        // enqueue setting a new number
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Numbers.setText("" + number);
            }
        });
        // enqueue taking a screenshot thereof
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                BufferedImage image = null;
                try {
                    image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit()
                            .getScreenSize()));
                } catch (AWTException ex) {
                    Logger.getLogger(Flash_Cards.class.getName()).log(Level.SEVERE, null, ex);
                }
                try {
                    ImageIO.write(image, "png", new File("E:/Data/Card_" + number + ".png"));
                } catch (IOException ex) {
                    Logger.getLogger(Flash_Cards.class.getName()).log(Level.SEVERE, null, ex);
                }
                System.out.println("End" + number);
            }
        });
    }
}