在GUI Java中上传JPG图像?

时间:2015-02-24 02:21:29

标签: java

因此,我们随机选择一个介于1到6之间的数字,无论滚动的是什么,都会上传一张与该数字相对应的模具面。它正在编译,但我得到一个我不明白的异常帖子。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.Random;
import java.awt.FlowLayout;

public class Butttin {

        private static JLabel label;

    public static void main(String[] args) {    
        JFrame frame = new JFrame("Rolling Dice Game");
        JPanel panel = new JPanel();
        JButton buttonRoll = new JButton("Roll!");

        buttonRoll.addActionListener(new buttonRoll()); 

        panel.setLayout(new GridLayout(5, 2, 5, 5));
        panel.add(label);
        frame.setVisible(true);
        frame.setSize(500, 500);
        frame.setResizable(false);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
    }

    private static class buttonRoll implements ActionListener {
         private java.util.Random random = new java.util.Random();

        public void actionPerformed(ActionEvent event) {
            int max = 6;
            int min = 1;
            ImageIcon img;
            int rolledNumber = random.nextInt(max - min + 1) + min;
            String command  = event.getActionCommand();
            if (command == "Roll!") {
                if ("Roll!".equals(command)) {
                    ImageIcon imageIcon = new ImageIcon("die 1.jpg");
                    label = new JLabel(imageIcon);

                } else if (rolledNumber == 2){
                    ImageIcon imageIcon = new ImageIcon("die 2.jpg");
                    label = new JLabel(imageIcon);

                } else if (rolledNumber == 3){
                    ImageIcon imageIcon = new ImageIcon("die 3.jpg");
                    label = new JLabel(imageIcon);

                } else if (rolledNumber == 4){
                    ImageIcon imageIcon = new ImageIcon("die 4.jpg");
                    label = new JLabel(imageIcon);

                } else if (rolledNumber == 5){
                    ImageIcon imageIcon = new ImageIcon("die 5.jpg");
                    label = new JLabel(imageIcon);

                } else if (rolledNumber == 6){
                    ImageIcon imageIcon = new ImageIcon("die 6.jpg");
                    label = new JLabel(imageIcon);
                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

问题是在将JLabel添加到JPanel之前,不要初始化它。最简单的方法是直接初始化它:

private static JLabel label = new JLabel();

在您的actionPerformed方法中,不是每次都创建一个新的JLabel而是替换旧版本,只需使用其setIcon方法。

label.setIcon(imageIcon);

另一方面,当使用Swing组件(创建组件,添加组件等)时,它应该在Event Dispatch Thread上运行:

javax.swing.SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        //...
    }
});