1. Trang chủ
  2. » Giáo Dục - Đào Tạo

SWING 4 layout input (lập TRÌNH NÂNG CAO SLIDE)

79 7 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Cấu trúc

  • Slide 1

  • Introduction

  • BorderLayout

  • BorderLayout

  • The BorderLayout API

  • FlowLayout

  • FlowLayout

  • The FlowLayout API

  • GridLayout

  • GridLayout

  • The GridLayout API

  • GridBagLayout

  • GridBagLayout : Specifying Constraints

  • GridBagLayout : Specifying Constraints

  • GridBagLayout : Specifying Constraints

  • GridBagLayout : Specifying Constraints

  • GridBagLayout : Specifying Constraints

  • Summary

  • Example

  • Example

  • Example

  • Slide 22

  • How to Use Check Boxes

  • How to Use Check Boxes

  • How to Use Check Boxes

  • How to Use Check Boxes

  • How to Use Check Boxes

  • How to Use Check Boxes

  • API : JCheckBox

  • API : JCheckBox

  • API : Interface ItemListener

  • API : ItemEvent

  • How to Use Radio Buttons

  • How to Use Radio Buttons

  • How to Use Radio Buttons

  • How to Use Radio Buttons

  • How to Use Radio Buttons

  • API: JRadioButton

  • API: ButtonGroup

  • How to Use Combo Boxes

  • Uneditable & Editable ComboBox

  • Using an Combo Box

  • Using an Combo Box

  • Handling Events on a Combo Box

  • Handling Events on a Combo Box

  • API: JComboBox

  • API: JComboBox

  • API: JComboBox

  • API: JComboBox

  • API: JComboBox

  • How to Use Sliders

  • How to Use Sliders

  • How to Use Sliders

  • How to Use Sliders

  • How to Use Sliders

  • API: Slider

  • API: Slider

  • API: Slider

  • API: Slider

  • API: Slider

  • Slide 61

  • Using Text Components

  • An Example of Using Each Text Component

  • Text Input

  • An Example of Using a Text Field

  • Text Fields

  • Text Fields

  • Text Fields

  • API javax.swing.JTextField

  • API javax.swing.JTextField

  • Providing a Password Field

  • An Example of Using a Password Field

  • Providing a Password Field

  • API: javax.swing.JPasswordField

  • API: javax.swing.JPasswordField

  • Using a Text Area

  • javax.swing.JTextArea

  • javax.swing.JTextArea

  • javax.swing.JTextArea

Nội dung

