06. september 2012 - 20:57Der er
6 kommentarer og 1 løsning
How to update a text from actionPerformed
Hello guys!
I think this is about some swing-thread-knowledge. How ever.
I get a JButton, and a JTextField.
The idea is that when the user pushes the button, it will load a URL from a server. But since that might take some time. I think it would be nice with to info messages in a textfield like:
public class Paging extends JFrame implements ActionListener { private JTextField txt; private JButton btn; public Paging() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); getContentPane().setLayout(new BorderLayout()); txt = new JTextField(); txt.setText(""); getContentPane().add(txt, BorderLayout.CENTER); btn = new JButton("Vis nyt billede"); btn.addActionListener(this); getContentPane().add(btn, BorderLayout.SOUTH); this.setSize(300, 300); } public void load(String s) { txt.setText(s); } public void actionPerformed(ActionEvent ev) { if (ev.getSource() == btn) { T t = new T(this); t.start(); } } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { Paging f = new Paging(); f.setVisible(true); } }); } }
class T extends Thread { private static int n = 0; private Paging pag; public T(Paging dn) { this.pag = dn; } public void run() { SwingUtilities.invokeLater(new Runnable() { public void run() { pag.load("Nu viser vi billede af nogle pausefisk"); } }); try { Thread.sleep(1000); } catch (InterruptedException e) { } SwingUtilities.invokeLater(new Runnable() { public void run() { n++; pag.load("Nu viser vi et rigtigt billede nummer " + n); } }); } }
Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.