所以我相信这个代码的问题在于ActionListner。运行程序时,我输入一个数字,没有任何反应。程序运行正常的唯一数字是当我输入数字2.我明显在for循环中做错了但我还没有能够弄明白。
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.text.*;
public class Prime implements ActionListener {
JFrame framePrime;
JPanel panelPrime;
JTextField primeTestField;
JLabel stringPrimelLabel, enterNumLabel, trueFalseLabel;
// Constructor
public Prime() {
// Create the frame and container.
framePrime = new JFrame("Prime or Not?");
panelPrime = new JPanel();
panelPrime.setLayout(new GridLayout(2, 2));
// Add the widgets.
addWidgets();
// Add the panel to the frame.
framePrime.getContentPane().add(panelPrime, BorderLayout.CENTER);
// Exit when the window is closed.
framePrime.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Show the converter.
framePrime.pack();
framePrime.setVisible(true);
}
// Create and add the widgets for converter.
private void addWidgets() {
// Create widgets.
primeTestField = new JTextField();
primeTestField.setHorizontalAlignment(JTextField.CENTER);
enterNumLabel = new JLabel("Enter a number: ",
SwingConstants.LEFT);
stringPrimelLabel = new JLabel("Is it Prime?: ",
SwingConstants.LEFT);
trueFalseLabel = new JLabel("Let's Find Out!",
SwingConstants.CENTER);
// Listen to events from Convert textfield.
primeTestField.addActionListener(this);
// Add widgets to container.
panelPrime.add(enterNumLabel);
panelPrime.add(primeTestField);
panelPrime.add(stringPrimelLabel);
panelPrime.add(trueFalseLabel);
panelPrime.setBackground(Color.red);
}
// Implementation of ActionListener interface.
public void actionPerformed(ActionEvent event) {
int n = Integer.parseInt(primeTestField.getText());
if (n == 2) {
trueFalseLabel.setText("Yes");
}
else {
for (int i = 2; 2*i < n; i++) {
if(n % i == 0){
trueFalseLabel.setText("No");
}
else {
trueFalseLabel.setText("Yes");
}
}
}
}
// main method
public static void main(String[] args) {
Prime converter = new Prime();
}
}
答案 0 :(得分:1)
ActionListener
JTextField。
编辑:如果要在文本字段中更改值时进行素数检查。正如@MadProgrammer所建议的那样,您可以在文本字段的文档中添加DocumentListener
并实现insertUpdate
(在添加字符时调用)和removeUpdate
(在删除时调用)字符)方法。
primeTestField.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e)
check();
}
@Override
public void removeUpdate(DocumentEvent e) {
check();
}
@Override
public void changedUpdate(DocumentEvent e) {
}
});
(PS:我纠正并将你的主要检查逻辑重构为方法,以便它是正确的和可重复的)
private void check() {
int n;
try {
System.out.println(primeTestField.getText());
n = Integer.parseInt(primeTestField.getText());
} catch (Exception ex) {
return;
}
if (n == 2) {
trueFalseLabel.setText("Yes");
} else {
boolean isPrime = true;
for (int i = 2; 2 * i < n; i++) {
if (n % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
trueFalseLabel.setText("Yes");
} else {
trueFalseLabel.setText("No");
}
}
}