PHẦN - SWING LAYOUT MANAGEMENT Introduction  Every container, by default, has a layout manager -an object that implements the LayoutManager interface.* If a container's default layout manager doesn't suit your needs, you can easily replace it with another one The Java platform supplies layout managers that range from the very simple (FlowLayout and GridLayout) to the special purpose (BorderLayout and CardLayout) to the very flexible (GridBagLayout and BoxLayout) Khoa CNTT – ĐH Nông Lâm TP HCM 2014 2/79 BorderLayout  BorderLayout is the default layout manager for every content pane A BorderLayout has five areas available to hold components: north, south, east, west, and center All extra space is placed in the center area Khoa CNTT – ĐH Nông Lâm TP HCM 2014 3/79 BorderLayout public class BorderLayoutFrame extends JFrame{ public BorderLayoutFrame(String title) { super(title); Container contentPane = getContentPane(); //Use the content pane's default BorderLayout contentPane.setLayout(new BorderLayout(2,2)); contPane.add(new JButton("Button (NORTH)"), BorderLayout.NORTH); contentPane.add(new JButton(“Button (CENTER)"), BorderLayout.CENTER); contentPane.add(new JButton("Button (WEST)"), BorderLayout.WEST); contentPane.add(new JButton("Long-Named Button (SOUTH)"), BorderLayout.SOUTH); contentPane.add(new JButton("Button (EAST)"), BorderLayout.EAST); pack(); // coding }} Khoa CNTT – ĐH Nông Lâm TP HCM 2014 4/79 The BorderLayout API By default, a BorderLayout puts no gap between the components it manages In the preceding applet, any apparent gaps are the result of the buttons reserving extra space around their apparent display area You can specify gaps (in pixels) using the following constructor:  BorderLayout(int horizontalGap, int verticalGap) You can also use the following methods to set the horizontal and vertical gaps, respectively:  void setHgap(int)  void setVgap(int) Khoa CNTT – ĐH Nông Lâm TP HCM 2014 5/79 FlowLayout  FlowLayout is the default layout manager for every JPanel It simply lays out components from left to right, starting new rows if necessary Khoa CNTT – ĐH Nông Lâm TP HCM 2014 6/79 FlowLayout Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); contentPane.add(new JButton("Button 1”); contentPane.add(new JButton("2")); contentPane.add(new JButton("Button 3")); contentPane.add(new JButton("Long-Named Button 4")); contentPane.add(new JButton("Button 5”); pack(); Khoa CNTT – ĐH Nông Lâm TP HCM 2014 7/79 The FlowLayout API   The FlowLayout class has three constructors: public FlowLayout() public FlowLayout(int alignment) public FlowLayout(int alignment, int horizontalGap, int verticalGap) The alignment argument must have the value FlowLayout.LEFT, FlowLayout.CENTER, or FlowLayout.RIGHT The horizontalGap and verticalGap arguments specify the number of pixels to put between components If you don't specify a gap value, FlowLayout uses for the default gap value Khoa CNTT – ĐH Nông Lâm TP HCM 2014 8/79 GridLayout  GridLayout simply makes a bunch of components equal in size and displays them in the requested number of rows and columns Here's an applet that uses a GridLayout to control the display of five buttons: Khoa CNTT – ĐH Nông Lâm TP HCM 2014 9/79 GridLayout   Container contentPane = getContentPane(); contentPane.setLayout(new GridLayout(0,2)); contentPane.add(new JButton("Button 1")); contentPane.add(new JButton("2")); contentPane.add(new JButton("Button 3")); contentPane.add(new JButton("Long-Named Button 4")); contentPane.add(new JButton("Button 5")); The constructor tells the GridLayout class to create an instance that has two columns and as many rows as necessary Khoa CNTT – ĐH Nông Lâm TP HCM 2014 10/79 An Example of Using a Text Field JTextField textField = new JTextField(10); textField.setActionCommand(textFieldString); textField.addActionListener(this);  As with buttons, you can set an action command and register an action listener on a text field The actionPerformed method copies the text field's contents to a label  public void actionPerformed(ActionEvent e) { String prefix = "You typed \""; JTextField source = (JTextField)e.getSource(); actionLabel.setText(prefix + source.getText() + "\""); }  Khoa CNTT – ĐH Nông Lâm TP HCM 2014 65/79 Text Fields The usual way to add a text field to a window is to add it to a panel or other container  JPanel panel = new JPanel(); JTextField textField = new JTextField("Default input", 20); panel.add(textField);  This code adds a text field and initializes the text field by placing the string "Default input" inside it The second parameter of this constructor sets the width In this case, the width is 20 "columns" This number is used along with metrics provided by the field's current font to calculate the field's preferred width It does not limit the number of characters the user can enter  If you need to reset the number of columns at run time, you can that with the setColumns method After changing the size of a text box with the setColumns method, you need to call the validate method of the surrounding container  Khoa CNTT – ĐH Nông Lâm TP HCM 2014 66/79 Text Fields       textField.setColumns(10); panel.validate(); The validate method recomputes the size and layout of all components in a container After you use the validate method, the layout manager repaints the container, and the changed size of the text field will be visible To make a blank text field, just leave out the string as a parameter for the JTextField constructor: JTextField textField = new JTextField(20); You can change the contents of the text field at any time by using the setText method from the TextComponent parent class mentioned in the previous section For example: textField.setText("Hello!"); Khoa CNTT – ĐH Nông Lâm TP HCM 2014 67/79 Text Fields   And, as was also mentioned in the previous section, you can find out what the user typed by calling the getText method This method returns the exact text that the user typed To trim any extraneous leading and trailing spaces from the data in a text field, apply the trim method to the return value of getText: String text = textField.getText().trim(); To change the font in which the user text appears, use the setFont method Khoa CNTT – ĐH Nông Lâm TP HCM 2014 68/79 API javax.swing.JTextField     JTextField(int columns) Constructs a new empty TextField with the specified number of columns JTextField(Document doc, String text, int columns) Constructs a new JTextField that uses the given text storage model and the given number of columns JTextField(String text) Constructs a new TextField initialized with the specified text JTextField(String text, int columns) Constructs a new TextField initialized with the specified text and columns Khoa CNTT – ĐH Nông Lâm TP HCM 2014 69/79 API javax.swing.JTextField     public int getColumns() Returns the number of columns in this TextField public void setColumns(int columns) Sets the number of columns in this TextField, and then invalidate the layout Parameters:columns - the number of columns >= public void addActionListener(ActionListener l) Adds the specified action listener to receive action events from this textfield protected Document createDefaultModel() Creates the default implementation of the model to be used at construction if one isn't explicitly given An instance of PlainDocument is returned Returns:the default model implementation Khoa CNTT – ĐH Nông Lâm TP HCM 2014 70/79 Providing a Password Field  Swing provides the JPasswordField class, a subclass of JTextField, to use in place of a text field for password entry For security reasons, a password field doesn't show the characters the user types Instead the field displays another character such as an asterisk '*' As another security precaution, the password field stores its value as an array of characters, rather than as a string Khoa CNTT – ĐH Nông Lâm TP HCM 2014 71/79 Field JPasswordField is a subclass of JTextField that, instead of showing the actual character the user types, shows another character such as an asterisk '*'  JPasswordField passwordField = new JPasswordField(10); passwordField.setActionCommand(passwordFieldString); passwordField.addActionListener(this);  Notice that this code uses the getPassword method to get the contents of the password field instead of getText  public void actionPerformed(ActionEvent e) { String prefix = "You typed \""; JPasswordField source = (JPasswordField)e.getSource(); actionLabel.setText(prefix + new String(source.getPassword()) + "\""); }  Khoa CNTT – ĐH Nông Lâm TP HCM 2014 72/79 Providing a Password Field JPasswordField passwordField = new JPasswordField(10); passwordField.setEchoChar('#'); passwordField.addActionListener(new ActionListener() { });  Finally, the code adds an action listener to the password field, which action-validates the value typed in by the user Here's the implementation of the action listener's actionPerformed method: public void actionPerformed(ActionEvent e) { JPasswordField input = (JPasswordField)e.getSource(); char[] password = input.getPassword(); if (isPasswordCorrect(password)) { JOptionPane.showMessageDialog(f, "Success! You typed the right password."); } else { JOptionPane.showMessageDialog(f, "Invalid password Try  }} again.", "Error Message", OptionPane.ERROR_MESSAGE); Khoa CNTT – ĐH Nông Lâm TP HCM 2014 73/79 API: javax.swing.JPasswordField    public JPasswordField(String text) Constructs a new JPasswordField initialized with the specified text The document model is set to the default, and the number of columns to public JPasswordField(int columns) Constructs a new empty JPasswordField with the specified number of columns A default model is created, and the initial string is set to null Parameters:columns - the number of columns >= public JPasswordField(String text, int columns) Constructs a new JPasswordField initialized with the specified text and columns The document model is set to the default Parameters:text - the text to be displayed, null if none columns - the number of columns >= Khoa CNTT – ĐH Nông Lâm TP HCM 2014 74/79 API: javax.swing.JPasswordField   public void setEchoChar(char c) Sets the echo character for this JPasswordField Note that this is largely a suggestion, since the view that gets installed can use whatever graphic techniques it desires to represent the field Setting a value of indicates that you wish to see the text as it is typed, similar to the behavior of a standard JTextField public char[] getPassword() Returns the text contained in this TextComponent If the underlying document is null, will give a NullPointerException For stronger security, it is recommended that the returned character array be cleared after use by setting each character to zero Khoa CNTT – ĐH Nông Lâm TP HCM 2014 75/79 Using a Text Area   A text area displays multiple lines of text and allows the user to edit the text with the keyboard and mouse JTextArea 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); By default, a text area doesn't wrap lines Instead it shows all the text on one line, and if the text area is within a scroll pane, allows itself to be scrolled horizontally This example turns line wrapping on with a call to setLineWrap and then calls setWrapStyleWord to indicate that the text area 76/79 Khoa CNTT – ĐH Nông Lâm TP HCM 2014 should wrap lines at word boundaries rather than javax.swing.JTextArea public JTextArea() Constructs a new TextArea A default model is set, the initial string is null, and rows/columns are set to  public JTextArea(String text) Constructs a new TextArea with the specified text displayed A default model is created and rows/columns are set to  public JTextArea(int rows, int columns)  public JTextArea(String text,int rows,int columns)  public JTextArea(Document doc) Constructs a new JTextArea with the given document model, and defaults for all of the other arguments (null, 0, 0)  public JTextArea(Document doc, String text, int rows,int columns) Constructs a new JTextArea with the specified number of rows and columns, and the given model All of the constructors feed through this constructor  Khoa CNTT – ĐH Nông Lâm TP HCM 2014 77/79 javax.swing.JTextArea void setColumns(int cols) tells the text area the preferred number of columns it should use Parameters: cols The number of columns  void setRows(int rows) tells the text area the preferred number of rows it should use Parameters:rowsThe number of rows  public void insert(String str, int pos) Insert the specified text at the given position (offset from the beginning of the document) To insert text at the beginning of the document, use a position of  public void replaceRange(String str, int start, int end) Replace a section of the document beginning with the character at the start position and ending with the character at the end position with the given78/79 Khoa CNTT – ĐH Nông Lâm TP HCM 2014  javax.swing.JTextArea     void append(String newText) appends the given text to the end of the text already in the text area void setLineWrap(boolean wrap) turns line-wrapping on or off void setWrapStyleWord(boolean word) If word is true, then long lines are wrapped at word boundaries If it is false, then long lines are broken without taking word boundaries into account void setTabSize(int c) sets tab stops every c columns Note that the tabs aren't converted to spaces, but they cause alignment with the next tab stop Khoa CNTT – ĐH Nông Lâm TP HCM 2014 79/79 ... supplies layout managers that range from the very simple (FlowLayout and GridLayout) to the special purpose (BorderLayout and CardLayout) to the very flexible (GridBagLayout and BoxLayout) Khoa... and BoxLayout) Khoa CNTT – ĐH Nông Lâm TP HCM 20 14 2/79 BorderLayout  BorderLayout is the default layout manager for every content pane A BorderLayout has five areas available to hold components:... default BorderLayout contentPane.setLayout(new BorderLayout(2,2)); contPane.add(new JButton("Button (NORTH)"), BorderLayout.NORTH); contentPane.add(new JButton(“Button (CENTER)"), BorderLayout.CENTER);

Ngày đăng: 29/03/2021, 10:53

TỪ KHÓA LIÊN QUAN