chapter 10 gui1 例 : lunarphases, 月亮盈亏 (jb demo) 如何使用 compound bounder 如何使用...
DESCRIPTION
Chapter 10 GUI3 // Create the main panel to contain the two subpanels. mainPanel = new JPanel(); mainPanel.setLayout(new GridLayout(2,1,5,5)); // (rows, cols, hgap, vgap) mainPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5)); // Add the select and display panels to the main panel. mainPanel.add(selectPanel); mainPanel.add(displayPanel); Compound BoarderTRANSCRIPT
Chapter 10 GUI 1
例 : LunarPhases, 月亮盈亏 (JB demo)• 如何使用 Compound Bounder• 如何使用 Combo Boxes• 如何使用 Loading Multiple Images
Chapter 10 GUI 2
• 使用多屏 (Panel) 来分组图形组件// Create the phase selection and display panels. selectPanel = new JPanel(); displayPanel = new JPanel(); // Add various widgets to the subpanels. addWidgets();
Chapter 10 GUI 3
// Create the main panel to contain the two subpanels. mainPanel = new JPanel();mainPanel.setLayout(new GridLayout(2,1,5,5)); // (rows, cols, hgap, vgap)mainPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
// Add the select and display panels to the main panel.mainPanel.add(selectPanel); mainPanel.add(displayPanel); • Compound Boarder
Chapter 10 GUI 4
// Add border around the select panelselectPanel.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Select Phase"), BorderFactory.createEmptyBorder(5,5,5,5)));
• Combo Boxes
Chapter 10 GUI 5
JComboBox phaseChoices = null; ... // Create combo box with lunar phase choices String[ ] phases =
{ "New", "Waxing Crescent", "First Quarter", "Waxing Gibbous", "Full", "Waning Gibbous", "Third Quarter", "Waning Crescent" };
phaseChoices = new JComboBox(phases);phaseChoices.setSelectedIndex(START_INDEX);• Handling Events on a Combo BoxphaseChoices.addActionListener(this); ...
Chapter 10 GUI 6
public void actionPerformed(ActionEvent event) { if ("comboBoxChanged".equals(event.getActionCommand())) { // update the icon to display the new phase
phaseIconLabel.setIcon( images[phaseChoices.getSelectedIndex()]);
} }
• Multiple Imagesfinal static int NUM_IMAGES = 8; final static int START_INDEX = 3; ImageIcon[ ] images = new ImageIcon[NUM_IMAGES]; ...
Chapter 10 GUI 7
// Create the widgets to select and display the phases of the moon. private void addWidgets() {
// Get the images and put them into an array of ImageIcon. for (int i = 0; i < NUM_IMAGES; i++) { String imageName = "images/image" + i + ".jpg"; URL iconURL = ClassLoader.getSystemResource(imageName);
ImageIcon icon = new ImageIcon(iconURL); images[i] = icon; }
}注 : getSystemResource 会搜索 classpath 中的路径去获取指定图象例 : VoteDialog• 怎样使用 Radio Buttons• 怎样使用 Dialogs
Chapter 10 GUI 8
• 怎样使用 Radio Buttons• 怎样使用 Dialogs
Chapter 10 GUI 9
• Radio Buttons
final int numButtons = 4;
JRadioButton[] radioButtons = new JRadioButton[numButtons];
final ButtonGroup group = new ButtonGroup();
...
final String defaultMessageCommand = "default";
final String yesNoCommand = "yesno";
final String yeahNahCommand = "yeahnah";
Chapter 10 GUI 10
final String yncCommand = "ync“;
radioButtons[0] = new JRadioButton("<html>Candidate 1: <font color=red>Sparky the Dog</font></html>");
radioButtons[0].setActionCommand(defaultMessageCommand);
radioButtons[1] = new JRadioButton("<html>Candidate 2: <font color=green>Shady Sadie</font></html>");
radioButtons[1].setActionCommand(yesNoCommand);
Chapter 10 GUI 11
radioButtons[2] = new JRadioButton("<html>Candidate 3: <font color=blue>R.I.P. McDaniels</font></html>");
radioButtons[2].setActionCommand(yeahNahCommand);
radioButtons[3] = new JRadioButton("<html>Candidate 4:
<font color=maroon>Duke the Java<font size=-2><sup>TM</sup>
</font size> Platform Mascot</font></html>");
radioButtons[3].setActionCommand(yncCommand);
for (int i = 0; i < numButtons; i++) {
group.add(radioButtons[i]);
}
// Select the first button by default.
radioButtons[0].setSelected(true);
Chapter 10 GUI 12
• Dialogs1. showMessageDialog
– Component parentComponent– Object message
Chapter 10 GUI 13
2. showOptionDialog– Component parentComponent– Object message – String title: title of the dialog– int optionType– int messageType– Icon icon: custom icon– Object[] options– Object initialValue
Chapter 10 GUI 14
• Getting User Input from a Dialog// yes/no dialog } else if (command == yesNoCommand) {
int n = JOptionPane.showConfirmDialog( frame, "This candidate is a convicted felon.\n Do you still want to vote for her?",
"A Follow-up Question", JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) { setLabel("OK. Keep an eye on your wallet."); } else if (n == JOptionPane.NO_OPTION) { setLabel("Whew! Good choice."); } else { setLabel("It is your civic duty to cast your vote."); }
Chapter 10 GUI 15
图形组件的布局管理– 五种不同布局管理选项的效果
Chapter 10 GUI 16
1. BorderLayout– A BorderLayout has five areas available to hold components:
north, south, east, west, and center. All extra space is placed in the center area
例 :Panel p = new Panel(); p.setLayout(new BorderLayout()); p.add(new Button("Okay"), BorderLayout.SOUTH);
2. BoxLayout – The BoxLayout class puts components in a single row or
column. This class respects the components' requested maximum sizes and also lets you align components.
例 :// Lay out the label and scroll pane from top to bottom. JPanel listPane = new JPanel(); listPane.setLayout(new BoxLayout(listPane, BoxLayout.Y_AXIS));
Chapter 10 GUI 17
3. FlowLayout – FlowLayout is the default layout manager for every JPanel. This
layout manager simply lays out components from left to right, starting new rows, if necessary
4. GridLayout – GridLayout simply makes a bunch of components equal in size
and displays them in the requested number of rows and columns例 :public class ButtonGrid extends Applet {
public void init() { setLayout(new GridLayout(3,2)); add(new Button("1")); add(new Button("2")); add(new Button("3")); add(new Button("4")); add(new Button("5")); add(new Button("6")); }
}
Chapter 10 GUI 18
5. GridBagLayout – GridBagLayout is the most sophisticated, flexible layout
manager the Java platform provides. This layout manager aligns components by placing them within a grid of cells, allowing some components to span more than one cell. The rows in the grid aren't necessarily all the same height; similarly, grid columns can have different widths
关于使用菜单的有关问题• 菜单以节省空间的方式给用户提供多种选择 ( MenuLookDemo.java )
Chapter 10 GUI 19
• 菜单图形组件类的层次结构
Chapter 10 GUI 20
• 创建一个菜单// in the constructor for a JFrame subclass: JMenuBar menuBar; JMenu menu, submenu; JMenuItem menuItem; JCheckBoxMenuItem cbMenuItem; JRadioButtonMenuItem rbMenuItem; ... //Create the menu bar. menuBar = new JMenuBar();setJMenuBar(menuBar); //Build the first menu. menu = new JMenu("A Menu"); menu.setMnemonic(KeyEvent.VK_A);menuBar.add(menu);
Chapter 10 GUI 21
// a group of JMenuItems menuItem =
new JMenuItem("A text-only menu item", KeyEvent.VK_T);menuItem.setAccelerator(
KeyStroke.getKeyStroke( KeyEvent.VK_1,ActionEvent.ALT_MASK));menu.add(menuItem);
menuItem = new JMenuItem("Both text and icon", new ImageIcon("images/middle.gif"));
menuItem.setMnemonic(KeyEvent.VK_B); menu.add(menuItem);
menuItem = new JMenuItem(new ImageIcon("images/middle.gif")); menuItem.setMnemonic(KeyEvent.VK_D); menu.add(menuItem);
Chapter 10 GUI 22
//a group of radio button menu items menu.addSeparator(); ButtonGroup group = new ButtonGroup(); rbMenuItem = new JRadioButtonMenuItem(
"A radio button menu item"); rbMenuItem.setSelected(true); rbMenuItem.setMnemonic(KeyEvent.VK_R); group.add(rbMenuItem); menu.add(rbMenuItem); rbMenuItem = new JRadioButtonMenuItem("Another one"); rbMenuItem.setMnemonic(KeyEvent.VK_O); group.add(rbMenuItem); menu.add(rbMenuItem);
Chapter 10 GUI 23
//a group of check box menu items menu.addSeparator(); cbMenuItem = new JCheckBoxMenuItem("A check box menu item"); cbMenuItem.setMnemonic(KeyEvent.VK_C); menu.add(cbMenuItem); cbMenuItem = new JCheckBoxMenuItem("Another one"); cbMenuItem.setMnemonic(KeyEvent.VK_H); menu.add(cbMenuItem);
//a submenu menu.addSeparator(); submenu = new JMenu("A submenu"); submenu.setMnemonic(KeyEvent.VK_S); menuItem = new JMenuItem("An item in the submenu"); menuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_2,
ActionEvent.ALT_MASK)); submenu.add(menuItem);
Chapter 10 GUI 24
menuItem = new JMenuItem("Another item"); submenu.add(menuItem); menu.add(submenu);
//Build second menu in the menu bar. menu = new JMenu("Another Menu"); menu.setMnemonic(KeyEvent.VK_N); menuBar.add(menu);
• 处理来自菜单的事件 (MenuDemo.java)– 向 JMenuItem 对象注册以获取它的 Action 事件– 向 JRadioButtonMenuItem 对象注册以获取它的 Action 或
Item 事件– 向 CheckBoxMenuItem 对象注册以获取它的 Item 事件
Chapter 10 GUI 25
// JB demopublic class MenuDemo extends JFrame implements
ActionListener, ItemListener { public MenuDemo() {
//...for each JMenuItem instance: menuItem.addActionListener(this); ... //for each JRadioButtonMenuItem:rbMenuItem.addActionListener(this);... //for each JCheckBoxMenuItem:cbMenuItem.addItemListener(this);...
}
Chapter 10 GUI 26
public void actionPerformed(ActionEvent e) { JMenuItem source = (JMenuItem)(e.getSource()); String s = "Action event detected." + newline + " Event source: " + source.getText() + " (an instance of " + getClassName(source) + ")"; output.append(s + newline);
}
public void itemStateChanged(ItemEvent e) { //...Get information from the item event... //...Display it in the text area...
}
Chapter 10 GUI 27
文本图形部件的使用
1. Text Controls– 单行文本输入和编辑
2. Plain Text Controls– 任意行文本输入和编辑 , 单字体
3. Styled Text Controls– 任意行文本输入和编辑 , 多字体 , 图形 , 声音
Chapter 10 GUI 28
Chapter 10 GUI 29
1. An Example of Using a Text FieldJTextField textField = new JTextField(10); textField.setActionCommand(textFieldString); textField.addActionListener(this);…
public void actionPerformed(ActionEvent e) {String prefix = "You typed \""; if (e.getActionCommand().equals(textFieldString)) {
JTextField source = (JTextField)e.getSource(); actionLabel.setText(prefix + source.getText() + "\"");
} else { JPasswordField source = (JPasswordField)e.getSource(); actionLabel.setText(prefix +
new String(source.getPassword()) + "\"");}
}
Chapter 10 GUI 30
2. An Example of Using a Password FieldJPasswordField passwordField = new JPasswordField(10);passwordField.setActionCommand(passwordFieldString);passwordField.addActionListener(this); …
3. An Example of Using a Text AreaJTextArea textArea = new JTextArea(
"This is an editable JTextArea " + "that has been initialized with the setText method. " + "A text area is a \"plain\" text component, " +"which means that although it can display text " + "in any font, all of the text is in the same font." );
textArea.setFont(new Font("Serif", Font.ITALIC, 16));textArea.setLineWrap(true); textArea.setWrapStyleWord(true);
Chapter 10 GUI 31
• 给 JTextArea 增加上下滚动功能 (JScrollPane)
JScrollPane areaScrollPane = new JScrollPane(textArea);
areaScrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
areaScrollPane.setPreferredSize(new Dimension(250, 250));
areaScrollPane.setBorder(...create border...);
• 完整的程序清单 : TextSamplerDemo.java (JB demo)