天天看點

第14章 視窗和對話框

第14章 視窗和對話框

  Swing的視窗(window)、窗體(frame)和對話框(dialog)是分别擴充AWT的window類Frame類和Dialog類的重量元件。當這三個元件都是視窗時,這三個元件之間的差别是不明顯的,是以,有時在給定情況下要确定使用哪個元件是很困難的。為了澄清這些差别,表14-1列出了與這三個元件有關的一些屬性。

        表14-1 視窗、窗體和對話框屬性①,②

  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

  屬性     視窗   窗體     對話框

  ─────────────────────────────────

  模态      否    否     否/CSG

  可調整大小   否    否/SG    是/SG

  标題欄     否    是      是

  邊框      否    是      是

  标題      否    是/CSG    是/CSG

  菜單欄     否    是/SG    否

  焦點管理器   是    是      是

  警告字元串   是/G   是/G     是/G

  圖示圖像③   否    是/SG    否

  連結到一個窗體  是   否      是

  ①是/否指預設的屬性狀态

  ②C=在構造時可設定,S=可使用的設定方法,G=可使用的擷取方法(即get...()或is...())

  ③不是所有的平台都支援視窗的圖示化。

  視窗是這三個元件中最基本的元件,事實上,java.awt.Window是Frame和Dialog的超類。視窗沒有邊框、标題欄或菜單欄,而且不能調整其大小。如果需要在其他元件之上的無邊框矩形區域中顯示某些内容,則視窗是最合适的。

14.1 JWindow

例14-1 使用JWindow來實作一個splash視窗

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

// This has been modified from the code in the book

// to display the animated swing.gif in a window in the corner

// of your desktop. A double click closes the window.

public class Test extends JFrame {

Toolkit toolkit = Toolkit.getDefaultToolkit();

JWindow window = new JWindow();

JLabel label = new JLabel(new ImageIcon("swing.gif"));

static public void main(String[] args) {

JFrame frame = new Test();

}

public Test() {

//label.setBorder(BorderFactory.createRaisedBevelBorder());

window.getContentPane().add(label, "Center");

//centerWindow();

// change location to suite taste ...

window.setLocation(75,10);

window.pack();

window.show();

window.addMouseListener(new MouseAdapter() {

public void mousePressed(MouseEvent e) {

if(e.getClickCount() == 2) {

window.dispose();

System.exit(0);

});

private void centerWindow() {

Dimension scrnSize = toolkit.getScreenSize();

Dimension labelSize = label.getPreferredSize();

int labelWidth = labelSize.width,

labelHeight = labelSize.height;

window.setLocation(scrnSize.width/2 - (labelWidth/2),

scrnSize.height/2 - (labelHeight/2));

例14-2 一個作為應用程式視窗使用的JWindow執行個體

public class Test extends JApplet {

JMenuBar menuBar = new JMenuBar();

JMenu fileMenu = new JMenu("File");

JMenuItem quitItem;

final Container contentPane = getContentPane();

JButton button = new JButton("show window ...");

contentPane.setLayout(new FlowLayout());

contentPane.add(button);

fileMenu.add("New");

fileMenu.add("Open ...");

fileMenu.add("Save");

fileMenu.add("Save As ...");

fileMenu.addSeparator();

fileMenu.add(quitItem = new JMenuItem("Quit"));

menuBar.add(fileMenu);

window.getRootPane().setJMenuBar(menuBar);

window.getRootPane().setBorder(

BorderFactory.createRaisedBevelBorder());

button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

Point pt = contentPane.getLocation();

SwingUtilities.convertPointToScreen(

pt, contentPane);

window.setBounds(pt.x + 10, pt.y + 10, 200, 200);

quitItem.addActionListener(new ActionListener() {

14.1.1 JWindow屬性

14.1.2 JWindow類總結

14.1.3 AWT相容

14.2 JDialog

例14-3 運作中的JDialog

private ConstraintsPanel cp = new ConstraintsPanel();

private JPanel buttonsPanel = new JPanel();

private JButton showButton = new JButton("show dialog ..."),

okButton = new JButton("OK"),

applyButton = new JButton("Apply"),

cancelButton = new JButton("Cancel");

private JButton[] buttons = new JButton[] {

okButton, applyButton, cancelButton,

};

private JDialog dialog = new JDialog(null, // owner

"Constraints Dialog", // title

true); // modal

Container contentPane = getContentPane();

Container dialogContentPane = dialog.getContentPane();

contentPane.add(showButton);

dialogContentPane.add(cp, BorderLayout.CENTER);

dialogContentPane.add(buttonsPanel, BorderLayout.SOUTH);

dialog.pack();

// setLocationRelativeTo must be called after pack(),

// because dialog placement is based on dialog size.

// Because the applet is not yet showing, calling

// setLocationRelativeTo() here causes the dialog to be

// shown centered on the screen.

//

// If setLocationRelativeTo() is not invoked, the dialog

// will be located at (0,0) in screen coordinates.

//dialog.setLocationRelativeTo(this);

for(int i=0; i < buttons.length; ++i) {

buttonsPanel.add(buttons[i]);

addButtonListeners();

private void addButtonListeners() {

showButton.addActionListener(new ActionListener() {

// calling setLocationRelativeTo() here causes

// the dialog ito be centered over the applet.

dialog.setLocationRelativeTo(Test.this);

dialog.show();

okButton.addActionListener(new ActionListener() {

showStatus("OK button Activated");

dialog.dispose();

applyButton.addActionListener(new ActionListener() {

showStatus("Apply button Activated");

cancelButton.addActionListener(new ActionListener() {

showStatus("Cancel button Activated");

14.2.1 JDialog屬性

14.2.2 JDialog類總結

14.2.3 AWT相容

14.3 JOptionPane

例14-4 用JOptionPane建立對話框

private JButton topButton = new JButton(

"show dialog created from option pane");

private JButton bottomButton = new JButton(

"show dialog created with static method");

private String title = "dialog title";

private String message = "message";

contentPane.add(topButton);

contentPane.add(bottomButton);

topButton.addActionListener(new ActionListener() {

JOptionPane optionPane = new JOptionPane(

message, // message

JOptionPane.INFORMATION_MESSAGE); // messageType

JDialog dialog = optionPane.createDialog(

topButton, // parentComponent

title); // title

bottomButton.addActionListener(new ActionListener() {

JOptionPane.showMessageDialog(

bottomButton, // parentComponent

title, // title

14.3.1 内部窗體

例14-5 用JOptionPane建立内部窗體

private JButton button = new JButton("show internal frame");

JOptionPane.showInternalMessageDialog(

button, // parentComponent

"Break Time ...", // message

"Reminder!", // title

14.3.2 用JOptionPane靜态方法建立對話框

14.3.3 消息對話框

例14-6 顯示具有不同消息類型的消息對話框

private JButton button = new JButton("show dialog ...");

private String message = "information";

private int messageType = JOptionPane.INFORMATION_MESSAGE;

private String messages[] = {

"information", "error", "warning", "question", "plain"

JPanel controlPanel = new ControlPanel(this);

contentPane.add(controlPanel);

messageType);

public void setMessageType(int messageType) {

this.messageType = messageType;

switch(messageType) {

case JOptionPane.INFORMATION_MESSAGE:

message = messages[0];

break;

case JOptionPane.ERROR_MESSAGE:

message = messages[1];

case JOptionPane.WARNING_MESSAGE:

message = messages[2];

case JOptionPane.QUESTION_MESSAGE:

message = messages[3];

case JOptionPane.PLAIN_MESSAGE:

message = messages[4];

class ControlPanel extends JPanel {

private JComboBox messageTypes = new JComboBox();

private int[] typeValues = {

JOptionPane.INFORMATION_MESSAGE,

JOptionPane.ERROR_MESSAGE,

JOptionPane.WARNING_MESSAGE,

JOptionPane.QUESTION_MESSAGE,

JOptionPane.PLAIN_MESSAGE,

private String[] typeNames = {

"JOptionPane.INFORMATION_MESSAGE",

"JOptionPane.ERROR_MESSAGE",

"JOptionPane.WARNING_MESSAGE",

"JOptionPane.QUESTION_MESSAGE",

"JOptionPane.PLAIN_MESSAGE",

public ControlPanel(final Test applet) {

add(messageTypes);

for(int i=0; i < typeNames.length; ++i) {

messageTypes.addItem(typeNames[i]);

messageTypes.addItemListener(new ItemListener() {

public void itemStateChanged(ItemEvent e) {

String s = (String)messageTypes.getSelectedItem();

int type;

if(s.equals(typeNames[i]))

applet.setMessageType(typeValues[i]);

例14-7 替換消息對話框的預設圖示

private String title = "Reminder!";

private String message = "Dinner time";

JOptionPane.INFORMATION_MESSAGE,// messageType

new ImageIcon("dining.gif")); // icon

14.3.4 确認對話框

例14-8 使用确認對話框

private String title = "Unsaved Changes";

private String message[] = {

"Unsaved Changes in File: dialog.fm",

" ",

"Save before closing?",

int result = JOptionPane.showConfirmDialog(

JOptionPane.YES_NO_CANCEL_OPTION, // optionType

JOptionPane.WARNING_MESSAGE, // messageType

new ImageIcon("punch.gif")); // icon

switch(result) {

case JOptionPane.CLOSED_OPTION:

showStatus("Dialog Closed");

case JOptionPane.YES_OPTION:

showStatus("Yes");

case JOptionPane.NO_OPTION:

showStatus("No");

case JOptionPane.CANCEL_OPTION:

showStatus("Cancel");

14.3.5 輸入對話框

例14-9 有文本域的輸入對話框

private String message = "Please Enter Your Name";

String s = JOptionPane.showInputDialog(message);

if(s == null)

showStatus("cancel button activated");

else

showStatus("Name: " + s);

例14-10 有組合框的輸入對話框

private String title = "Animal Selection Dialog";

private String message = "Select your favorite animal:";

private String[] selectionValues = {

"dog", "cat", "mouse", "goat", "koala", "rabbit",

String s = (String)JOptionPane.showInputDialog(

Test.this, // parentComponent

JOptionPane.QUESTION_MESSAGE, // messageType

null, // icon

selectionValues, // selectionValues

selectionValues[3]); // initialValue

showStatus(s);

例14-11 帶清單的輸入對話框

private Object[] selectionValues = {

"mouse", "horse", "kangaroo", "iguana", "tiger", "lion",

"eagle", "vulture", "wolf", "coyote", "owl", "snake",

"shrew", "zebra", "wildebeast"

14.3.6 選項對話框

例14-12 使用一個選項對話框

private JButton applyButton = new JButton("Apply");

private RotatePanel rotatePanel = new RotatePanel();

private String title = "Rotate";

private Object[] buttonRowObjects = new Object[] {

"Ok",

applyButton,

"Cancel",

showStatus(rotatePanel.getSelectedAngle() +

" degrees");

int value = JOptionPane.showOptionDialog(

rotatePanel, // message

JOptionPane.DEFAULT_OPTION, // optionType

JOptionPane.PLAIN_MESSAGE, // messageType

buttonRowObjects, // options

applyButton); // initialValue

switch(value) {

showStatus(

"Dialog closed with close box");

case JOptionPane.OK_OPTION:

showStatus("Ok button activated: " +

rotatePanel.getSelectedAngle() +

showStatus("Cancel button activated");

class RotatePanel extends JPanel {

private ButtonGroup group = new ButtonGroup();

private JRadioButton[] buttons = {

new JRadioButton("0"),

new JRadioButton("90"),

new JRadioButton("180"),

new JRadioButton("270"),

public RotatePanel() {

setBorder(BorderFactory.createTitledBorder("Angle:"));

if(i ==0)

buttons[i].setSelected(true);

add(buttons[i]);

group.add(buttons[i]);

public String getSelectedAngle() {

String rv = null; // rv = return value

if(buttons[i].isSelected())

rv = buttons[i].getText();

return rv;

14.3.7 JOptionPane屬性

14.3.8 JOptionPane事件

例14-13 監聽從選項窗格激發的 PropertyChangeEvents

import java.beans.*;

private String title = "Update References";

private JPanel messagePanel = new JPanel();

private JCheckBox[] checkBoxes = {

new JCheckBox("All Cross-References"),

new JCheckBox("Text Insets Marked for Manual Update"),

new JCheckBox("Text Insets Marked for Automatic Update"),

new JCheckBox("OLE Links Marked for Manual Update"),

new JCheckBox("OLE Links Marked for Automatic Update"),

messagePanel.setBorder(

BorderFactory.createTitledBorder("Update:"));

messagePanel.setLayout(new BoxLayout(messagePanel,

BoxLayout.Y_AXIS));

for(int i=0; i < checkBoxes.length; ++i)

messagePanel.add(checkBoxes[i]);

final JOptionPane pane = new JOptionPane(

messagePanel, // message

JOptionPane.OK_CANCEL_OPTION); // optionType

JDialog dialog = pane.createDialog(

dialog.show(); // blocks

Integer value = (Integer)pane.getValue();

if(value.intValue() == JOptionPane.OK_OPTION)

updateReferences();

showStatus("dialog canceled");

pane.addPropertyChangeListener(

new PropertyChangeListener() {

public void propertyChange(PropertyChangeEvent e) {

String name = e.getPropertyName();

if(name.equals(JOptionPane.VALUE_PROPERTY))

System.out.println(name + ":" + e.getNewValue());

private void updateReferences() {

showStatus("updating references");

14.3.9 JOptionPane類總結

例14-14 構造各種配置的選項窗格

Object[] objects = new Object[] {

new JLabel("JOptionPane(Object message)",

new ImageIcon("beach_umbrella.gif"),

JLabel.LEFT),

new JCheckBox("check me out"),

new VerboseObject(),

Object[] objects2 = new Object[] {

"JOptionPane(Object message, int messageType)",

"messageType = JOptionPane.INFORMATION_MESSAGE",

Object[] objects3 = new Object[] {

"JOptionPane(Object message, " +

"int messageType, int optionsType)",

"messageType = JOptionPane.QUESTION_MESSAGE",

"optionType = JOptionPane.YES_NO_CANCEL_OPTION",

Object[] objects4 = new Object[] {

"int messageType, int optionsType, Icon icon)",

"messageType = JOptionPane.WARNING_MESSAGE",

"optionType = JOptionPane.OK_CANCEL_OPTION",

"icon = new ImageIcon(/"ballot_box.gif/")",

Object[] objects5 = new Object[] {

"messageType = JOptionPane.ERROR_MESSAGE",

"icon = null",

"options = /"button 1/", /"button 2/", " +

"new JButton(/"button 3/")",

JOptionPane defaultPane = new JOptionPane();

JOptionPane messagePane = new JOptionPane(

"JOptionPane(Object message)");

JOptionPane objectPane = new JOptionPane(objects);

JOptionPane messageTypePane = new JOptionPane(

objects2, JOptionPane.INFORMATION_MESSAGE);

JOptionPane messageAndOptionTypePane = new JOptionPane(

objects3, JOptionPane.QUESTION_MESSAGE,

JOptionPane.YES_NO_CANCEL_OPTION);

JOptionPane messageOptionAndIconPane = new JOptionPane(

objects4, JOptionPane.WARNING_MESSAGE,

JOptionPane.OK_CANCEL_OPTION,

new ImageIcon("ballot_box.gif"));

Object[] options = {

"button 1", "button 2", new JButton("button 3"),

JOptionPane messageOptionIconAndOptionsPane =

new JOptionPane(

objects5, JOptionPane.ERROR_MESSAGE,

null,

options,

options[2]);

contentPane.setLayout(new BoxLayout(contentPane,

contentPane.add(defaultPane);

contentPane.add(new JSeparator());

contentPane.add(messagePane);

contentPane.add(objectPane);

contentPane.add(messageTypePane);

contentPane.add(messageAndOptionTypePane);

contentPane.add(messageOptionAndIconPane);

contentPane.add(messageOptionIconAndOptionsPane);

class VerboseObject extends Object {

public String toString() {

return "This is what you'll see in the option pane";

14.3.10 AWT相容

14.4 本章回顧

  略

繼續閱讀