Añada un botón de Stop a la aplicación de NumeroPrimos.java para poder detenerla antes de terminar
Publicado por Marcos (5 intervenciones) el 07/03/2020 17:32:08
si me pueden ayudar se lo voy agradeser.
Añada un botón de Stop a la aplicación de NumeroPrimos.java para poder detenerla antes de terminar.
Añada un botón de Stop a la aplicación de NumeroPrimos.java para poder detenerla antes de terminar.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package com.java8talleres;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class NumeroPrimos extends JFrame implements Runnable, ActionListener {
Thread go;
JLabel howManyLabel;
JTextField howMany;
JButton display;
JTextArea primes;
public NumeroPrimos() {
super("Find Prime Numbers");
setLookAndFeel();
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BorderLayout bord = new BorderLayout();
setLayout(bord);
howManyLabel = new JLabel("Quantity: ");
howMany = new JTextField("400", 10);
display = new JButton("Display primes");
primes = new JTextArea(8, 40);
display.addActionListener(this);
JPanel topPanel = new JPanel();
topPanel.add(howManyLabel);
topPanel.add(howMany);
topPanel.add(display);
add(topPanel, BorderLayout.NORTH);
primes.setLineWrap(true);
JScrollPane textPane = new JScrollPane(primes);
add(textPane, BorderLayout.CENTER);
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
display.setEnabled(false);
if (go == null) {
go = new Thread(this);
go.start();
}
}
public void run() {
int quantity = Integer.parseInt(howMany.getText());
int numPrimes = 0;
// candidate: the number that might be prime
int candidate = 2;
primes.append("First " + quantity + " primes:");
while (numPrimes < quantity) {
if (isPrime(candidate)) {
primes.append(candidate + " ");
numPrimes++;
}
candidate++;
}
}
public static boolean isPrime(int checkNumber) {
double root = Math.sqrt(checkNumber);
for (int i = 2; i <= root; i++) {
if (checkNumber % i == 0) {
return false;
}
}
return true;
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
} catch (Exception exc) {
// ignore error
}
}
public static void main(String[] arguments) {
new NumeroPrimos();
}
Valora esta pregunta


0