Re: [問題] 如何在視窗輸入參數後,繼續執行main?

看板java作者 (畢業了..@@")時間13年前 (2012/12/21 16:52), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串6/7 (看更多)
發現真的很多人想要在main去拿UI的資料耶... 我隨便寫一個...拿去用用看 https://gist.github.com/4351530 //MyFrame.java package cc.ptt.popcorny; import java.awt.BorderLayout; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.JFrame; import javax.swing.JTextField; public class MyFrame extends JFrame { private static final long serialVersionUID = 1L; private Object lock; private String result; private JTextField textField; public MyFrame() { super("this is a test"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); textField = new JTextField(); getContentPane().add(textField, BorderLayout.CENTER); pack(); lock = new Object(); addWindowListener(new WindowListener() { public void windowOpened(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} public void windowClosing(WindowEvent e) {} public void windowClosed(WindowEvent e) { notifyResult(textField.getText()); } public void windowActivated(WindowEvent e) {} }); textField.addKeyListener(new KeyListener() { public void keyTyped(KeyEvent e) {} public void keyReleased(KeyEvent e) {} public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_ENTER) { dispose(); } } }); } private void notifyResult(String result) { this.result = result; synchronized (lock) { lock.notify(); } } public String waitForResult() throws InterruptedException { synchronized (lock) { lock.wait(); } return result; } /** * @param args */ public static void main(String[] args) throws Exception{ MyFrame frame = new MyFrame(); frame.setVisible(true); String result = frame.waitForResult(); System.out.println(result); } } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.135.251.162
文章代碼(AID): #1Gr2C-G_ (java)
討論串 (同標題文章)
文章代碼(AID): #1Gr2C-G_ (java)