随机数到JTextfield

时间:2016-03-17 12:43:01

标签: java random

我正在制作一款名为“谁想成为大学作业的亿万富翁”的游戏。我正在使用Eclipse IDE。我有这个代码,使用随机数生成器方法给出每个答案的百分比。 代码:

public AskPublic ()
    {

        Random r = new Random ();
        int A = r.nextInt(101);
        int B = r.nextInt(101 - A);
        int C = r.nextInt(101 - A - B);
        int D = 100 - A - B - C;
}

有人可以告诉我如何使用“窗口”构建器将其添加到GUI。这是GUI的一些代码 代码

    btnDismiss = new JButton("Dismiss");
    btnDismiss.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            dispose();
        }
    });

    btnDismiss.setBounds(275, 187, 89, 23);
    percent.add(btnDismiss);

    lblA = new JLabel("A");
    lblA.setForeground(Color.ORANGE);
    lblA.setFont(new Font("Arial", Font.BOLD, 25));
    lblA.setBounds(88, 67, 23, 35);
    percent.add(lblA);

    lblB = new JLabel("B");
    lblB.setFont(new Font("Arial", Font.BOLD, 25));
    lblB.setForeground(Color.ORANGE);
    lblB.setBounds(209, 70, 31, 29);
    percent.add(lblB);

    lblC = new JLabel("C");
    lblC.setFont(new Font("Arial", Font.BOLD, 25));
    lblC.setForeground(Color.ORANGE);
    lblC.setBounds(333, 70, 31, 29);
    percent.add(lblC);

    lblD = new JLabel("D");
    lblD.setForeground(Color.ORANGE);
    lblD.setBackground(Color.WHITE);
    lblD.setFont(new Font("Arial", Font.BOLD, 25));
    lblD.setBounds(457, 70, 31, 29);
    percent.add(lblD);

    A1 = new JTextField();
    A1.setEditable(false);
    A1.setBounds(113, 67, 86, 32);
    percent.add(A1);
    A1.setColumns(10);
    System.out.println(A);

    B2 = new JTextField();
    B2.setEditable(false);
    B2.setBounds(233, 67, 86, 32);
    percent.add(B2);
    B2.setColumns(10);
    System.out.println(B);

    C3 = new JTextField();
    C3.setEditable(false);
    C3.setBounds(361, 67, 86, 32);
    percent.add(C3);
    C3.setColumns(10);
    System.out.println(C);

    D4 = new JTextField();
    D4.setEditable(false);
    D4.setBounds(485, 67, 86, 32);
    percent.add(D4);
    D4.setColumns(10);
    System.out.println(D);
}       

1 个答案:

答案 0 :(得分:1)

似乎是什么问题,你可以把它变成一个返回随机数的函数:

private int AskPublic() {
        Random r = new Random(); // you should probably make this a class variable
        int A = r.nextInt(101);
        int B = r.nextInt(101 - A);
        int C = r.nextInt(101 - A - B);
        return (100 - A - B - C);
}

并通过调用AskPublic()在代码中的任何位置调用它。