📄 jan04_johnz.txt
字号:
that component is used in the dialog. This allows you to place
icons in the buttons, for instance. More typically, you would
provide an array of strings, and their labels would be used as the
button labels. The initialValue is then used to select which of
the options gets the default selection.
The showOptionDialog method returns an int. This indicates the
position selected from the options array. CLOSED_OPTION is still
returned if the user closed the dialog.
String options[] = {"Yes", "Not Now", "Go Away"};
int value = JOptionPane.showOptionDialog(
component,
"Lunch?",
"Lunch Time",
JOptionPane.YES_NO_OPTION, // Need something
JOptionPane.QUESTION_MESSAGE,
null, // Use default icon for message type
options,
options[1]);
if (value == JOptionPane.CLOSED_OPTION) {
System.out.println("Closed window");
} else {
System.out.println("Selected: " + options[value]);
}
If you don't want buttons, pass in an empty array for the options.
Adding Word Wrap
The JOptionPane component has a read-only property
(MaxCharactersPerLineCount) for the maximum number of characters
per line. By default, this is Integer.MAX_VALUE. By subclassing
JOptionPane, you can override this setting. Changing this setting
allows the component to word-wrap when a message is really long.
public static JOptionPane getNarrowOptionPane(
int maxCharactersPerLineCount) {
// Our inner class definition
class NarrowOptionPane extends JOptionPane {
int maxCharactersPerLineCount;
NarrowOptionPane(int maxCharactersPerLineCount) {
this.maxCharactersPerLineCount =
maxCharactersPerLineCount;
}
public int getMaxCharactersPerLineCount() {
return maxCharactersPerLineCount;
}
}
return new NarrowOptionPane(
maxCharactersPerLineCount);
}
By subclassing, you can no longer use the static helper methods
such as showMessageDialog. Here's how you manually create and
show the component:
String msg = "This is a really long message. ...";
JOptionPane pane = getNarrowOptionPane(50);
pane.setMessage(msg);
pane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
JDialog dialog = pane.createDialog(
component, "Width 50");
dialog.show();
Of course, you can add a "\n" to the message, but then you have
to count the characters per line.
Message as Object
At this point you might ask why the message argument to all the
showXXXDialog methods is an Object. The answer is that it's
because the message argument to all these methods doesn't have to
be a String. You can pass in any Object. Each object is "added"
to the message area, one on top of the other. For instance, if
you pass in an array of two strings, it creates a message on two
lines:
String msg[] = {"Welcome", "Home"};
JOptionPane.showMessageDialog(component, msg);
The objects you add can be components, icons, or objects.
Components are added as such. Icons are shown in a label, as are
strings. For other objects, their string representation
(toString()) is shown. For instance, the following component can
be added to an option pane. As the user changes the selection in
the slider, the option pane's value is updated:
public static JSlider getSlider(
final JOptionPane optionPane) {
JSlider slider = new JSlider();
slider.setMajorTickSpacing (10);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
ChangeListener changeListener =
new ChangeListener() {
public void stateChanged(
ChangeEvent changeEvent) {
JSlider theSlider =
(JSlider)changeEvent.getSource();
if (!theSlider.getValueIsAdjusting()) {
optionPane.setInputValue(
new Integer(theSlider.getValue()));
}
}
};
slider.addChangeListener(changeListener);
return slider;
}
Because you have to pass the option pane to the method, here
again, you can't use one of the shortcuts to create the dialog:
JOptionPane optionPane = new JOptionPane();
JSlider slider = getSlider(optionPane);
Object msg[] = {"Select a value:", slider};
optionPane.setMessage(msg);
optionPane.setMessageType(
JOptionPane.QUESTION_MESSAGE);
optionPane.setOptionType(
JOptionPane.OK_CANCEL_OPTION);
JDialog dialog = optionPane.createDialog(
Options.this, "Select Value");
dialog.show();
Object value = optionPane.getValue();
if (value == null || !(value instanceof Integer)) {
System.out.println("Closed");
} else {
int i = ((Integer)value).intValue();
if (i == JOptionPane.CLOSED_OPTION) {
System.out.println("Closed");
} else if (i == JOptionPane.OK_OPTION) {
System.out.println("OKAY - value is: " +
optionPane.getInputValue());
} else if (i == JOptionPane.CANCEL_OPTION) {
System.out.println("Cancelled");
}
}
Notice that as you start getting fancier with JOptionPane, you
lose the ability to use the shortcut methods. And, you have to
do special handling of the return value. You first need to use
getValue for the JOptionPane to determine which button the user
selected. Then, for when the user presses the OK button, you need
to use the getInputValue method to get the value from the
underlying slider.
Sounds
Swing provides for auditory cues related to the four types of
icons:
o OptionPane.errorSound
o OptionPane.informationSound
o OptionPane.questionSound
o OptionPane.warningSound
By setting these properties, you can get sounds when your option
panes are displayed. You can set the individual sounds with lines
like the following:
UIManager.put("OptionPane.questionSound",
"sounds/OptionPaneError.wav");
Or set all of them with the system defaults as follows:
UIManager.put("AuditoryCues.playList",
UIManager.get("AuditoryCues.defaultCueList"));
Audio cues are disabled by default because they might have
problems on some platforms. It is recommended that you use them
with care until the issues have been resolved.
Complete Example
Here is the source code for a complete example that uses the
features explored in this tip.
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Locale;
public class Options extends JFrame {
private static class FrameShower
implements Runnable {
final Frame frame;
public FrameShower(Frame frame) {
this.frame = frame;
}
public void run() {
frame.show();
}
}
public static JOptionPane getNarrowOptionPane(
int maxCharactersPerLineCount) {
// Our inner class definition
class NarrowOptionPane extends JOptionPane {
int maxCharactersPerLineCount;
NarrowOptionPane(
int maxCharactersPerLineCount) {
this.maxCharactersPerLineCount =
maxCharactersPerLineCount;
}
public int getMaxCharactersPerLineCount() {
return maxCharactersPerLineCount;
}
}
return new NarrowOptionPane(
maxCharactersPerLineCount);
}
public static JSlider getSlider(
final JOptionPane optionPane) {
JSlider slider = new JSlider();
slider.setMajorTickSpacing (10);
slider.setPaintTicks(true);
slider.setPaintLabels(true);
ChangeListener changeListener =
new ChangeListener() {
public void stateChanged(
ChangeEvent changeEvent) {
JSlider theSlider = (
JSlider)changeEvent.getSource();
if (!theSlider.getValueIsAdjusting()) {
optionPane.setInputValue(new Integer(
theSlider.getValue()));
}
}
};
slider.addChangeListener(changeListener);
return slider;
}
public Options() {
super("JOptionPane Usage");
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
JButton message = new JButton("Message");
ActionListener messageListener =
new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(
Options.this, "Hello, World");
}
};
message.addActionListener(messageListener);
contentPane.add(message);
JButton confirm = new JButton("Confirm");
ActionListener confirmListener =
new ActionListener() {
public void actionPerformed(ActionEvent e) {
int returnValue =
JOptionPane.showConfirmDialog(
Options.this, "Lunch?");
String message = null;
if (returnValue == JOptionPane.YES_OPTION) {
message = "Yes";
} else if (
returnValue == JOptionPane.NO_OPTION) {
message = "No";
} else if (
returnValue == JOptionPane.CANCEL_OPTION) {
message = "Cancel";
} else if (
returnValue == JOptionPane.CLOSED_OPTION) {
message = "Closed";
}
System.out.println("User selected: " + message);
}
};
confirm.addActionListener(confirmListener);
contentPane.add(confirm);
JButton inputText = new JButton("Input Text");
ActionListener inputTextListener =
new ActionListener() {
public void actionPerformed(ActionEvent e) {
String value =
JOptionPane.showInputDialog("Name");
System.out.println("Name: " + value);
}
};
inputText.addActionListener(inputTextListener);
contentPane.add(inputText);
JButton inputCombo = new JButton("Input Combo");
ActionListener inputComboListener =
new ActionListener() {
public void actionPerformed(ActionEvent e) {
String smallList[] = {
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
};
String value =
(String)JOptionPane.showInputDialog(
Options.this, "Which Day?", "Day",
JOptionPane.QUESTION_MESSAGE, null,
smallList, smallList[smallList.length-1]);
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -