In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail how to use the advanced Swing container in Java graphical interface development, and the content of the article is of high quality, so the editor will share it with you for reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.
We will learn about some containers built on top of these layout managers and others that do not require layout managers.
Starting with the Box class, we will find the best way to use the BoxLayout manager to create a single-row or single-column component. Next we'll take a look at the JSplitPane container, which is similar to a special Box with only two components. JSplitPane provides a separator bar that users can drag to resize the components to meet their needs.
Then we'll explore the JTabbedPane container, which works like a container managed by the CardLayout layout manager, except that the built-in tags allow us to move from a card to a card. We can also use JTabbedPane to create multiple screens, and the property page dialog box is used for user input.
The two high-level Swing containers discussed at the end are JScrollPane and JViewport. Both components provide the ability to display a collection of large components within a limited screen reality. JScrollPane adds scroll bars to the display area so that we can move around large components within a small area. In fact, JScrollPane uses JViewport to split parts of large components that are invisible.
Let's start with the first container, the Box class.
11.1 Box class
As a subclass of the JComponent class, the Box class is a special Java Container that creates single-row or single-column components with the help of BoxLayout Manager. The Box container acts like JPanel (or Panel), but has a different default layout manager, BoxLayout. There are some problems with using BoxLayout outside of Box, while Box simplifies the use of BoxLayout. We only need three steps to associate the BoxLayout manager with the container: manually create the container, create the layout manager, and then associate the manager with the container. When we create an instance of Box, we perform these three steps at a time. In addition, we can use Box's inline class called Box.Filler to better place the components in the container.
11.1.1 create Box
We have three ways to create a Box, a constructor, and two static factory methods:
Public Box (int direction) Box horizontalBox = new Box (BoxLayout.X_AXIS); Box verticalBox = new Box (BoxLayout.Y_AXIS); public static Box createHorizontalBox () Box horizontalBox = Box.createHorizontalBox (); public static Box createVerticalBox () Box verticalBox = Box.createVerticalBox ()
Note that the Box class is not designed to be used as a JavaBean component. The use of this container in IDE is awkward.
Infrequently used constructors require the direction of the layout manager's primary coordinates. This direction is specified by two constants of BoxLayout: X_AXIS or Y_AXIS, which are used to create horizontal or vertical boxes, respectively. Instead of specifying the direction manually, we can simply create a box with the desired direction through the factory method provided: createHorizontalBox () or createVerticalBox ().
Populating a horizontal and vertical Box with JLabel,JTextField and JButton demonstrates the flexibility of BoxLayout, as shown in figure 11-1.
For horizontal containers, labels and buttons are displayed with their optimal width because their maximum size is the same as the optimal size. The text field uses the remaining space.
In vertical containers, the size of labels and buttons is also their optimal size, because their maximum size is still the same as their optimal size. The height of the text fills the height that the label and button do not use, and its width is the same as the width of the container.
The source code for creating the screen shown in figure 11-1 is shown in listing 11-1.
Package swingstudy.ch21; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.Box; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField Public class BoxSample {/ * * @ param args * / public static void main (String [] args) {/ / TODO Auto-generated method stub Runnable runner = new Runnable () {public void run () {JFrame verticalFrame = new JFrame ("Vertical"); verticalFrame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE) Box verticalBox = Box.createVerticalBox (); verticalBox.add (new JLabel ("Top")); verticalBox.add (new JTextField ("Middle")); verticalBox.add (new JButton ("Bottom")); verticalFrame.add (verticalBox, BorderLayout.CENTER); verticalFrame.setSize (150,150) VerticalFrame.setVisible (true); JFrame horizontalFrame = new JFrame ("Horizontal"); horizontalFrame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); Box horizontalBox = Box.createHorizontalBox (); horizontalBox.add (new JLabel ("Left")); horizontalBox.add (new JTextField ("Middle")) HorizontalBox.add (new JButton ("Right")); horizontalFrame.add (horizontalBox, BorderLayout.CENTER); horizontalFrame.setSize (150,150); horizontalFrame.setVisible (true);}; EventQueue.invokeLater (runner);}}
11.1.2 Box attribute
As shown in Table 11-1, Box has only two properties. Although the layout property is inherited by its parent class Container, the setLayout (LayoutManager) method, if called on the Box object, this class throws an AWTError. Once the BoxLayout manager is set in its constructor, it can be changed and its direction cannot be changed.
11.1.3 using Box.Filer
The Box class has an inline class Box.Filler that helps us create invisible components to better position components within containers using BoxLayout layout managers. By directly manipulating the minimum, maximum and optimal size of the components created, we can create components that can grow to fill unused space or maintain a fixed size, making the screen more acceptable to users.
Note that technically, the use of Box.Filler is not limited to containers that use the BoxLayout layout manager. We can use it anywhere else using Component. It's just that the components are invisible.
Instead of using the Box.Filler class directly, some static methods of the Box class can help us create appropriate filler components. The factory approach allows us to classify components by type, rather than by minimum, maximum, or optimal size. We will learn about these methods in the next two sections.
If we are interested in the class definition, the class definition for Box.Filler is shown below. Similar to the Box class, Box.Filler is not originally used as a JavaBean component.
Public class Box.Filler extends Component implements Accessible {/ / Constructors public Filler (Dimension minSize, Dimension prefSize, Dimension maxSize); / / Properties public AccessibleContext getAccessibleContext (); public Dimension getMaximumSize (); public Dimension getMinimumSize (); public Dimension getPreferredSize (); / / Others protected AccessibleContext accessibleContext; public void changeShape (Dimension minSize, Dimension prefSize, Dimension maxSize);}
11.1.4 create an extended area
If a component has a smaller minimum and optimal size, and the maximum size is larger than the screen size, the component can be expanded in one or both directions to occupy unused space between components in the container. In the case of Box, or rather, the layout manager is a container of BoxLayout, and the extension occurs in the direction that the layout manager initially chose (BoxLayout.X_AXIS or BoxLayout.Y_AXIS). For horizontal boxes, the extension affects the width of the component. For vertical boxes, the extension is reflected in the height of the component.
The name commonly specified for this extension component type is glue. The two types of glue are direction-independent glue and direction-related glue. The following Box factory method is used to create glued components:
Public static Component createGlue () / / Direction independent Component glue = Box.createGlue (); aBox.add (glue); public static Component createHorizontalGlue (); / / Direction dependent: horizontal Component horizontalGlue = Box.createHorizontalGlue (); aBox.add (horizontalGlue); public static Component createVerticalGlue () / / Direction dependent: vertical Component verticalGlue = Box.createVerticalGlue (); aBox.add (verticalGlue)
Once we have created the glue, we can add it to the container like any other component, through Container.add (Component) or other add () methods. Glue allows us to align components within the container, as shown in figure 11-2.
We can add glued components to any container whose layout manager takes into account the minimum, maximum and optimal size of the component, such as BoxLayout. For example, figure 11-3 shows what it looks like when we add a glued component to the JMenuBar before the last JMenu. Because the layout manager of JMenuBar is BoxLayout (actually a subclass javax.swing.plaf.basic.DefaultMenuLayout), this pushes the last menu to the right of the toolbar, similar to the Motif/CDE-style help menu.
Note that it is recommended to avoid using this feature of glued components to set menus on the menu bar. In fact, JMenuBar's public void sethelpMenu (JMenu menu) will implement this behavior without throwing an Error. Of course, many of us are still waiting for this operation.
11.1.5 create a fixed area
Because glued components expand to fill the available space, if we want a fixed distance between components, we need to create a fixed component, or strut. When we do this, we need to specify the size of the strut. Strut can be two-dimensional, requiring us to specify the width or debug of the component, or it can be one-dimensional, requiring us to specify width or height.
Public static Component createRigidArea (Dimension dimension) / / Two-dimensional Component rigidArea = Box. CreateRigidArea (new Dimension (10,10)); aBox.add (rigidArea); public static Component createHorizontalStrut (int width) / / One-dimensional: horizontal Component horizontalStrut = Box. CreateHorizontalStrut (10); aBox.add (horizontalStrut); public static Component createVerticalStrut (int height) / / One-dimensional: vertical Component verticalStrut = Box. CreateVerticalStrut (10); aBox.add (verticalStrut)
Note that although direction-independent glued components created using the createGule () method have no side effects when we modify the orientation of the container, creating fixed areas can cause layout problems when modifying coordinates. (imagine dragging the menu bar) this is because the component has a minimum size. Using the createRigidArea () method is not recommended unless we do need a two-dimensional empty component.
Figure 11-4 shows some fixed components. Note that we can change the fixed distance between different components, and the fixed component at the end of the container has no effect. After the user adjusts the screen, the fixed distance between the components remains the same, as shown in figure 11-4.
11.2 JSplitPane Class
Similar to the Box container, the JSplitPane container allows us to display components in a single row or column. While Box can contain any number of components, JSplitPane can only be used to display two components. Components can be resized and separated by a removable separator. The separator bar allows the user to resize the included components by dragging the separator bar. Figure 11-5 shows the vertical and horizontal split panels, and what they look like before and after moving the separator bar.
11.2.1 create JSplitPane
JSplitPane has five constructors. With these constructors, we can initialize the orientation of the included component pairs, set the continuousLayout property, or initialize the component pairs for the container.
Public JSplitPane () JSplitPane splitPane = new JSplitPane (); public JSplitPane (int newOrientation) JSplitPane splitPane = new JSplitPane (JSplitPane.VERTICAL_SPLIT); public JSplitPane (int newOrientation, boolean newContinuousLayout) JSplitPane splitPane = new JSplitPane (JSplitPane.VERTICAL_SPLIT, true); public JSplitPane (int newOrientation, Component newLeftComponent, Component newRightComponent) JComponent topComponent = new JButton ("Top Button"); JComponent bottomComponent = new JButton ("Bottom Button"); JSplitPane splitPane = new JSplitPane (JSplitPane.VERTICAL_SPLIT, topComponent, bottomComponent) Public JSplitPane (int newOrientation, boolean newContinuousLayout, Component newLeftComponent, Component newRightComponent) JSplitPane splitPane = new JSplitPane (JSplitPane.VERTICAL_SPLIT, true, topComponent, bottomComponent)
Unless otherwise specified, the default orientation is horizontal. The direction can be specified by the constant VERTICAL_SPLIT or HORIZONTAL_SPLIT of JSplitPane. The continuousLayout property setting determines how the splitter panel responds when the user drags the splitter bar. When set to false (the default), only delimiters are redrawn when dragging. When set to true, JSplitPane resizes and redraws components on each side of the separator bar when the user drags the separator bar.
Note that if the direction is JSplitPane.VERTICAL_SPLIT, we can think of the upper component as the left component and the lower component as the right component.
If we use a constructor with no arguments, the initial set of components within the delimited panel consists of buttons (two JButton components). The other two constructors show the initial two components set. Oddly, the remaining two constructors do not provide components within the container by default. To add or modify components within JSplitPane, see the section "modifying JSplitPane components" later.
11.2.2 JSplitPane Properties
Table 11-2 shows the 17 properties of JSplitPane.
Set orientation
In addition to initializing the direction in the constructor, we can modify the JSplitPane direction by changing the direction property to JSplitPane.VERTICAL_SPLIT or JSplitPane.HORIZONTAL_SPLIT. If we try to change the property to a non-equivalent setting, an IllegalArgumentException will be thrown.
It is not recommended to change the orientation dynamically at run time because it can confuse the user. However, if we are using a visual development tool, we can display the setting orientation property after creating the JSplitPane. When there is no visual programming, we usually initialize the direction when we create the JSplitPane.
Modify JSplitPane components
There are four read-write properties that can be used to handle different locations of components within a JSplitPane: bottomComponent, leftComponent, rightComponent, and topComponent. In fact, these four attributes represent two kinds of internal components: the left and upper components are one, and the right and lower components represent the other.
We should use attributes appropriate to the direction of our JSplitPane. Using inappropriate attribute methods can make it very difficult for programmers to maintain their lives. Imagine that after creating the user interface, you will see the following code six months later:
JComponent leftButton = new JButton ("Left"); JComponent rightButton = new JButton ("Right"); JSplitPane splitPane = new JSplitPane (JSplitPane.VERTICAL_SPLIT); splitPane.setLeftComponent (leftButton); splitPane.setRightComponent (rightButton)
If we look at the code, based on the variable name and the use of the setXXXComponent () method, we might think that the screen contains a button on the left and a button on the right. But the instantiated JSplitPane has a vertical orientation, and the interface created is shown in figure 11-6. The variables used are the label of the button, not their location.
If the setTopComponent () and setBottomComponent () methods use better variable names, the code will be easier to understand:
JComponent topButton = new JButton ("Left"); JComponent bottomButton = new JButton ("Right"); JSplitPane splitPane = new JSplitPane (JSplitPane.VERTICAL_SPLIT); splitPane.setTopComponent (topButton); splitPane.setBottomComponent (bottomButton)
Move the JSplitPane delimiter
Initially, the delimiter is displayed below the upper component or at the appropriate size on the right side of the left component. At any time, we can reset the delimited position by calling the restToPreferredSizes () method of JSplitPane. If we are programming to locate the delimiter, we can modify the dividerLocation property through setDividerLocation (newLocation). This property can modify an int position to indicate the absolute distance from the top or left, or set to a JSplitPane value between 0.0 and 1.0, representing a percentage of the width of the container.
Note that IllegalArgumentException is thrown if the property is set to a value outside the range of 0. 0 and 1. 0.
If we want to set the location of the delimiter, we must wait until the component has been implemented. In essence, this means that components must be visible. There are several ways to do this, and the most direct way is to associate a HierarchyListener to the JSplitPane and listen when the HierarchyEvent becomes a SHOWING_CHANGED. The following code snippet demonstrates this, changing the delimiter position to 75%.
HierarchyListener hierarchyListener = new HierarchyListener () {public void hierarchyChanged (HierarchyEvent e) {long flags = e.getChangeFlags (); if ((flags & HierarchyEvent.SHOWING_CHANGED) = = HierarchyEvent.SHOWING_CHANGED) {splitPane.setDividerLocation (.75);}; splitPane.addHierarchyListener (hierarchyListener)
Although we can set the dividerLocation property with the declare value, we only get an int value that identifies the absolute position.
Resizing components and using extensible delimiters
There are restrictions on resizing components within JSplitPane. JSplitPane takes into account the minimum size of each included component. If you drag the delimiter so that a component shrinks to less than its minimum size, the scrolling panel does not allow the user to drag the separator beyond that minimum size.
Note that we can programmatically put the delimiter anywhere, even making the component smaller than its minimum size. However, this is not a good idea, because the minimum size of the component exists for a reason.
If the minimum dimension of the component is too large for JSplitPane, we need to modify the minimum size of the component so that the delimiter can use the space of the component. For AWT components, changing the minimum size of a standard component requires subclass derivation. For the Swing component, we can simply call the setMinimumSize () method of JComponent through a new Dimension. However, the minimum size should be set reasonably. If we explicitly reduce its minimum size, the component will not work properly.
There is a better way to make one component take up more space than others: set the onTouchExpandable property of JSplitPane to true. When this property is true, an icon is added to the delimiter, allowing the user to completely collapse one of the two components to specify full space for the other. In the box in figure 11-7, the icon is a combination of up and down arrows.
Figure 11-7 shows what this icon looks like (rendered via Ocean look and feel) and demonstrates what it looks like when you select the up arrow on the delimiter to expand the lower component to its full size. Clicking the icon on the delimiter again causes the component to return to its previous position. Clicking outside the icon on the delimiter positions the delimiter so that the folded component is at its optimal size.
Note that there is no easy way to modify the icon of the extended delimiter or how the delimiter is rendered. Both aspects are defined by the BasicSplitPaneDivider subclass and created in the createDefaultDivider () method of the BasicSplitPaneUI subclass for a particular type of look and feel. We can simply modify the border around the delimiter, which is a custom border.
The lastDividerLocation attribute allows us or the system to query the previous delimiter location. JSplitPane uses this property when the user selects the maximizer icon to unminimize a component in the JSplitPane.
Be careful, be careful that the minimum size is based on the container size or its initial size. Placing these properties in JSplitPane may require us to manually set the minimum or optimal size of the component. The components that most often cause problems when used in JSplitPane are JTextArea and JScrollPane.
Resize JSplitPane
If there is extra space in the JSplitPane that is not needed by the optimal size of the components it contains, the space is allocated according to the resizeWeight property setting. The initial setting of this property is 0.0, which means that the components on the right or below will get extra space. Changing this setting to 1.0 allocates all space to the left or upper component. 0.5 separates the panel between the two components. Figure 11-8 shows the effect of these changes.
11.2.3 listening for JSplitPane property changes
The JSplitPane class defines the following constants to help listen for changes in boundary properties:
CONTINUOUS_LAYOUT_PROPERTY
DIVIDER_LOCATION_PROPERTY
DIVIDER_SIZE_PROPERTY
LAST_DIVIDER_LOCATION_PROPERTY
ONE_TOUCH_EXPANDABLE_PROPERTY
ORIENTATION_PROPERTY
RESIZE_WEIGHT_PROPERTY
One way to monitor when a user moves a delimiter is to listen for changes in the lastDividerLocation property. The example in listing 11-2 associates a PropertyChangeListener to the JSplitPane, showing the current delimiter position, the current last position, and the previous last position. The components above and below the delimiters are the OvalPanel class (discussed in Chapter 4), drawn to populate the dimensions of the component. This component helps demonstrate the effect state of setting the continuousLayout property to true.
Package swingstudy.ch21; import java.awt.BorderLayout; import java.awt.EventQueue; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JSplitPane; import swingstudy.ch04.OvalPanel Public class PropertySplit {/ * * @ param args * / public static void main (String [] args) {/ / TODO Auto-generated method stub Runnable runner = new Runnable () {public void run () {JFrame frame = new JFrame ("PropertySplit"); frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE) / / create/configure split pane JSplitPane splitPane = new JSplitPane (JSplitPane.VERTICAL_SPLIT); splitPane.setContinuousLayout (true); splitPane.setOneTouchExpandable (true); / / create top component JComponent topComponent = new OvalPanel (); splitPane.setTopComponent (topComponent) / / create bottom component JComponent bottomComponent = new OvalPanel (); splitPane.setBottomComponent (bottomComponent); / / create PropertyChangeListener PropertyChangeListener propertyChangeListener = new PropertyChangeListener () {public void propertyChange (PropertyChangeEvent event) {JSplitPane sourceSplitPane = (JSplitPane) event.getSource () String propertyName = event.getPropertyName (); if (propertyName.equals (JSplitPane.LAST_DIVIDER_LOCATION_PROPERTY)) {int current = sourceSplitPane.getDividerLocation (); System.out.println ("Current:" + current) Integer last = (Integer) event.getNewValue (); System.out.println ("Last:" + last); Integer priorLast = (Integer) event.getOldValue (); System.out.println ("Prior last:" + priorLast) }; / / attach listener splitPane.addPropertyChangeListener (propertyChangeListener); frame.add (splitPane, BorderLayout.CENTER); frame.setSize (300,150); frame.setVisible (true) }; EventQueue.invokeLater (runner);}}
As shown in the sample output below, when we run the previous program, we will notice the change in the lastDividerLocation property to reflect the drag of the delimiter. When the user stops dragging the delimiter, the last setting is set to the previous setting of the dividerLocation property, rather than the initial setting when the user starts dragging. When the user drags the delimiter, the current value becomes the last value and then the previous last value.
Current: 11 Last:-1 Prior last: 0 Current: 12 Last: 11 Prior last:-1 Current: 12 Last: 12 Prior last: 11 Current: 12 Last: 11 Prior last: 12 Current: 15 Last: 12 Prior last: 11 Current: 15 Last: 15 Prior last: 12 Current: 15 Last: 12 Prior last: 15 Current: 112 Last: 15 Prior last: 12 Current: 112 Last: Prior last: 15 Current: 112 Last: 15 Prior last: 112
Note that PropertyChangeListener does not support the BOTTOM, DIVIDER, LEFT, RIGHT and TOP constants of the JSplitPane class. Instead, they are internal constraints used for the add (Component component, Object constraints) method.
11.2.4 Custom JSplitPane types
Each installable Swing look and feel provides a different JSplitPane look and feel and a default set of UIResources values for the component. Figure 11-9 shows the JSplitPane container appearance of the pre-installed collection of look and feel types: Motif,Windows and Ocean.
Table 11-3 shows the collection of UIResource-related attributes available to JSplitPane. For the JSplitPane component, there are 25 different properties, including 3 delimiter-specific properties.
On the Java graphical interface development of the advanced Swing container how to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.