Re: [問題] Thread with JFileChooser

看板java作者 (!H45)時間16年前 (2009/04/02 10:47), 編輯推噓12(1208)
留言20則, 3人參與, 最新討論串1/1
:   我寫了個Swing的介面, 有個JButton在接收click的event之後, :   會使用Thread開啟JFileChooser, 但始終開不起來Orz... :   只是停用Thread後, 就可以了@@... 我 JFileChooser 開的起來 import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JOptionPane; public class TestDrive extends JFrame{ private JButton jButton1 = new JButton("Button"); public static void main(String[] args) { new TestDrive().setVisible(true); } public TestDrive() { setSize(640, 480); getContentPane().add(jButton1); jButton1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { Thread t = new Thread() { public void run() { open(); } }; t.start(); } }); } public void open() { JFileChooser chooser =new JFileChooser("."); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setMultiSelectionEnabled(true); //only choose file(s) int result = chooser.showOpenDialog(this); System.out.println(result); if (result == JFileChooser.APPROVE_OPTION) { try { for(File x:chooser.getSelectedFiles()) { showChoose(x); } } catch (Exception e) { } } } private void showChoose(File x) { JOptionPane.showMessageDialog(null, x); } } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.116.247.13

04/02 14:03, , 1F
Orz...居然跟public有關...我習慣同一個package內的方法
04/02 14:03, 1F

04/02 14:04, , 2F
都是用default...現在改成public, 就好了O___Q
04/02 14:04, 2F

04/02 14:25, , 3F
我想事情不是你想的那樣...可以的話提供一份可以重製出
04/02 14:25, 3F

04/02 14:28, , 4F
你描述的現象的程式碼,讓大家看看癥結在哪
04/02 14:28, 4F

04/02 14:32, , 5F
我的問題有放程式碼, 那個open是default level, 我學習H45大
04/02 14:32, 5F

04/02 14:33, , 6F
師, 將open改成public level就可以顯示JFileChooser了@__@
04/02 14:33, 6F

04/02 14:48, , 7F
你給的程式碼太片段了。真的不會是跟 access level 有關
04/02 14:48, 7F

04/02 15:13, , 8F
好像真的不是access level的問題Orz... 我放上完整的了@@
04/02 15:13, 8F

04/03 10:02, , 9F
不要在非EDT上建造gui
04/03 10:02, 9F

04/03 13:22, , 10F
EDT是指Event Dispatch Thread嗎?
04/03 13:22, 10F

04/03 16:09, , 11F
對,建造元件不會費時的話,就不需要用到thread
04/03 16:09, 11F

04/03 16:11, , 12F
費時的話,請使用SwingUtilities.invokeLater
04/03 16:11, 12F

04/03 16:57, , 13F
但是我是希望在open JFileChooser後還可以同步做其他的事
04/03 16:57, 13F

04/03 16:58, , 14F
所以我才直覺的使用thread, 若改成SwingUtilities也可以做到
04/03 16:58, 14F

04/03 16:59, , 15F
嗎? 謝謝, thanks a lot.
04/03 16:59, 15F

04/03 17:10, , 16F
我指的同步作其他事是類似可以同時輸入JTextField/Area等.
04/03 17:10, 16F

04/03 17:35, , 17F
SwingUtilities也是Thread
04/03 17:35, 17F

04/03 17:36, , 18F
SwingUtilities.invokeLater
04/03 17:36, 18F

04/03 19:36, , 19F
不必擔心 JFileChooser 秀出 dialog 會 block UI-thread
04/03 19:36, 19F

04/03 19:37, , 20F
否則,連 JFileChooser 自己的 UI 也無法使用了,不是嗎
04/03 19:37, 20F
文章代碼(AID): #19r2SnZ_ (java)