Hey,
ich habe ein Programm mit 2 Buttons (Start und Stopp).
Bei Start kommt man in eine While-Schleife rein.
Wenn ich Stopp drücke, soll diese natürlich gestoppt werden.
Wie realisiere ich das am besten?
Start.java
ListenerAction.java
Controller.java
Gui.java
gruß Holly
ich habe ein Programm mit 2 Buttons (Start und Stopp).
Bei Start kommt man in eine While-Schleife rein.
Wenn ich Stopp drücke, soll diese natürlich gestoppt werden.
Wie realisiere ich das am besten?
Start.java
Java:
public class Start {
public static void main(String[] args) {
ListenerAction listenerAction = new ListenerAction();
Controller controller = new Controller();
new Gui(listenerAction);
listenerAction.setController(controller);
}
}
ListenerAction.java
Java:
public class ListenerAction implements ActionListener {
private Controller controller;
public void setController(Controller controller) {
this.controller = controller;
}
public void actionPerformed(ActionEvent e) {
String aktion = e.getActionCommand();
if (aktion.equals(Gui.JB_START)) {
controller.start();
} else if (aktion.equals(Gui.JB_STOPP)) {
controller.stopp();
}
}
}
Controller.java
Java:
public class Controller extends Thread {
private boolean aktive;
public Controller() {
this.aktive = false;
}
public void start() {
this.aktive = true;
while (aktive) {
// .......
}
}
public void stopp() {
this.aktive = false;
}
}
Gui.java
Java:
@SuppressWarnings("serial")
public class Gui extends JFrame {
public static final String JB_START = "Start";
public static final String JB_STOPP = "Stopp";
public Gui(ListenerAction listenerAction) {
super("...");
konfiguriereFenster();
setzeIcon();
befuelleFenster(listenerAction);
this.pack();
this.setVisible(true);
}
private void setzeIcon() {
ImageIcon imageIcon = new ImageIcon("img/icon.jpg");
Image image = imageIcon.getImage();
this.setIconImage(image);
}
private void konfiguriereFenster() {
this.setPreferredSize(new Dimension(300, 70));
this.setLayout(new GridLayout());
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void befuelleFenster(ListenerAction listenerAction) {
JButton jbStart = new JButton(JB_START);
JButton jbStopp = new JButton(JB_STOPP);
jbStart.addActionListener(listenerAction);
jbStopp.addActionListener(listenerAction);
this.add(jbStart);
this.add(jbStopp);
}
}
gruß Holly