生成随机出现一个数字的随机数

时间:2015-03-10 23:30:36

标签: java swing random

我目前正在学习Java中的Swing而我正在尝试生成一个随机数,除非生成数字时程序需要计算出它有多少数字(1-10),然后暂停半秒,然后显示第一个数字暂停半秒显示第二个数字等。

非常像这样:

生成的数字1256

1(1/2秒)2(1/2秒)5(1/2秒)6

到目前为止,这是我的代码:

package test;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.BevelBorder;

public class RandomNumerGenerator implements ActionListener {
    JFrame f;
    JPanel p;
    JTextField tNumber, tFrom, tTo;
    JButton b, bSave;
    private File configFile = new File("config.properties");
    private Properties configProps;
    private JPanel panel;
    private JTextField tTitle;
    private JMenuBar menuBar;
    private JMenu mnConfiguration;
    private JTextField tName;
    String z;
    private JCheckBoxMenuItem chckbxmntmEnableSpinButton;
    private JLabel lColour;
    private JRadioButton rRed;
    private JRadioButton rBlue;
    private JRadioButton rWhite;
    private JRadioButton rYellow;
    private JRadioButton rOrange;
    private JRadioButton rPink;
    private JRadioButton rPurple;

    // -----------------------------Frame-------------------------
    @SuppressWarnings("deprecation")
    public RandomNumerGenerator() {
        f = new JFrame("Random Number Generator Ver 1.1");
        f.setTitle("Randomiser Ver 1.4");
        f.setBackground(Color.BLACK);
        f.setIconImage(Toolkit.getDefaultToolkit().getImage(RandomNumerGenerator.class.getResource("/test/Resources/owl_1.png")));
        f.setResizable(false);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        p = new JPanel();
        p.setAutoscrolls(true);
        p.setBorder(new BevelBorder(BevelBorder.LOWERED, Color.WHITE,
                Color.WHITE, Color.WHITE, Color.WHITE));
        p.setBackground(Color.BLACK);
        f.setExtendedState(JFrame.MAXIMIZED_BOTH); 
        f.setVisible(true);
        f.setSize(5000, 5000);
        f.show();
        // -----------------------Generated number
        // settings-------------------------------
        tNumber = new JTextField(10);
        tNumber.setBorder(null);
        tNumber.setEditable(false);
        tNumber.setHorizontalAlignment(SwingConstants.CENTER);
        tNumber.setBackground(Color.BLACK);
        tNumber.setForeground(Color.WHITE);
        tNumber.setFont(new Font("Tahoma", Font.BOLD, 300));
        f.getContentPane().add(p, BorderLayout.SOUTH);
        panel = new JPanel();
        panel.setBackground(Color.BLACK);
        panel.setBorder(new BevelBorder(BevelBorder.RAISED, Color.WHITE,
                Color.WHITE, Color.WHITE, Color.WHITE));

        // ----------------------Title--------------------------------------------
        tTitle = new JTextField("Randomiser");
        tTitle.setEditable(false);
        tTitle.setOpaque(false);
        tTitle.setBorder(null);
        tTitle.setHorizontalAlignment(SwingConstants.CENTER);
        tTitle.setFont(new Font("Tahoma", Font.BOLD, 150));
        tTitle.setForeground(Color.WHITE);
        tTitle.setBackground(Color.BLACK);
        panel.add(tTitle);
        tTitle.setColumns(13);
        // ----------------------------Buttons------------------------------------------
        b = new JButton("Spin");
        b.setForeground(Color.WHITE);
        b.setFont(new Font("Tahoma", Font.BOLD, 150));
        b.setBackground(Color.BLACK);
        b.addActionListener(this);


        GroupLayout gl_p = new GroupLayout(p);
        gl_p.setHorizontalGroup(
            gl_p.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_p.createSequentialGroup()
                    .addGap(7)
                    .addComponent(panel, GroupLayout.DEFAULT_SIZE, 1257, Short.MAX_VALUE)
                    .addGap(18))
                .addGroup(gl_p.createSequentialGroup()
                    .addGap(7)
                    .addComponent(tNumber, GroupLayout.DEFAULT_SIZE, 1257, Short.MAX_VALUE)
                    .addGap(18))
                .addGroup(gl_p.createSequentialGroup()
                    .addGap(454)
                    .addComponent(b, GroupLayout.DEFAULT_SIZE, 365, Short.MAX_VALUE)
                    .addGap(463))
        );
        gl_p.setVerticalGroup(
            gl_p.createParallelGroup(Alignment.LEADING)
                .addGroup(gl_p.createSequentialGroup()
                    .addGap(26)
                    .addComponent(panel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGap(8)
                    .addComponent(tNumber, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addGap(106)
                    .addComponent(b, GroupLayout.DEFAULT_SIZE, 191, Short.MAX_VALUE)
                    .addGap(87))
        );
        p.setLayout(gl_p);
        // -------------------------------Menu------------------------
        menuBar = new JMenuBar();
        f.setJMenuBar(menuBar);
        mnConfiguration = new JMenu("Configuration");
        menuBar.add(mnConfiguration);
        JLabel lblName = new JLabel("Name");
        lblName.setBackground(Color.WHITE);
        lblName.setFont(new Font("Tahoma", Font.BOLD, 11));
        mnConfiguration.add(lblName);
        // -------------------Title Options-------------------
        tName = new JTextField();
        mnConfiguration.add(tName);
        tName.setColumns(4);
        JLabel lblStartValue = new JLabel("Start Value");
        lblStartValue.setBackground(Color.WHITE);
        lblStartValue.setFont(new Font("Tahoma", Font.BOLD, 11));
        mnConfiguration.add(lblStartValue);

        // --------------------------------From Field------------------------
        tFrom = new JTextField("1", 5);
        mnConfiguration.add(tFrom);
        JLabel lblEndValue = new JLabel("End Value");
        lblEndValue.setBackground(Color.WHITE);
        lblEndValue.setFont(new Font("Tahoma", Font.BOLD, 11));
        mnConfiguration.add(lblEndValue);

        // -----------------------To Field---------------------------
        tTo = new JTextField("100", 5);
        mnConfiguration.add(tTo);

        lColour = new JLabel("Colour");
        lColour.setBackground(Color.WHITE);
        lColour.setFont(new Font("Tahoma", Font.BOLD, 11));
        mnConfiguration.add(lColour);

        JSeparator separator = new JSeparator();
        mnConfiguration.add(separator);
        //-------------Set Font Colour green--------
        final JRadioButton rGreen = new JRadioButton("Green");
        rGreen.setOpaque(false);
        rGreen.setBackground(Color.WHITE);
        rGreen.setFont(new Font("Tahoma", Font.BOLD, 11));      
        mnConfiguration.add(rGreen);
        rGreen.addActionListener(this);

        rGreen.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent ae){
                if (rGreen.isSelected()){
                    tNumber.setForeground(Color.GREEN);
                    rRed.setEnabled(false);
                    rBlue.setEnabled(false);
                    rYellow.setEnabled(false);
                    rPink.setEnabled(false);
                    rPurple.setEnabled(false);
                    rWhite.setEnabled(false);
                    rOrange.setEnabled(false);

                }else
                {
                    tNumber.setForeground(Color.WHITE);
                    rRed.setEnabled(true);
                    rBlue.setEnabled(true);
                    rYellow.setEnabled(true);
                    rPink.setEnabled(true);
                    rPurple.setEnabled(true);
                    rWhite.setEnabled(true);
                    rOrange.setEnabled(true);
                }
            }
            }
        );
        //-------------Set Font Colour Red--------
        rRed = new JRadioButton("Red");
        rRed.setFont(new Font("Tahoma", Font.BOLD, 11));
        mnConfiguration.add(rRed);

        rRed.addActionListener(this);

        rRed.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent ae){
                if (rRed.isSelected()){
                    tNumber.setForeground(Color.RED);
                    rGreen.setEnabled(false);
                    rBlue.setEnabled(false);
                    rYellow.setEnabled(false);
                    rPink.setEnabled(false);
                    rPurple.setEnabled(false);
                    rWhite.setEnabled(false);
                    rOrange.setEnabled(false);

                }else
                {
                    tNumber.setForeground(Color.WHITE);
                    rGreen.setEnabled(true);
                    rBlue.setEnabled(true);
                    rYellow.setEnabled(true);
                    rPink.setEnabled(true);
                    rPurple.setEnabled(true);
                    rWhite.setEnabled(true);
                    rOrange.setEnabled(true);
                }
            }
            }
        );
        //-------------Set Font Colour Blue--------
        rBlue = new JRadioButton("Blue");
        rBlue.setFont(new Font("Tahoma", Font.BOLD, 11));
        mnConfiguration.add(rBlue);
        rBlue.addActionListener(this);

        rBlue.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent ae){
                if (rBlue.isSelected()){
                    tNumber.setForeground(Color.BLUE);
                    rGreen.setEnabled(false);
                    rRed.setEnabled(false);
                    rYellow.setEnabled(false);
                    rPink.setEnabled(false);
                    rPurple.setEnabled(false);
                    rWhite.setEnabled(false);
                    rOrange.setEnabled(false);
                }else
                {
                    tNumber.setForeground(Color.WHITE);
                    rGreen.setEnabled(true);
                    rRed.setEnabled(true);
                    rYellow.setEnabled(true);
                    rPink.setEnabled(true);
                    rPurple.setEnabled(true);
                    rWhite.setEnabled(true);
                    rOrange.setEnabled(true);
                }
            }
            }
        );
        //-------------Set Font Colour Yellow--------
        rYellow = new JRadioButton("Yellow");
        rYellow.setFont(new Font("Tahoma", Font.BOLD, 11));
        mnConfiguration.add(rYellow);
        rYellow.addActionListener(this);

        rYellow.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent ae){
                if (rYellow.isSelected()){
                    tNumber.setForeground(Color.YELLOW);
                    rGreen.setEnabled(false);
                    rBlue.setEnabled(false);
                    rRed.setEnabled(false);
                    rPink.setEnabled(false);
                    rPurple.setEnabled(false);
                    rWhite.setEnabled(false);
                    rOrange.setEnabled(false);
                }else
                {
                    tNumber.setForeground(Color.WHITE);
                    rGreen.setEnabled(true);
                    rBlue.setEnabled(true);
                    rRed.setEnabled(true);
                    rPink.setEnabled(true);
                    rPurple.setEnabled(true);
                    rWhite.setEnabled(true);
                    rOrange.setEnabled(true);
                }
            }
            }
        );
        //-------------Set Font Colour Orange--------
        rOrange = new JRadioButton("Orange");
        rOrange.setFont(new Font("Tahoma", Font.BOLD, 11));
        mnConfiguration.add(rOrange);

        rOrange.addActionListener(this);

        rOrange.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent ae){
                if (rOrange.isSelected()){
                    tNumber.setForeground(Color.ORANGE);
                    rGreen.setEnabled(false);
                    rBlue.setEnabled(false);
                    rYellow.setEnabled(false);
                    rPink.setEnabled(false);
                    rPurple.setEnabled(false);
                    rWhite.setEnabled(false);
                    rRed.setEnabled(false);
                }else
                {
                    tNumber.setForeground(Color.WHITE);
                    rGreen.setEnabled(true);
                    rBlue.setEnabled(true);
                    rYellow.setEnabled(true);
                    rPink.setEnabled(true);
                    rPurple.setEnabled(true);
                    rWhite.setEnabled(true);
                    rRed.setEnabled(true);
                }
            }
            }
        );
        //-------------Set Font Colour Purple--------
        rPurple = new JRadioButton("Purple");
        rPurple.setFont(new Font("Tahoma", Font.BOLD, 11));
        mnConfiguration.add(rPurple);

        rPurple.addActionListener(this);

        rPurple.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent ae){
                if (rPurple.isSelected()){
                    tNumber.setForeground(Color.MAGENTA);
                    rGreen.setEnabled(false);
                    rBlue.setEnabled(false);
                    rYellow.setEnabled(false);
                    rPink.setEnabled(false);
                    rRed.setEnabled(false);
                    rWhite.setEnabled(false);
                    rOrange.setEnabled(false);
                }else
                {
                    tNumber.setForeground(Color.WHITE);
                    rGreen.setEnabled(true);
                    rBlue.setEnabled(true);
                    rYellow.setEnabled(true);
                    rPink.setEnabled(true);
                    rRed.setEnabled(true);
                    rWhite.setEnabled(true);
                    rOrange.setEnabled(true);
                }
            }
            }
        );
        //-------------Set Font Colour Pink--------
        rPink = new JRadioButton("Pink");
        rPink.setFont(new Font("Tahoma", Font.BOLD, 11));
        mnConfiguration.add(rPink);
        rPink.addActionListener(this);

        rPink.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent ae){
                if (rPink.isSelected()){
                    tNumber.setForeground(Color.PINK);
                    rGreen.setEnabled(false);
                    rBlue.setEnabled(false);
                    rYellow.setEnabled(false);
                    rRed.setEnabled(false);
                    rPurple.setEnabled(false);
                    rWhite.setEnabled(false);
                    rOrange.setEnabled(false);
                }else
                {
                    tNumber.setForeground(Color.WHITE);
                    rGreen.setEnabled(true);
                    rBlue.setEnabled(true);
                    rYellow.setEnabled(true);
                    rRed.setEnabled(true);
                    rPurple.setEnabled(true);
                    rWhite.setEnabled(true);
                    rOrange.setEnabled(true);
                }
            }
            }
        );
        //-------------Set Font Colour White--------
        rWhite = new JRadioButton("White");
        rWhite.setFont(new Font("Tahoma", Font.BOLD, 11));
        mnConfiguration.add(rWhite);

        rWhite.addActionListener(this);

        rWhite.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent ae){
                if (rWhite.isSelected()){
                    tNumber.setForeground(Color.WHITE);
                    rGreen.setEnabled(false);
                    rBlue.setEnabled(false);
                    rYellow.setEnabled(false);
                    rPink.setEnabled(false);
                    rPurple.setEnabled(false);
                    rRed.setEnabled(false);
                    rOrange.setEnabled(false);
                }else
                {
                    tNumber.setForeground(Color.WHITE);
                    rGreen.setEnabled(true);
                    rBlue.setEnabled(true);
                    rYellow.setEnabled(true);
                    rPink.setEnabled(true);
                    rPurple.setEnabled(true);
                    rRed.setEnabled(true);
                    rOrange.setEnabled(true);
                }
            }
            }
        );

        // -------------------Save Count-----------
        bSave = new JButton("Save");
        bSave.setFont(new Font("Tahoma", Font.BOLD, 11));
        bSave.setInheritsPopupMenu(true);
        mnConfiguration.add(bSave);
        bSave.addActionListener(this);
        f.setVisible(true);
        // ----------------Save Config------------------------------
        bSave.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                try {
                    saveProperties();
                    JOptionPane.showMessageDialog(f,
                            "Properties were saved successfully!");
                } catch (IOException ex) {
                    JOptionPane.showMessageDialog(f,
                            "Error saving properties file: " + ex.getMessage());
                }
            }
        });
        try {
            loadProperties();
        } catch (IOException ex) {
            JOptionPane
                    .showMessageDialog(f,
                            "The config.properties file does not exist, default properties loaded.");
        }
        tName.setText(configProps.getProperty("Name"));
        tFrom.setText(configProps.getProperty("Start"));
        tTo.setText(configProps.getProperty("End"));
        tTitle.setText(tName.getText());
        ;
        // ----------Action on Button Pressed-------------------------
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == b) {
            String s = tTo.getText();
            String t = tFrom.getText();
            try {
                int x = Integer.parseInt(t);
                int d = Integer.parseInt(s);
                if (x >= d) {
                    JOptionPane.showMessageDialog(f, "START value is higher or Equal to END value, please enter a lower number...");
                } else {
                    int newNumber = (int) (Math.random() * (d + 1 - x) + x);
                    tNumber.setText(newNumber + "");
                }
            } catch (NumberFormatException ee) {
                JOptionPane.showMessageDialog(f, "You have entered an Invaild format please reconfigure...");

            }

        } else if (e.getSource() == bSave) {
            tTitle.setText(tName.getText());
        }
    }

    // -----------------------Saving-----------------------
    private void saveProperties() throws IOException {

        configProps.setProperty("Name", tName.getText());
        configProps.setProperty("Start", tFrom.getText());
        configProps.setProperty("End", tTo.getText());
        OutputStream outputStream = new FileOutputStream(configFile);
        configProps.store(outputStream, "host setttings");
        outputStream.close();

    }

    // ------------------------Loading--------------
    private void loadProperties() throws IOException {
        Properties defaultProps = new Properties();
        // sets default properties
        defaultProps.setProperty("Name", "Randomiser");
        defaultProps.setProperty("Start", "1");
        defaultProps.setProperty("End", "100");

        configProps = new Properties(defaultProps);

        // loads properties from file
        InputStream inputStream = new FileInputStream(configFile);
        configProps.load(inputStream);
        inputStream.close();


    }

    // -----------------Main Program------------------------
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new RandomNumerGenerator();
            }
        });
    }
}

因此,每次按下旋转按钮,它都会生成一个新数字,但会显示每个数字1。

1 个答案:

答案 0 :(得分:2)

利用Swing Timer在更新之间注入延迟

有关详细信息,请参阅How to use Swing Timers

Random Number

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JLabel label;
        private JTextField field;
        private Timer timer;
        private char[] values;
        private int index;

        private Random rnd;

        public TestPane() {
            rnd = new Random();

            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;

            label = new JLabel("...");
            field = new JTextField(10);
            JButton btn = new JButton("Start");

            add(label, gbc);
            add(field, gbc);
            add(btn, gbc);

            timer = new Timer(1000, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    StringBuilder sb = new StringBuilder(field.getText());
                    sb.append(values[index]);
                    field.setText(sb.toString());

                    index++;
                    if (index >= values.length) {
                        ((Timer)e.getSource()).stop();
                    }
                }
            });
            timer.setInitialDelay(0);

            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (timer.isRunning()) {
                        timer.stop();
                    }
                    field.setText("");
                    index = 0;
                    int number = rnd.nextInt(999);
                    String text = Integer.toString(number);
                    label.setText(text);
                    values = text.toCharArray();
                    timer.start();
                }
            });
        }

    }

}