为想要随机数生成器的教授进行侧面项目。
目前状态下的节目还有很多不足之处,但我认为我走在了正确的轨道上。但是,当涉及到使用文本字段,将数据传递给我的随机数等式并显示它时,我感到困惑。基本上,程序不会等待用户输入文本字段。
我们从未在学校通过OOP,因此我需要拔出大枪(你们)。
这是我目前正在使用的内容。最后一点是我遇到问题的部分。
package RandomButton;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.JLabel;
public class GUI extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField ClassSize;
private JLabel label;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI frame = new GUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public GUI() {
int x;
int max;
String strMax;
String strX;
Scanner kb = new Scanner(System.in);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
//Text field code
textField = new JTextField();
textField.setText("1");
textField.setHorizontalAlignment(SwingConstants.CENTER);
textField.setBounds(10, 143, 414, 35);
contentPane.add(textField);
textField.setColumns(10);
//Randomize button code
JButton btnNewButton = new JButton("Randomize!");
btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 40));
btnNewButton.setBounds(10, 196, 414, 54);
contentPane.add(btnNewButton);
//Label code
label = new JLabel();
label.setFont(new Font("Tahoma", Font.PLAIN, 70));
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setBounds(10, 11, 414, 103);
contentPane.add(label);
//math code
Random num = new Random();
strMax = textField.getText();
max = Integer.parseInt(strMax);
x = num.nextInt(max) + 1;
strX = String.valueOf(x);
label.setText(strX);
}
}
答案 0 :(得分:0)
您需要添加ActionListener,请参阅javadoc here
在没有更大讨论的情况下对代码进行简单修改就是提升模拟随机数的代码......
//Randomize button code
JButton btnNewButton = new JButton("Randomize!");
btnNewButton.setFont(new Font("Tahoma", Font.BOLD, 40));
btnNewButton.setBounds(10, 196, 414, 54);
contentPane.add(btnNewButton);
// the listener
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Random num = new Random();
String strMax = textField.getText();
int max = Integer.parseInt(strMax);
int x = num.nextInt(max) + 1;
String strX = String.valueOf(x);
label.setText(strX);
}
} );