62,614
社区成员
发帖
与我相关
我的任务
分享
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JOptionPanelDemo implements ActionListener {
JFrame frame=new JFrame("JOptionPane Demo");
JTextField tf=new JTextField();
JButton messageButton,ConfirmButton,InputButton,OptionButton;
public static void main(String args[]){
JOptionPanelDemo opd=new JOptionPanelDemo();
opd.go();
}
public void go() {
messageButton=new JButton("Message Dialog");
messageButton.addActionListener(this);
ConfirmButton=new JButton("ConfirmButton Dialog");
ConfirmButton.addActionListener(this);
InputButton=new JButton("InputButton Dialog");
InputButton.addActionListener(this);
OptionButton=new JButton("OptionButton Dialog");
OptionButton.addActionListener(this);
JPanel jp=new JPanel();
jp.add(messageButton);
jp.add(ConfirmButton);
jp.add(InputButton);
jp.add(OptionButton);
Container cp=frame.getContentPane();
cp.add(jp,BorderLayout.CENTER);
cp.add(tf,BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
JButton button=(JButton)e.getSource();
//信息对话框
if(button==messageButton) {
JOptionPane.showMessageDialog(frame,"Field not found.","An error",JOptionPane.ERROR_MESSAGE);
}
//确认对话框
if(button==ConfirmButton) {
int select=JOptionPane.showConfirmDialog(frame,"Create one","Confirm",JOptionPane.YES_NO_OPTION);
if(select==JOptionPane.YES_OPTION) {
tf.setText("Choose YES");
if(select==JOptionPane.NO_OPTION) {
tf.setText("Choose NO");
if(select==JOptionPane.CLOSED_OPTION) {
tf.setText("Choose CLOSE");
}
//输入对话框
if(button==InputButton) {
Object[] possibleValues={"First","Second","Third"};
Object selectedValue=JOptionPane.showInputDialog(frame,
"Choose one","Input",JOptionPane.INFORMATION_MESSAGE,null,
possibleValues,possibleValues[0]);
if(selectedValue!=null)
tf.setText(selectedValue.toString());
else
tf.setText("Closed");
}
//选项对话框
if(button==OptionButton) {
Object[]options={"OK","CANCEL"};
int select1=JOptionPane.showOptionDialog(frame,"Click OK to continue",
"Warning",JOptionPane.DEFAULT_OPTION,JOptionPane.WARNING_MESSAGE,
null,options,options[0]);
if(select1==0)
tf.setText("choose OK");
else if(select1==1)
tf.setText("choose CANCEL");
else if(select1==-1)
tf.setText("Closed");
}
}
}
if(button==ConfirmButton) {
int select=JOptionPane.showConfirmDialog(frame,"Create one","Confirm",JOptionPane.YES_NO_OPTION);
if(select==JOptionPane.YES_OPTION) {
tf.setText("Choose YES");
if(select==JOptionPane.NO_OPTION) {
tf.setText("Choose NO");
if(select==JOptionPane.CLOSED_OPTION) {
tf.setText("Choose CLOSE");
}