Я создаю приложение Java Swing с SwingWorker с JTextField и JButton.Внутри SwingWorker я создал 2 потока (один - для отображения JDialog с сообщением, а другой - для проверки, является ли введенное значение в JTextField правильным целым числом или нет).Я выполняю эти темы, нажимая на кнопку JButton.Если значение является целым числом, будет отображено успешное сообщение (нажатие на это сообщение не закроет основной JFrame).Если это String, будет выдано исключение с сообщением об ошибке (в этом сценарии я также не закрываю основной JFrame).После закрытия сообщения об исключении, даже если я введу правильное целочисленное значение и нажму кнопку JButton, потоки не будут выполняться в этот раз.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
import javax.swing.WindowConstants;
import javax.swing.text.DefaultCaret;
class MyThread extends Thread {
public JPanel panel;
public JLabel label;
public JDialog progressDialog;
private volatile boolean flag = true;
public String value;
public MyThread() {
}
public void createJDialog() {
progressDialog = new JDialog();
panel = new JPanel();
label = new JLabel();
label.setBounds(20,-20,560,120);
panel.setBounds(0,-10,570,120);
panel.add(label);
panel.setLayout(null);
progressDialog.add(panel);
progressDialog.setSize(580,95);
progressDialog.setLocationRelativeTo(null);
progressDialog.setLayout(null);
progressDialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
progressDialog.setVisible(true);
}
public void startThreads() {
createJDialog();
try {
t1.start();
Thread.sleep(1000);
t2.start();
Thread.sleep(2000);
} catch (Exception e) {
}
}
Thread t1 = new Thread(new Runnable() {
public void run() {
while (flag) {
try {
progressDialog.setTitle(" Thread Test...");
for (int i = 1; i < 100; i++) {
label.setText("Checking values ");
Thread.sleep(500);
label.setText("Checking values .");
Thread.sleep(500);
label.setText("Checking values . .");
Thread.sleep(500);
label.setText("Checking values . . . ");
Thread.sleep(500);
}
} catch (Exception e) {
e.printStackTrace();
}
flag = false;
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
flag = true;
while (flag) {
try {
value = ThreadTest.textField1.getText().trim();
checkValues(value);
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
flag = false;
}
}
});
public void checkValues(String value) {
try {
int intValue = Integer.parseInt(value);
JOptionPane.showMessageDialog(null, "Successful, proper integer value - " + intValue, "Checking value", JOptionPane.OK_OPTION);
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "Enter proper integer value", "Exception in checking value", JOptionPane.OK_OPTION);
progressDialog.setVisible(false);
flag = false;
ThreadTest.verifyBtn.setEnabled(true);
return;
}
}
public void stopRunning() {
flag = false;
}
}
public class ThreadTest {
public static MyThread myThread;
public static volatile boolean isValueCheckSuccessful = true;
public static boolean isTextAreaDisplayed;
public static DefaultCaret caret;
public static JFrame mainFrame;
public static JPanel topPanel;
public static JLabel textFieldLbl1;
public static JTextField textField1;
public static JLabel textFieldLbl2;
public static JTextField textField2;
public static JPanel bottomPanel;
public static JTextArea textArea;
public static JScrollPane scrollPane;
public static JButton verifyBtn;
public ThreadTest() {
mainFrame = new JFrame("Thread Test");
mainFrame.setSize(330, 220);
topPanel = new JPanel();
topPanel.setBounds(5,5,310,180);
topPanel.setLayout(null);
textFieldLbl1 = new JLabel("Enter value 1 : ");
textFieldLbl1.setBounds(5,5,100,20);
textField1 = new JTextField();
textField1.setBounds(120,5,150,25);
textField1.setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.BLACK));
textFieldLbl2 = new JLabel("Enter value 2 : ");
textFieldLbl2.setBounds(5,35,100,20);
textField2 = new JTextField();
textField2.setBounds(120,35,150,25);
textField2.setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.BLACK));
topPanel.add(textField1);
topPanel.add(textFieldLbl1);
verifyBtn = new JButton("Verify");
verifyBtn.setBounds(120,120,70,30);
topPanel.add(verifyBtn);
mainFrame.setResizable(false);
mainFrame.add(topPanel);
mainFrame.setLayout(null);
mainFrame.setLocationRelativeTo(null);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
}
public static void main(String[] args) {
new ThreadTest();
myThread = new MyThread();
verifyBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
SwingWorker<Object, Object> swingWorker = new SwingWorker<Object, Object>() {
@Override
protected Object doInBackground() throws Exception {
try {
isValueCheckSuccessful = true;
if (!isTextAreaDisplayed) {
mainFrame.setSize(330,420);
mainFrame.setLocationRelativeTo(null);
bottomPanel = new JPanel();
bottomPanel.setLayout(new BorderLayout());
bottomPanel.setBounds(3,195,320,90);
textArea = new JTextArea();
textArea.setEditable(false);
textArea.setBounds(5,5,280,80);
caret = (DefaultCaret) textArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
scrollPane = new JScrollPane(textArea);
bottomPanel.add(scrollPane, BorderLayout.CENTER);
Thread.sleep(10);
mainFrame.add(bottomPanel);
mainFrame.revalidate();
isTextAreaDisplayed = true;
}
textArea.append("*********** Execution Started ***********\n");
verifyBtn.setEnabled(false);
Thread.sleep(50);
textArea.append("Values entered by user:\n");
textArea.append("--------------------------------\n");
textArea.append(" Value 1 = " + textField1.getText() + "\n");
Thread.sleep(100);
myThread.startThreads();
myThread.stopRunning();
myThread.progressDialog.setVisible(false);
verifyBtn.setEnabled(true);
} catch (Exception e) {
}
return null;
}
};
swingWorker.execute();
}
});
}
}
Ожидается: если возникает исключение, нажатие JButton должно снова выполнить оба потока после закрытияэто исключение.