消息框(Message box)

视窗环境下通常包含了一组标准的消息框,使你能够快速地把消息通知给用户,或者是从
用户那里得到信息。在 Swing 中,这些消息框包含在 JoptionPane 组件里。你有许多选
择(有些非常高级),但最常用的可能就是消息对话框和确认对话框,它们分别可以通过
调用静态的 JOptionPane.showMessageDialog( )和
JOptionPane.showConfirmDialog( )方法得到。下面的例子演示了 JoptionPane 中一
些可用的消息框。


//: c14:MessageBoxes.java
// Demonstrates JoptionPane.
// <applet code=MessageBoxes width=200 height=150></applet>
import javax.swing.*;
import java.awt.event.*; 
import java.awt.*; 
import com.bruceeckel.swing.*; 


public class MessageBoxes extends JApplet { 
private JButton[] b = { 
new JButton("Alert"), new JButton("Yes/No"),
new JButton("Color"), new JButton("Input"), 
new JButton("3 Vals")
  };
private JTextField txt = new JTextField(15); 
private ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) { 
 






      String id = ((JButton)e.getSource()).getText(); 
if(id.equals("Alert"))
        JOptionPane.showMessageDialog(null,
"There's a bug on you!", "Hey!",
          JOptionPane.ERROR_MESSAGE); 
else if(id.equals("Yes/No")) 
        JOptionPane.showConfirmDialog(null,
"or no", "choose yes",
          JOptionPane.YES_NO_OPTION); 
else if(id.equals("Color")) {
        Object[] options = { "Red", "Green" };
int sel = JOptionPane.showOptionDialog( 
null, "Choose a Color!", "Warning",
          JOptionPane.DEFAULT_OPTION, 
          JOptionPane.WARNING_MESSAGE, null,
          options, options[0]); 
if(sel != JOptionPane.CLOSED_OPTION)
          txt.setText("Color Selected: " + options[sel]); 
      } else if(id.equals("Input")) {
        String val = JOptionPane.showInputDialog( 
"How many fingers do you see?");
        txt.setText(val); 
      } else if(id.equals("3 Vals")) { 
        Object[] selections = {"First", "Second", "Third"};
        Object val = JOptionPane.showInputDialog( 
null, "Choose one", "Input",
          JOptionPane.INFORMATION_MESSAGE, 
null, selections, selections[0]);
if(val != null)
          txt.setText(val.toString()); 
      }
    }
  };
public void init() { 
    Container cp = getContentPane(); 
    cp.setLayout(new FlowLayout()); 
for(int i = 0; i < b.length; i++) { 
      b[i].addActionListener(al);
      cp.add(b[i]);
    }
    cp.add(txt);
  }
public static void main(String[] args) { 
    Console.run(new MessageBoxes(), 200, 200); 
 






  }
} ///:~


为了能够只编写一个单一的ActionListener,我使用了检查按钮上字符串标签的方法来判
断事件的来源,这有点冒险。其问题在于标签可能会有拼写错误,尤其是大小写,这种Bug
很难发现。


注意,showOptionDialog( )和showInputDialog( )方法提供了返回对象,此对象包含

了用户输入的信息。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值