Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.ActionEvent;
- public class SE3SimpleGui {
- private volatile JFrame frame;
- private volatile JButton btn;
- private volatile JTextField txt;
- private volatile Count count;
- private volatile Paint paint;
- private volatile boolean currentlyCounting;
- private void createAndShow() {
- /* Threads instanziieren */
- currentlyCounting = false;
- /* links: ein Button mit Beschriftung */
- btn = new JButton();
- btn.addActionListener(new ActionListener());
- btn.setText("Start");
- /* rechts: ein Textfeld */
- txt = new JTextField();
- /* Hauptfenster */
- frame = new JFrame();
- /* Aktion beim schließen: JVM beenden */
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- /* Layout festlegen und Button & Textfeld hinzufügen */
- frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(),
- BoxLayout.X_AXIS));
- frame.getContentPane().add(btn);
- frame.getContentPane().add(txt);
- /* Größe setzen und anzeigen */
- frame.setPreferredSize(new Dimension(300, 100));
- frame.pack();
- frame.setVisible(true);
- }
- public static void main(String[] args) {
- /* Im EDT ausführen: new SE3SimpleGui().createAndShow(); */
- javax.swing.SwingUtilities.invokeLater(new Runnable() {
- public void run() {
- new SE3SimpleGui().createAndShow();
- }
- });
- }
- private class ActionListener implements java.awt.event.ActionListener {
- @Override
- public void actionPerformed(ActionEvent e) {
- if (!currentlyCounting) {
- btn.setText("Stop");
- count = new Count();
- paint = new Paint(count);
- count.start();
- paint.start();
- } else {
- btn.setText("Start");
- count.stopping();
- paint.stopping();
- }
- currentlyCounting = !currentlyCounting;
- frame.pack();
- }
- }
- private class Count extends Thread {
- private volatile boolean stopped = false;
- private volatile int count;
- @Override
- public void run() {
- while (!stopped) {
- count++;
- }
- }
- public void stopping() {
- this.stopped = true;
- }
- }
- private class Paint extends Thread {
- private volatile boolean stopped = false;
- private Count c;
- public Paint(Count c) {
- this.c = c;
- }
- @Override
- public void run() {
- while (!stopped) {
- txt.setText(String.valueOf(c.count));
- frame.pack();
- try {
- Thread.sleep(500);
- } catch (InterruptedException ex) {
- System.err.println("Error Paint");
- }
- }
- }
- public void stopping() {
- this.stopped = true;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement