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

Session09 swing basic

16 31 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

Thông tin cơ bản

Định dạng
Số trang 16
Dung lượng 710,18 KB

Nội dung

2/23/2018 What is a SWING • Swing is the next-generation GUI toolkit that Sun Microsystems created to enable enterprise development in Java • Swing is part of a larger family of Java products known as the Java Foundation Classes ( JFC) • The Swing package was first available as an add-on to JDK 1.1 CÔNG NGHỆ JAVA CH9 GUI PROGRAMMING - SWING Giảng viên: ThS Lê Nhật Tùng www.lenhattung.com 2/23/2018 http://www.lenhattung.com – Prior to the introduction of the Swing package, the Abstract Window Toolkit (AWT) components provided all the UI components in the JDK 1.0 and 1.1 platforms Swing Toolkit 2/23/2018 http://www.lenhattung.com http://www.lenhattung.com Other APIs • 100% Java implementation of components • Pluggable Look & Feel – customizable for different environments, or – use Java Look & Feel in every environment • Lightweight components – no separate (child) windows for components – allows more variation on component structure – makes Look & Feel possible • Three parts – component set (subclasses of JComponent) – support classes – interfaces 2/23/2018 http://www.lenhattung.com 2/23/2018 2/23/2018 Example Swing Overview import java.awt.*; import javax.swing.*; • Swing Components and the Containment Hierarchy – Swing provides many standard GUI components such as buttons, lists, menus, and text areas, windows, tool bars public class HelloAppTest { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { HelloFrame frame = new HelloFrame("Hello World App"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } } • Layout Management – Containers use layout managers to determine the size and position of the components they contain • Event Handling – Event handling is how programs respond to external events, such as the user pressing a mouse button class HelloFrame extends JFrame { public HelloFrame(String title) { super(title); JLabel label = new JLabel("Hello World!"); getContentPane().add(label); setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); } public static final int DEFAULT_WIDTH = 300; public static final int DEFAULT_HEIGHT = 200; } • Painting – Painting means drawing the component on-screen – it's easy to customize a component's painting • More Swing Features and Concepts – include support for icons, actions, Pluggable Look & Feel technology, … 2/23/2018 http://www.lenhattung.com Walk through this program http://www.lenhattung.com Adding component • What to import • The Content Pane – You need to import both java.awt.* and javax.swing.* to get all the basic classes – components must add to the frame’s content cane – Call getContentPane() to get the content pane import java.awt.*; import javax.swing.*; • Adding content – Create another Swing component • Create Frame • In this case, a label is created with the text "Hello, World!" – Call add() with the component as a parameter to add it to the frame’s content pane –Creating a JFrame gives you a "top level" container •A top-level window –The string passed to the constructor is the title of the window JLabel hello = new JLabel("Hello, world!"); frame.getContentPane().add(hello); HelloFrame frame = new HelloFrame("Hello World App"); 2/23/2018 2/23/2018 http://www.lenhattung.com 2/23/2018 http://www.lenhattung.com 2/23/2018 Resizing and showing • setSize(width, height) • pack() frame to the minimum size needed to display the items in the content pane • Calling setVisible(true) will show the JFrame Swing Components – You must set the size of the frame (directly or with pack()) before you show the frame frame.pack(); frame.setVisible(true); 2/23/2018 http://www.lenhattung.com 2/23/2018 http://www.lenhattung.com 10 Swing Container Swing Components Example • The frame (JFrame) is a top-level container – Provide a place for other components to paint themselves – The other commonly used top-level containers are dialogs (JDialog) and applets (JApplet) frame panel button label • The panel (JPanel) is an intermediate container • SwingApplication example creates four commonly used Swing components: – – – – a frame, or main window (JFrame) a panel, sometimes called a pane (JPanel) a button (JButton) a label (JLabel) 2/23/2018 http://www.lenhattung.com 11 – Used to group small lightweight components together – Other intermediate Swing containers, such as scroll panes (JScrollPane) and tabbed panes (JTabbedPane), typically play a more visible, interactive role in a program's GUI 2/23/2018 http://www.lenhattung.com 12 2/23/2018 Swing Atomic Components The Containment Hierarchy • The button and label are atomic components • A diagram of the containment hierarchy shows each container created or used by the program, along with the components it contains – components that exist as self-sufficient entities that present bits of information to the user • Often, atomic components also get input from the user • The Swing API provides many atomic components – – – – – Even the simplest Swing program has multiple levels in its containment hierarchy The root of the containment hierarchy is always a toplevel container Button (JButton) Combo boxes (JComboBox), Text fields (JTextField), Tables (JTable) … 2/23/2018 http://www.lenhattung.com Swing Components SwingApplication 13 2/23/2018 http://www.lenhattung.com 14 Top-Level Containers JFrame 2/23/2018 JApplet http://www.lenhattung.com JDialog 16 2/23/2018 General-Purpose Containers Special-Purpose Containers • Intermediate containers that can be used under many different circumstances JPanel JScrollPane JOptionPane JInternalFrame JLayeredPane JToolBar JTabbedPane 2/23/2018 JSplitPane http://www.lenhattung.com 17 Basic Controls - Buttons 2/23/2018 http://www.lenhattung.com 18 Basic Controls - MENUS • Basic Controls: Atomic components that exist primarily to get input from the user; they generally also show simple state JMenuBar 2/23/2018 http://www.lenhattung.com 19 2/23/2018 http://www.lenhattung.com 20 2/23/2018 Basic Controls - Others Uneditable Information Displays • Atomic components that exist solely to give the user information JComboBox JProgressBar JList JLabel JTooltip JScrollBar JSlider JImageIcon 2/23/2018 http://www.lenhattung.com 2/23/2018 21 http://www.lenhattung.com 22 Editable Displays of Formatted Information •Atomic components that display highly formatted information that (if you choose) can be edited by the user JColorChooser JTable 2/23/2018 JTextArea Layout Managers Arranging Elements in Windows JFileChooser JTextField http://www.lenhattung.com JTree 23 2/23/2018 http://www.lenhattung.com 24 2/23/2018 Layout Management Applications of Layout Managers • Each layout manager has its own particular use –For displaying a few components of same size in rows and columns, the GridLayout would be appropriate –To display a component in maximum possible space, a choice between BorderLayout and GridBagLayout has to be made • How to set layouts? –When a container is first created, it uses its default layout manager • Default layout of an frame is BorderLayout –A new layout manager can be set using the setLayout() method • Layout management is the process of determining the size and position of components – By default, each container has a layout manager - an object that performs layout management for the components within the container – Components can provide size and alignment hints to layout managers, but layout managers have the final say on the size and position of those components • The Java platform supplies commonly used layout managers: – FlowLayout, BorderLayout, BoxLayout, CardLayout GridLayout, and GridBagLayout 2/23/2018 http://www.lenhattung.com 25 Layout Manager – FlowLayout http://www.lenhattung.com http://www.lenhattung.com 26 FlowLayout - Example • Default layout for Panel, JPanel, and Applet • Resizes components to their preferred size • Places components in rows left to right, starting new rows if necessary • Rows are centered by default 2/23/2018 2/23/2018 public class FlowLayoutFrame extends JFrame{ public FlowLayoutFrame(String title) { super(title); this.setLayout(new FlowLayout()); this.add(new JButton("Button 1")); this.add(new JButton("2")); this.add(new JButton("Button 3")); this.add(new JButton("Long-Named Button 4")); this.add(new JButton("Button 5")); this.pack(); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } 27 2/23/2018 http://www.lenhattung.com 28 2/23/2018 FlowLayout constructors Layout Manager – BorderLayout • public FlowLayout() • public FlowLayout(int alignment) • Is the default layout manager of the content pane of every JFrame • A BorderLayout has five areas available to hold components: north, south, east, west, and center – The alignment must have the value FlowLayout.LEFT, FlowLayout.CENTER, or FlowLayout.RIGHT • public FlowLayout(int alignment, int horizontalGap, int verticalGap) – The horizontalGap and verticalGap specify the number of pixels to put between components If you don't specify a gap value, FlowLayout uses for the default gap value 2/23/2018 http://www.lenhattung.com 29 2/23/2018 http://www.lenhattung.com BorderLayout - Example The BorderLayout API public class BorderLayoutFrame extends JFrame{ public BorderLayoutFrame(String title) { super(title); // Use the content pane's default BorderLayout setLayout(new BorderLayout(2, 2)); add(new JButton("Button (NORTH)"), BorderLayout.NORTH); add(new JButton("Button (CENTER)"), BorderLayout.CENTER); add(new JButton("Button (WEST)"), BorderLayout.WEST); add(new JButton("Long-Named Button (SOUTH)"), BorderLayout.SOUTH); add(new JButton("Button (EAST)"), BorderLayout.EAST); pack(); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } • Constructors 2/23/2018 2/23/2018 http://www.lenhattung.com 31 30 – BorderLayout() • Border layout with no gaps between components – BorderLayout(int hGap, int vGap) • Border layout with the specified empty pixels between regions • Adding Components – add(component, BorderLayout.REGION) – Always specify the region in which to add the component: • CENTER is the default • to set the horizontal and vertical gaps, use: – setHgap(int) – setVgap(int) http://www.lenhattung.com 32 2/23/2018 Layout Manager – BoxLayout Layout Manager – CardLayout • The BoxLayout class puts components in a single row or column • It respects the components' requested maximum sizes, and also lets you align components 2/23/2018 http://www.lenhattung.com • The CardLayout class lets you implement an area that contains different components at different times • A CardLayout is often controlled by a combo box, with the state of the combo box determining which panel (group of components) the CardLayout displays • Tabbed panes are intermediate Swing containers that provide similar functionality 33 CardLayout 2/23/2018 http://www.lenhattung.com 34 CardLayout, Example • Stacks components on top of each other, displaying the top one • Associates a name with each component in window Panel cardPanel; CardLayout layout = new CardLayout(); cardPanel.setLayout(layout); cardPanel.add("Card 1", component1); cardPanel.add("Card 2", component2); layout.show(cardPanel, "Card 1"); layout.first(cardPanel); layout.next(cardPanel); 2/23/2018 http://www.lenhattung.com 35 2/23/2018 http://www.lenhattung.com 36 2/23/2018 GridLayout GridLayout • Divides window into equal-sized rectangles based upon the number of rows and columns specified 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")); – Items placed into cells left-to-right, top-to-bottom, based on the order added to the container – Ignores the preferred size of the component; each component is resized to fit into its grid cell • Too few components results in blank cells • Too many components results in extra columns The constructor tells the GridLayout class to create an instance that has two columns and as many rows as necessary 2/23/2018 http://www.lenhattung.com 37 The GridLayout Constructors 2/23/2018 • – Creates a single row with one column allocated per component • • GridLayout(int rows, int cols) is the most sophisticated, flexible layout manager It aligns components by placing them within a grid of cells, allowing some components to span more than one cell – The grid rows and columns aren't necessarily all the same size – Divides the window into the specified number of rows and columns – Either rows or cols (but not both) can be zero • Each component managed by a grid bag layout is associated with an instance of GridBagConstraints – The GridBagConstraints specifies: • GridLayout(int rows, int cols, int hGap, int vGap) • • • • – Uses the specified gaps between cells http://www.lenhattung.com 38 GridBagLayout • GridLayout() 2/23/2018 http://www.lenhattung.com 39 2/23/2018 How the component is laid out in the display area In which cell the component starts and ends How the component stretches when extra room is available Alignment in cells http://www.lenhattung.com 40 2/23/2018 GridBagLayout: Basic Steps GridBagConstraints Fields • Set the layout, saving a reference to it • gridx, gridy GridBagLayout layout = new GridBagLayout(); setLayout(layout); –Specifies the column and row positions of the top-left –corner of the component to be added –Upper left of grid is located at s(0,0) –Set to GridBagConstraints.RELATIVE to autoincrement row/column • Allocate a GridBagConstraints object GridBagConstraints constraints = new GridBagConstraints(); • Set up the GridBagConstraints for component constraints.gridx = x1; constraints.gridy = y1; constraints.gridwidth = width1; constraints.gridheight = height1; GridBagConstraints constraints = new GridBagConstraints(); constraints.gridx = GridBagConstraints.RELATIVE; container.add(new Button("one"), constraints); container.add(new Button("two"), constraints); • Add component to the window, including constraints add(component1, constraints); • Repeat the last two steps for each remaining component 2/23/2018 http://www.lenhattung.com 41 GridBagConstraints Fields 42 • fill – Determine how many columns and rows the component occupies – Specifies what to to an element that is smaller than the cell size constraints.fill = GridBagConstraints.VERTICAL; constraints.gridwidth = 3; – The size of row/column is determined by the widest/tallest element in it – Can be NONE, HORIZONTAL, VERTICAL, or BOTH – GridBagConstraints.REMAINDER lets the component take up the remainder of the row/column • weightx, weighty • anchor – Specifies how much the cell will stretch in the x or y direction if space is left over – If the fill is set to GridBagConstraints.NONE, then the anchor field determines where the component is placed constraints.weightx = 1.0; constraints.anchor = GridBagConstraints.NORTHEAST; – Constraint affects the cell, not the component (use fill) – Use a value of 0.0 for no grow or shrink beyond its initial size in that direction – Values are relative, not absolute http://www.lenhattung.com http://www.lenhattung.com GridBagConstraints Fields • gridwidth, gridheight 2/23/2018 2/23/2018 – Can be NORTH, EAST, SOUTH, WEST, NORTHEAST, NORTHWEST, SOUTHEAST, or SOUTHWEST 43 2/23/2018 http://www.lenhattung.com 44 2/23/2018 GridBagLayout: Example GridBagLayout: Example public GridBagTest() { setLayout(new GridBagLayout()); textArea = new JTextArea(12, 40); // 12 rows, 40 cols btnSaveAs = new JButton("Save As"); txtFile = new JTextField("C:\\Document.txt"); btbOk = new JButton("OK"); btnExit = new JButton("Exit"); gbc = new GridBagConstraints(); // Text Area gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.gridheight = 1; gbc.weightx = 1.0; gbc.weighty = 1.0; gbc.fill = GridBagConstraints.BOTH; gbc.insets = new Insets(2, 2, 2, 2); // t,l,b,r add(textArea, gbc); 2/23/2018 http://www.lenhattung.com 45 GridBagLayout: Example (con't) 2/23/2018 // OK Button gbc.gridx = 2; gbc.gridy++; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.weightx = 0.0; gbc.weighty = 0.0; gbc.fill = GridBagConstraints.NONE; add(btnOk, gbc); // Exit Button gbc.gridx = 3; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.weightx = 0.0; gbc.weighty = 0.0; gbc.fill = GridBagConstraints.NONE; add(btnExit, gbc); // Filler so Column has nonzero width Component filler = Box.createRigidArea(new Dimension(1, 1)); gbc.gridx = 1; gbc.weightx = 1.0; add(filler, gbc); // Filename Input (Textfield) gbc.gridx = 1; gbc.gridwidth = GridBagConstraints.REMAINDER; gbc.gridheight = 1; gbc.weightx = 1.0; gbc.weighty = 0.0; gbc.fill = GridBagConstraints.BOTH; add(txtFile, gbc); http://www.lenhattung.com 46 GridBagLayout: Example (con't) // Save As Button gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = 1; gbc.gridheight = 1; gbc.weightx = 0.0; gbc.weighty = 0.0; gbc.fill = GridBagConstraints.VERTICAL; add(btnSaveAs, gbc); 2/23/2018 http://www.lenhattung.com } 47 2/23/2018 http://www.lenhattung.com 48 2/23/2018 GridBagLayout: Result Strategies for Using Layout Managers 2/23/2018 http://www.lenhattung.com 49 Absolute layout – Disabling the Layout Manager –If the layout is set to null, then components must be sized and positioned by hand – Positioning components –component.setSize(width, height) –component.setLocation(left, top) or –component.setBounds(left, top, width, height) http://www.lenhattung.com http://www.lenhattung.com 50 Absolute layout: Example • Behavior 2/23/2018 2/23/2018 51 setLayout(null); Button b1 = new Button("Button 1"); Button b2 = new Button("Button 2"); b1.setBounds(0, 0, 150, 50); b2.setBounds(150, 0, 75, 50); add(b1); add(b2); 2/23/2018 http://www.lenhattung.com 52 2/23/2018 Using Layout Managers Effectively Nested Containers: Example • Use nested containers – Rather than struggling to fit your design in a single layout, try dividing the design into sections – Let each section be a panel with its own layout manager • Turn off the layout manager for some containers • Adjust the empty space around components – Change the space allocated by the layout manager – Override insets in the Container – Use a Canvas or a Box as an invisible spacer 2/23/2018 http://www.lenhattung.com 53 Nested Containers: Example 2/23/2018 http://www.lenhattung.com Nested Containers: Example public NestedLayout() { JPanel subPanel1 = new JPanel(); JPanel subPanel2 = new JPanel(); subPanel1.setLayout(new BorderLayout()); subPanel2.setLayout( new FlowLayout(FlowLayout.RIGHT, 2, 2)); setLayout(new BorderLayout(2, 2)); setBorder(BorderFactory.createEtchedBorder()); textArea = new JTextArea(12, 40); // 12 rows, 40 cols bSaveAs = new JButton("Save As"); fileField = new JTextField("C:\\Document.txt"); bOk = new JButton("OK"); bExit = new JButton("Exit"); subPanel1.add(bSaveAs, BorderLayout.WEST); subPanel1.add(fileField, BorderLayout.CENTER); subPanel2.add(bOk); subPanel2.add(bExit); add(textArea, BorderLayout.CENTER); bottomPanel.add(subPanel1); bottomPanel.add(subPanel2); // Set up buttons and textfield in bottom panel JPanel bottomPanel = new JPanel(); bottomPanel.setLayout(new GridLayout(2, 1)); 2/23/2018 http://www.lenhattung.com 54 add(bottomPanel, BorderLayout.SOUTH); } 55 2/23/2018 http://www.lenhattung.com 56 2/23/2018 Nested Containers: Result Absolute layout:Example • Suppose that you wanted to arrange a column of buttons (on the left) that take exactly 40% of the width of the container 2/23/2018 http://www.lenhattung.com 57 Turning Off Layout Manager: Result setLayout(null); int width1 = getSize().width * / 10, width2 = getSize().width - width1, height = getSize().height; JPanel buttonPanel = new JPanel(); buttonPanel.setBounds(0, 0, width1, height); buttonPanel.setLayout(new GridLayout(6, 1)); buttonPanel.add(new Label("Buttons", Label.CENTER)); buttonPanel.add(new Button("Button One")); buttonPanel.add(new Button("Button Two")); buttonPanel.add(new Button("Button Three")); buttonPanel.add(new Button("Button Four")); buttonPanel.add(new Button("Button Five")); add(buttonPanel); JPanel everythingElse = new JPanel(); everythingElse.setBounds(width1 + 1, 0, width2, height); everythingElse.add(new Label("Everything Else")); add(everythingElse); http://www.lenhattung.com 2/23/2018 58 Adjusting Space Around Components • Change the space allocated by the layout manager – Most LayoutManagers accept a horizontal spacing (hGap) and vertical spacing (vGap) argument – For GridBagLayout, change the insets • Use a Canvas or a Box as an invisible spacer – For AWT layouts, use a Canvas that does not draw or handle mouse events as an “empty” component for spacing – For Swing layouts, add a Box as an invisible spacer to improve positioning of components 2/23/2018 http://www.lenhattung.com 59 2/23/2018 http://www.lenhattung.com 60 2/23/2018 Drag-and-Drop Swing GUI Builders • Free: Matisse – Started in NetBeans (now "NetBeans GUI Builder") – Also available in MyEclipse Not in regular Eclipse • Commercial – WindowBuilder • instantiations.com – JFormDesigner • jformdesigner.com – Jvider • jvider.com – SpeedJG • wsoftware.de – Jigloo • http://www.cloudgarden.com/jigloo/ 2/23/2018 http://www.lenhattung.com 61 ...2/23/2018 Example Swing Overview import java.awt.*; import javax .swing. *; • Swing Components and the Containment Hierarchy – Swing provides many standard GUI components... java.awt.* and javax .swing. * to get all the basic classes – components must add to the frame’s content cane – Call getContentPane() to get the content pane import java.awt.*; import javax .swing. *; •... JTabbedPane 2/23/2018 JSplitPane http://www.lenhattung.com 17 Basic Controls - Buttons 2/23/2018 http://www.lenhattung.com 18 Basic Controls - MENUS • Basic Controls: Atomic components that exist primarily

Ngày đăng: 05/11/2019, 00:04

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN

w