Input Dialog可以让用户输入相关信息,当用户按下确定钮后,系统会得到用户所输入的信息.输入对话框不仅可以让用户自输入 文字,也可以显示出ComboBox组件让用户选择相关信息,避免用户输入错误,当用户输入完毕按下确定按钮时会返回用户输入的信息, 若按下取消则返回null值.下面为InputDialog的范例.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import com.incors.plaf.alloy.*;
import com.incors.plaf.alloy.themes.glass.*;
public class InputDialog implements ActionListener
{
JFrame f = null;
JLabel label = null;
public InputDialog()
{
f = new JFrame("OptionPane Demo");
Container contentPane = f.getContentPane();
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(1,2));
JButton b = new JButton("Show Text Input");
b.addActionListener(this);
panel.add(b);
b = new JButton("Show ComboBox Input");
b.addActionListener(this);
panel.add(b);
label = new JLabel(" ",JLabel.CENTER);
contentPane.add(label,BorderLayout.NORTH);
contentPane.add(panel,BorderLayout.CENTER);
f.pack();
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args)
{
SwingUtil.setLookAndFeel();
new InputDialog();
}
public void actionPerformed(ActionEvent e)
{
String cmd = e.getActionCommand();
String title = "Input Dialog";
String message ="您最熟悉哪一种程序语言?";
int messageType = JOptionPane.QUESTION_MESSAGE;
String[] values = {"JAVA","PHP","ASP","C++","VB"};
String result ="";
if(cmd.equals("Show Text Input")) {
result = JOptionPane.showInputDialog(f, message,
title, messageType);
} else if(cmd.equals("Show ComboBox Input")) {
result = (String)JOptionPane.showInputDialog(f, message,
title, messageType,null,values,values[0]);
}
if (result == null)
label.setText("您取消了对话框");
else{
label.setText("您输入:"+result);
}
}
}
class SwingUtil{
public static final void setLookAndFeel() {
try{
Font font = new Font("JFrame", Font.PLAIN, 12);
Enumeration keys = UIManager.getLookAndFeelDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
if (UIManager.get(key) instanceof Font) {
UIManager.put(key, font);
}
}
AlloyLookAndFeel.setProperty("alloy.isLookAndFeelFrameDecoration", "true");
AlloyTheme theme = new GlassTheme();
LookAndFeel alloyLnF = new AlloyLookAndFeel(theme);
UIManager.setLookAndFeel(alloyLnF);
}catch(UnsupportedLookAndFeelException ex){
ex.printStackTrace();
}
}
}