2013-06-18 89 views
3

我想在用戶點擊「從文件加載」按鈕時創建一個彈出窗口。我希望那個彈出框有一個文本框和一個「確定」「取消」選項。如何製作只有文本字段的彈出窗口?

我已經通讀了很多Java文檔,並且我沒有看到簡單的解決方案,感覺就像我缺少一些東西,因爲如果有一個JOptionPane允許我向用戶顯示文本框,爲什麼沒有辦法檢索文字?

除非我想創建一個「在文本框中輸入文本並點擊確定」程序,但這就是我現在正在做的。

+0

您是否試圖在用戶按下ok之前或之後獲得輸入文本? –

回答

6

事實上,你可以檢索與一個JOptionPane的用戶輸入的文本:

String path = JOptionPane.showInputDialog("Enter a path"); 

有一個關於JOptionPane的一個偉大壯舉在Java教程: http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html

但如果你真的需要的用戶選擇路徑/文件,我想你,而要顯示一個JFileChooser:

JFileChooser chooser = new JFileChooser(); 
if(chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { 
    File selectedFile = chooser.getSelectedFile(); 
} 

否則,你可以走了艱辛的道路並通過使用JDialog創建您自己的對話框,其中包含您想要的所有內容。

編輯

下面是一個簡單的例子,以幫助您創建主窗口。 使用Swing,使用JFrame創建窗口。

// Creating the main window of our application 
final JFrame frame = new JFrame(); 

// Release the window and quit the application when it has been closed 
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 

// Creating a button and setting its action 
final JButton clickMeButton = new JButton("Click Me!"); 
clickMeButton.addActionListener(new ActionListener() { 

    public void actionPerformed(ActionEvent e) { 
     // Ask for the user name and say hello 
     String name = JOptionPane.showInputDialog("What is your name?"); 
     JOptionPane.showMessageDialog(frame, "Hello " + name + '!'); 
    } 
}); 

// Add the button to the window and resize it to fit the button 
frame.getContentPane().add(clickMeButton); 
frame.pack(); 

// Displaying the window 
frame.setVisible(true); 

我還是建議你遵循Java Swing GUI的教程,因爲它包含了你需要開始一切。

+1

你介紹給我的那個頁面是我曾經說過的那個頁面,我說的是我看過但沒有找到簡單的解決方案。它看起來像是說我必須創建一個自定義對話框並添加一個WindowListener或其他東西(我從來沒有使用過)。我迷失在他們添加propertyChangeListener的部分。 感謝JFileChooser提示,我也在尋找。不過,我正在重寫一份來自學校的舊作業,並遵循規範。 – OKGimmeMoney

相關問題