开发者

Java GUI Menu Issues

开发者 https://www.devze.com 2023-02-10 20:23 出处:网络
statCl.addActionListener(new ActionListener(){ public void actionPerformed (ActionEvent e) { try { ta.append(\"Searching...\\n\");
statCl.addActionListener(new ActionListener(){
        public void actionPerformed (ActionEvent e) {
            try {
            ta.append("Searching...\n");
            //Do Some stuff, call some classes etc
                ta.append("Search Complete\n");
            } catch (Exception IOE) {}
        }
 });

This might seem like an odd question but I'm having a couple of issues with my GUI. Basically, I want it so you click through the JMenu, get to the item you want, click that and it runs the code above.

However, when you click the button, it sort of freezes whilst it runs the processes inside the actionListener etc. It then eventually continues, clos开发者_如何学JAVAes the menu and lets the user carry on. Problem is, it sort of looks like the program has crashed.

Ideally, I'd like it so the user clicks, the text 'Searching...' appears, the process runs and then once the process is done it prints out 'Search Complete'

I've tried moving things in and out of the try/catch, I've tried adding a separate actionListener for the same item and no luck

Any ideas would be really appreciated.


You need to use a SwingWorker.

All updates to the user interface must occur on the Event Dispatch Thread (EDT). The code inside your action listener gets called on the EDT too. Which means that while your code is running, the UI will not update.

The normal way to handle this is to have the long-running code run inside a SwingWorker. SwingUtilities.invokeLater can then be used to let your long-running code call methods to update the UI, which must happen on the EDT.


Try using the SwingWorker.

0

精彩评论

暂无评论...
验证码 换一张
取 消