1 / 62

第 15 讲 .  图像界面组件

第 15 讲 .  图像界面组件. 常用用户界面组件. JButton 按钮 jbt JCheckBox 复选框 jchk JRadioButton 单选框 jrb JLabel 标签 jlbl JTextField 文本域 jtf JTextArea 文本区域 jta JComboBox 组合框 jcbo JList 列表 jlst. GUI Class Hierarchy (Swing) GUI 类的继承关系. 常用用户界面组件. Java 事件对象的层次结构. 用户行为、源对象和事件 对应关系.

Download Presentation

第 15 讲 .  图像界面组件

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 第15讲.  图像界面组件

  2. 常用用户界面组件 • JButton 按钮jbt • JCheckBox 复选框jchk • JRadioButton 单选框jrb • JLabel 标签 jlbl • JTextField 文本域 jtf • JTextArea 文本区域 jta • JComboBox 组合框 jcbo • JList 列表 jlst

  3. GUI Class Hierarchy (Swing) GUI类的继承关系

  4. 常用用户界面组件

  5. Java事件对象的层次结构

  6. 用户行为、源对象和事件 对应关系 Source Event TypeUser Action Object Generated Click a button点击按钮 JButtonActionEvent Click a check box点击复选框 JCheckBoxItemEvent, ActionEvent Click a radio button单击单选框 JRadioButtonItemEvent, ActionEvent Press return on a text field文本回车 JTextFieldActionEvent Select a new item选一个新项 JComboBoxItemEvent, ActionEvent Select a list new item 选多项 JList JSelectionListEvent Window opened, closed, etc. WindowWindowEvent Mouse pressed, released, etc. ComponentMouseEvent Key released, pressed, etc. ComponentKeyEvent

  7. AbstractButton

  8. 1 JButton

  9. JButton Constructors 构造方法 The following are JButton constructors: JButton() JButton(String text) JButton(String text, Icon icon) JButton(Icon icon)

  10. JButton Properties 常用属性 • text • icon • mnemonic • horizontalAlignment • verticalAlignment • horizontalTextPosition • verticalTextPosition

  11. Default Icons, Pressed Icon, and Rollover Icon 默认图标、按下图标和翻转图标 A regular button has a default icon, pressed icon, and rollover icon. Normally, you use the default icon. All other icons are for special effects. A pressed icon is displayed when a button is pressed and a rollover icon is displayed when the mouse is over the button but not pressed. (A) Default icon (B) Pressed icon (C) Rollover icon

  12. Demo TestButtonIcons.java import javax.swing.*; public class TestButtonIcons extends JFrame { public static void main(String[] args) { // Create a frame and set its properties JFrame frame = new TestButtonIcons(); frame.setTitle("ButtonIcons"); frame.setSize(165, 80); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public TestButtonIcons() { ImageIcon usIcon = new ImageIcon("image/usIcon.gif"); ImageIcon caIcon = new ImageIcon("image/caIcon.gif"); ImageIcon ukIcon = new ImageIcon("image/ukIcon.gif"); JButton jbt = new JButton("Click it", usIcon); jbt.setPressedIcon(caIcon); jbt.setRolloverIcon(ukIcon); add(jbt); } }

  13. Horizontal Alignments 水平对齐 Horizontal alignment specifies how the icon and text are placed horizontally on a button. You can set the horizontal alignment using one of the five constants: LEADING, LEFT, CENTER, RIGHT, TRAILING. At present, LEADING and LEFT are the same and TRAILING and RIGHT are the same. Future implementation may distinguish them. The default horizontal alignment is SwingConstants.TRAILING.

  14. Vertical Alignments 垂直对齐 Vertical alignment specifies how the icon and text are placed vertically on a button. You can set the vertical alignment using one of the three constants: TOP, CENTER, BOTTOM. The default vertical alignment is SwingConstants.CENTER.

  15. Horizontal Text Positions 文本水平 Horizontal text position specifies the horizontal position of the text relative to the icon. You can set the horizontal text position using one of the five constants: LEADING, LEFT, CENTER, RIGHT, TRAILING. The default horizontal text position is SwingConstants.RIGHT.

  16. Vertical Text Positions 文本垂直 Vertical text position specifies the vertical position of the text relative to the icon. You can set the vertical text position using one of the three constants: TOP, CENTER. The default vertical text position is SwingConstants.CENTER.

  17. JButton触发事件 当按钮回车时,触发一个ActionEvent。

  18. Example: Using Buttons Write a program that displays a message on a panel and uses two buttons, <= and =>, to move the message on the panel to the left or right. 触发ActionEvent

  19. Demo ButtonDemo .java • import java.awt.*; • import java.awt.event.ActionListener; • import java.awt.event.ActionEvent; • import javax.swing.*; • public class ButtonDemo extends JFrame { • // Create a panel for displaying message • protected MessagePanel messagePanel • = new MessagePanel("Welcome to Java"); • // Declare two buttons to move the message left and right • private JButton jbtLeft = new JButton("<="); • private JButton jbtRight = new JButton("=>"); • public static void main(String[] args) { • ButtonDemo frame = new ButtonDemo(); • frame.setTitle("ButtonDemo"); • frame.setLocationRelativeTo(null); // Center the frame • frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); • frame.setSize(500, 200); • frame.setVisible(true); • } • public ButtonDemo() { • // Set the background color of messagePanel • messagePanel.setBackground(Color.white); • // Create Panel jpButtons to hold two Buttons "<=" and "right =>" • JPanel jpButtons = new JPanel(); • jpButtons.setLayout(new FlowLayout()); • jpButtons.add(jbtLeft); • jpButtons.add(jbtRight); • // Set keyboard mnemonics • jbtLeft.setMnemonic('L'); • jbtRight.setMnemonic('R'); • // Set icons and remove text • // jbtLeft.setIcon(new ImageIcon("image/left.gif")); • // jbtRight.setIcon(new ImageIcon("image/right.gif")); • // jbtLeft.setText(null); • // jbtRight.setText(null); • // Set tool tip text on the buttons • jbtLeft.setToolTipText("Move message to left"); • jbtRight.setToolTipText("Move message to right"); • // Place panels in the frame • setLayout(new BorderLayout()); • add(messagePanel, BorderLayout.CENTER); • add(jpButtons, BorderLayout.SOUTH); • // Register listeners with the buttons • jbtLeft.addActionListener(new ActionListener() { • public void actionPerformed(ActionEvent e) { • messagePanel.moveLeft(); • } • }); • jbtRight.addActionListener(new ActionListener() { • public void actionPerformed(ActionEvent e) { • messagePanel.moveRight(); • } • }); • } • }

  20. 2 JCheckBox 复选框 JCheckBox inherits all the properties such as text, icon, mnemonic, verticalAlignment, horizontalAlignment, horizontalTextPosition, verticalTextPosition, and selected from AbstractButton, and provides several constructors to create check boxes.

  21. JCheckBox触发事件 当复选框被点击(选中或未选中)时,先触发一个ItemEvent,然后触发一个ActionEvent。要确定是否选中,用isSelected()方法,返回true表示被选中。 对于监听器的设置,可以选用ItemEvent或者ActionEvent两者之一。

  22. Example: Using Check Boxes Add three check boxes named Centered, Bold, and Italic into Example 15.1 to let the user specify whether the message is centered, bold, or italic. ButtonDemo CheckBoxDemo

  23. Demo CheckBoxDemo .java • import java.awt.*; • import java.awt.event.*; • import javax.swing.*; • public class CheckBoxDemo extends ButtonDemo { • // Create three check boxes to control the display of message • private JCheckBox jchkCentered = new JCheckBox("Centered"); • private JCheckBox jchkBold = new JCheckBox("Bold"); • private JCheckBox jchkItalic = new JCheckBox("Italic"); • public static void main(String[] args) { • CheckBoxDemo frame = new CheckBoxDemo(); • frame.setTitle("CheckBoxDemo"); • frame.setLocationRelativeTo(null); // Center the frame • frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); • frame.setSize(500, 200); • frame.setVisible(true); • } • public CheckBoxDemo() { • // Set mnemonic keys • jchkCentered.setMnemonic('C'); • jchkBold.setMnemonic('B'); • jchkItalic.setMnemonic('I'); • // Create a new panel to hold check boxes • JPanel jpCheckBoxes = new JPanel(); • jpCheckBoxes.setLayout(new GridLayout(3, 1)); • jpCheckBoxes.add(jchkCentered); • jpCheckBoxes.add(jchkBold); • jpCheckBoxes.add(jchkItalic); • add(jpCheckBoxes, BorderLayout.EAST); • // Register listeners with the check boxes • jchkCentered.addActionListener(new ActionListener() { • public void actionPerformed(ActionEvent e) { • messagePanel.setCentered(jchkCentered.isSelected()); • } • }); • jchkBold.addActionListener(new ActionListener() { • public void actionPerformed(ActionEvent e) { • setNewFont(); • } • }); • jchkItalic.addActionListener(new ActionListener() { • public void actionPerformed(ActionEvent e) { • setNewFont(); • } • }); • } • private void setNewFont() { • // Determine a font style • int fontStyle = Font.PLAIN; • fontStyle += (jchkBold.isSelected() ? Font.BOLD : Font.PLAIN); • fontStyle += (jchkItalic.isSelected() ? Font.ITALIC : Font.PLAIN); • // Set font for the message • Font font = messagePanel.getFont(); • messagePanel.setFont( • new Font(font.getName(), fontStyle, font.getSize())); • } • }

  24. 3 JRadioButton 单选按钮 Radio buttons are variations of check boxes. They are often used in the group, where only one button is checked at a time.

  25. Grouping Radio Buttons 单选按钮组群 ButtonGroup btg = new ButtonGroup(); btg.add(jrb1); btg.add(jrb2);

  26. JRadioButton触发事件 当单选框被点击(选中或未选中)时,先触发一个ItemEvent,然后触发一个ActionEvent。要确定是否选中,用isSelected()方法,返回true表示被选中。 对于监听器的设置,可以选用ItemEvent或者ActionEvent两者之一。

  27. Example: Using Radio Buttons Add three radio buttons named Red, Green, and Blue into the preceding example to let the user choose the color of the message. ButtonDemo CheckBoxDemo RadioButtonDemo

  28. Demo RadioButtonDemo .java • import java.awt.*; • import java.awt.event.*; • import javax.swing.*; • public class RadioButtonDemo extends CheckBoxDemo { • // Declare radio buttons • private JRadioButton jrbRed, jrbGreen, jrbBlue; • public static void main(String[] args) { • RadioButtonDemo frame = new RadioButtonDemo(); • frame.setLocationRelativeTo(null); • // Center the frame • frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); • frame.setTitle("RadioButtonDemo"); • frame.setSize(500, 200); • frame.setVisible(true); • } • public RadioButtonDemo() { • // Create a new panel to hold check boxes • JPanel jpRadioButtons = new JPanel(); • jpRadioButtons.setLayout(new GridLayout(3, 1)); • jpRadioButtons.add(jrbRed = new JRadioButton("Red")); • jpRadioButtons.add(jrbGreen = new JRadioButton("Green")); • jpRadioButtons.add(jrbBlue = new JRadioButton("Blue")); • add(jpRadioButtons, BorderLayout.WEST); • // Create a radio button group to group three buttons • ButtonGroup group = new ButtonGroup(); • group.add(jrbRed); • group.add(jrbGreen); • group.add(jrbBlue); • // Set keyboard mnemonics • jrbRed.setMnemonic('E'); • jrbGreen.setMnemonic('G'); • jrbBlue.setMnemonic('U'); • // Register listeners for check boxes • jrbRed.addActionListener(new ActionListener() { • public void actionPerformed(ActionEvent e) { • messagePanel.setForeground(Color.red); • } • }); • jrbGreen.addActionListener(new ActionListener() { • public void actionPerformed(ActionEvent e) { • messagePanel.setForeground(Color.green); • } • }); • jrbBlue.addActionListener(new ActionListener() { • public void actionPerformed(ActionEvent e) { • messagePanel.setForeground(Color.blue); • } • }); • // Set initial message color to blue • jrbBlue.setSelected(true); • messagePanel.setForeground(Color.blue); • } • }

  29. 4 JLabel 标签 A label is a display area for a short text, an image, or both.

  30. JLabel Constructors 构造方法 The constructors for labels are as follows: JLabel() JLabel(String text, int horizontalAlignment) JLabel(String text) JLabel(Icon icon) JLabel(Icon icon, int horizontalAlignment) JLabel(String text, Icon icon, int horizontalAlignment)

  31. JLabel Properties 属性 JLabel inherits all the properties from JComponent and has many properties similar to the ones in JButton, such as text, icon, horizontalAlignment, verticalAlignment, horizontalTextPosition, verticalTextPosition.

  32. Using Labels // Create an image icon from image file ImageIcon icon = new ImageIcon("image/grapes.gif"); // Create a label with text, an icon, // with centered horizontal alignment JLabel jlbl = new JLabel("Grapes", icon, SwingConstants.CENTER); // Set label's text alignment and gap between text and icon jlbl.setHorizontalTextPosition(SwingConstants.CENTER); jlbl.setVerticalTextPosition(SwingConstants.BOTTOM); jlbl.setIconTextGap(5);

  33. 5 JTextField 文本域 A text field is an input area where the user can type in characters. Text fields are useful in that they enable the user to enter in variable data (such as a name or a description).

  34. JTextField Constructors 构造方法 • JTextField(int columns) Creates an empty text field with the specified number of columns. • JTextField(String text) Creates a text field initialized with the specified text. • JTextField(String text, int columns) Creates a text field initialized with thespecified text and the column size.

  35. JTextField Properties 常用属性 • text • horizontalAlignment • editable • columns

  36. JTextField Methods 常用方法 • getText() Returns the string from the text field. • setText(String text) Puts the given string in the text field. • setEditable(boolean editable) Enables or disables the text field to be edited. By default, editable is true. • setColumns(int) Sets the number of columns in this text field.The length of the text field is changeable.

  37. JTextField 触发事件 当光标移动到文本域,并且按回车键时,触发一个ActionEvent事件。

  38. Example: Using Text Fields Add a text field to the preceding example to let the user set a new message.

  39. Demo TextFieldDemo .java • import java.awt.*; • import java.awt.event.*; • import javax.swing.*; • public class TextFieldDemo extends RadioButtonDemo { • private JTextField jtfMessage = new JTextField(10); • /** Main method */ • public static void main(String[] args) { • TextFieldDemo frame = new TextFieldDemo(); • frame.pack(); • frame.setTitle("TextFieldDemo"); • frame.setLocationRelativeTo(null); • // Center the frame • frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); • frame.setVisible(true); • } • public TextFieldDemo() { • // Create a new panel to hold label and text field • JPanel jpTextField = new JPanel(); • jpTextField.setLayout(new BorderLayout(5, 0)); • jpTextField.add( • new JLabel("Enter a new message"), BorderLayout.WEST); • jpTextField.add(jtfMessage, BorderLayout.CENTER); • add(jpTextField, BorderLayout.NORTH); • jtfMessage.setHorizontalAlignment(JTextField.LEFT); • // Register listener • jtfMessage.addActionListener(new ActionListener() { • /** Handle ActionEvent */ • public void actionPerformed(ActionEvent e) { • messagePanel.setMessage(jtfMessage.getText()); • // jtfMessage.requestFocusInWindow(); • } • }); • } • }

  40. 6 JTextArea 文本区域 If you want to let the user enter multiple lines of text, you cannot use text fields unless you create several of them. The solution is to use JTextArea, which enables the user to enter multiple lines of text.

  41. JTextArea Constructors • JTextArea(int rows, int columns) Creates a text area with the specified number of rows and columns. • JTextArea(String s, int rows, int columns) Creates a text area with the initial text andthe number of rows and columns specified.

  42. JTextArea Properties • text • editable • columns • lineWrap • wrapStyleWord • rows • lineCount • tabSize

  43. JTextArea Methods 常用方法 • getText() Returns the string from the text field. • setText(String text) Puts the given string in the text field. • setEditable(boolean editable) Enables or disables the text field to be edited. By default, editable is true. • setColumns(int) Sets the number of columns in this text field.The length of the text field is changeable.

  44. JTextArea 触发事件 当光标移动到文本区域,并且按回车键时,触发一个ActionEvent事件。

  45. Example: Using Text Areas • This example gives a program that displays an image in a label, a title in a label, and a text in a text area.

  46. Example, cont. JTextArea不处理滚动,但可以创建一个的对象,将JTextArea的实例放入其中,让JScrollPane为JTextArea处理滚动。 JTextArea jtaDescription=new JTextArea (“dfdfd”); JScrollPane scrollPane = new JScrollPane(jtaDescription); add(scrollPane, BorderLayout.CENTER);

  47. Demo TextAreaDemo .java • import java.awt.*; • import javax.swing.*; • public class TextAreaDemo extends JFrame { • // Declare and create a description panel • private DescriptionPanel descriptionPanel = new DescriptionPanel(); • public static void main(String[] args) { • TextAreaDemo frame = new TextAreaDemo(); • frame.pack(); • frame.setLocationRelativeTo(null); • // Center the frame • frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); • frame.setTitle("TextAreaDemo"); • frame.setVisible(true); • } • public TextAreaDemo() { • // Set title, text and image in the description panel • descriptionPanel.setTitle("Canada"); • String description = "The Maple Leaf flag \n\n" + • "The Canadian National Flag was adopted by the Canadian " + • "Parliament on October 22, 1964 and was proclaimed into law " + • "by Her Majesty Queen Elizabeth II (the Queen of Canada) on " + • "February 15, 1965. The Canadian Flag (colloquially known " + • "as The Maple Leaf Flag) is a red flag of the proportions " + • "two by length and one by width, containing in its center a " + • "white square, with a single red stylized eleven-point " + • "mapleleaf centered in the white square."; • descriptionPanel.setDescription(description); • descriptionPanel.setImageIcon(new ImageIcon("image/ca.gif")); • // Add the description panel to the frame • setLayout(new BorderLayout()); • add(descriptionPanel, BorderLayout.CENTER); • } • } • // Define a panel for displaying image and text • class DescriptionPanel extends JPanel { • /** Label for displaying an image icon and a text */ • private JLabel jlblImageTitle = new JLabel(); • /** Text area for displaying text */ • private JTextArea jtaDescription = new JTextArea(); • public DescriptionPanel() { • // Center the icon and text and place the text under the icon • jlblImageTitle.setHorizontalAlignment(JLabel.CENTER); • jlblImageTitle.setHorizontalTextPosition(JLabel.RIGHT); • jlblImageTitle.setVerticalTextPosition(JLabel.BOTTOM); • // Set the font in the label and the text field • jlblImageTitle.setFont(new Font("SansSerif", Font.BOLD, 16)); • jtaDescription.setFont(new Font("Serif", Font.PLAIN, 14)); • // Set lineWrap and wrapStyleWord true for the text area • jtaDescription.setLineWrap(true); • jtaDescription.setWrapStyleWord(true); • jtaDescription.setEditable(false); • // Create a scroll pane to hold the text area • JScrollPane scrollPane = new JScrollPane(jtaDescription); • // Set BorderLayout for the panel, add label and scrollpane • setLayout(new BorderLayout(5, 5)); • add(scrollPane, BorderLayout.CENTER); • add(jlblImageTitle, BorderLayout.WEST); • } • /** Set the title */ • public void setTitle(String title) { • jlblImageTitle.setText(title); • } • /** Set the image icon */ • public void setImageIcon(ImageIcon icon) { • jlblImageTitle.setIcon(icon); • } • /** Set the text description */ • public void setDescription(String text) { • jtaDescription.setText(text); • } • }

  48. 7 JComboBox 组合框 A combo box is a simple list of items from which the user can choose. It performs basically the same function as a list, but can get only one value.

  49. JComboBox Properties • selectedIndex • selectedItem

More Related