我们可以将 Swing 组件添加到JOptionPane
. 那么为什么不创建一个包含JLabel
和JTextFeild
布局的自定义面板,即,FlowLayout
并将该面板添加到 JOptionPane 使用
JOptionPane.showConfirmDialog
(
frame, // main window frame
customPanel, // custom panel containing the label and textFeild
"My Panel with Text Feild", // Title
JOptionPane.OK_CANCEL_OPTION, // with OK and CANCEL button
JOptionPane.PLAIN_MESSAGE
);
一个最小的工作示例:
import java.awt.event.*;
import javax.swing.*;
class CustomPanel extends JPanel
{
JLabel lab;
JTextField txtField;
public CustomPanel() {
lab = new JLabel("Some Text: ");
txtField = new JTextField(20);
add(lab);
add(txtField);
}
public String getText()
{
return txtField.getText();
}
}
public class JOptionPaneDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
CustomPanel inputPane = new CustomPanel();
int value = JOptionPane.showConfirmDialog(null, inputPane, "Demo" ,JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if(value == JOptionPane.OK_OPTION)
{
JOptionPane.showMessageDialog(null, "Value Entered: "+inputPane.getText(), "Demo", JOptionPane.INFORMATION_MESSAGE);
}
}
});
}
}
教程资源: 如何进行对话