Hello Guys,
I'm new to these forums as well as to Java and Swing.
So on my way to get a lil bit more knowledge on Swing, I wanted to build a simple GUI with a textfield (probably JEditorPane)
and a Button. Everytime I press the button I wanted the textfield to go through the alphabet, showing each letter of it.
I heard that because Swing is not threadsafe, you should put all non-thread-safe operations into the Event-Dispatch-Thread.
Still if I add a new Thread that reads the Alphabet into the EDT, the GUI freezes until the last letter is displayed.
Since I'm new to this I guess Im doing something wrong, and Id like to ask you for help.
import java.awt.*;
import javax.swing.*;
public class abcSwing extends JFrame{
Container c;
JEditorPane jep;
JButton butt;
ButtonListener BL;
public abcSwing () { //Konstruktor
c = getContentPane();
jep = new JEditorPane();
butt = new JButton("ABC");
c.add(jep,BorderLayout.NORTH);
c.add(butt,BorderLayout.CENTER);
BL = new ButtonListener(c, jep);
butt.addActionListener(BL);
}
public static void main (String[] args) {
abcSwing window = new abcSwing();
window.setTitle("Running the Alphabet");
window.setSize(350,200);
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.JEditorPane;
import javax.swing.SwingUtilities;
public class ButtonListener implements ActionListener {
Container c;
JEditorPane jep;
//Konstruktor
public ButtonListener (Container c, JEditorPane jep) {
this.c = c;
this.jep = jep;
}
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable () {
public void run () {
jep.setText("a");
MachMal.Pause();
jep.setText("b");
MachMal.Pause();
jep.setText("c");
}
});
}
}
public class MachMal {
public static void Pause() {
try {
Thread.sleep(2000);
}catch (InterruptedException e){
}
}
}
As you can see, Ive reduced the alphabet to A, B, C with a break in between each char of 2 secs. As a result the Gui freezes for 6 seconds then displays a "C" on the EditorPane.
My goal however is to get the A displayed, then after two seconds the B and so on...
Any ideas?
Edited by: 880650 on 21.08.2011 09:37