好的,我很抱歉,我正在重复已经被问到的问题,但我已经搜索过并搜索过,没有人的答案似乎帮助了我......我尝试了以下问题:
JButton "stay pressed" after click in Java Applet
JButton stays pressed when focus stolen by JOptionPane
(如果我只是愚蠢而道歉......很难与我的代码联系起来)
我已尝试过所有内容:使用另一个线程处理所有内容,将JFrame更改为JDialog
,因为它们显然是“模态”的,因此它可以独立工作。但这似乎也没有用。我现在被卡住所以我正在使用我的最后一个资源(询问Stack Overflow)。
我要做的是让用户在文本字段中输入一些数字(4,2,7),然后按JButton
“计算均值”,它会找到数字和显示的平均值它在JOptionPane
消息中。当用户关闭JOptionPane
对话框时,他们应该能够编辑数字并再次执行,但“计算均值”按钮保持按下状态,用户除了关闭窗口外无法执行任何操作。即使按Tab键也不会改变任何东西。有人知道为什么吗?我的代码如下:
如果我的代码很难阅读,请原谅我!我花了很长时间试图将它全部缩进,我还试图通过取出与问题无关的任何一点来尽可能地缩短它。我不确定要取出哪些位,所以仍然可能会有一些不必要的位...... 我很抱歉我的代码很乱,但这是代码:
package MathsProgram_II;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
public class Mean implements Runnable {
JFrame meanFrame = new JFrame(); //I tried changing this to dialog
JPanel meanPanel = new JPanel(new GridBagLayout());
JLabel enterNums = new JLabel("Enter Numbers: ");
JTextField txtNums = new JTextField(20);
JButton calculate = new JButton("Calculate Mean");
boolean valid = true;
double answer = 0;
ButtonListener bl = new ButtonListener();
public synchronized double[] getArray() {
String nums = txtNums.getText();
String[] numsArray = nums.split(",");
double[] doubleArray = new double[numsArray.length];
if (nums.isEmpty() == true) {
JOptionPane.showMessageDialog(meanFrame, "You did not enter anything!",
"Fail", JOptionPane.ERROR_MESSAGE);
valid = false;
calculate.setEnabled(false);
} else {
for (int i = 0; i < numsArray.length; i++) {
try {
doubleArray[i] = Double.parseDouble(numsArray[i]);
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(meanFrame, "Error getting numbers!",
"Error", JOptionPane.ERROR_MESSAGE);
valid = false;
}
}
}
return doubleArray;
}
public synchronized void calculateMean() {
ArrayList<Double> numbersList = new ArrayList<Double>(20);
double[] theNumbers = getArray();
double tempAnswer = 0;
if (valid == true) {
int length = theNumbers.length;
for (int i = 0; i < theNumbers.length; i++) {
numbersList.add(theNumbers[i]);
}
for (int i = 0; i < length; i++) {
double y = numbersList.get(i);
tempAnswer = tempAnswer + y;
}
this.answer = tempAnswer / length;
//I ALSO TRIED DOING THIS:
txtNums.requestFocus();
calculate.setEnabled(false);
showMean();
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
}
public void showMean() {
JOptionPane.showMessageDialog(meanFrame, "The Mean: " + answer, "The Mean of Your Numbers", JOptionPane.INFORMATION_MESSAGE);
}
private class ButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == calculate) {
meanFrame.remove(meanPanel);
meanFrame.setVisible(true);
calculateMean();
}
}
}
}
答案 0 :(得分:0)