- Использование JPanel контейнера панели
- Class JPanel
- Nested Class Summary
- Nested classes/interfaces declared in class javax.swing.JComponent
- Nested classes/interfaces declared in class java.awt.Container
- Nested classes/interfaces declared in class java.awt.Component
- Field Summary
- Fields declared in class javax.swing.JComponent
- Fields declared in class java.awt.Component
- Fields declared in interface java.awt.image.ImageObserver
- Constructor Summary
- Method Summary
- Methods declared in class javax.swing.JComponent
- Methods declared in class java.awt.Container
- Methods declared in class java.awt.Component
- Methods declared in class java.lang.Object
- Constructor Details
- JPanel
- JPanel
- JPanel
- JPanel
- Method Details
- updateUI
- getUI
- setUI
- getUIClassID
- paramString
- getAccessibleContext
- Java code for panel
- Nested Class Summary
- Nested classes/interfaces inherited from class java.awt.Container
- Nested classes/interfaces inherited from class java.awt.Component
- Field Summary
- Fields inherited from class java.awt.Component
- Fields inherited from interface java.awt.image.ImageObserver
- Constructor Summary
- Method Summary
- Methods inherited from class java.awt.Container
- Methods inherited from class java.awt.Component
- Methods inherited from class java.lang.Object
- Constructor Detail
- Panel
- Panel
- Method Detail
- addNotify
- getAccessibleContext
- JPanel basic tutorial and examples
- 1. Creating a new JPanel
- 2. Setting a layout manager for JPanel
- 3. Adding components to JPanel
- 4. Adding JPanel to a parent container
- 5. Customizing appearance for JPanel
- 6. JPanel Sample application
- Other Java Swing Tutorials:
- About the Author:
Использование JPanel контейнера панели
При построении интерфейсов нужны компоненты-контерйнеры, которые будут содержать другие компоненты пользовательского интерфейса. В Swing одним из таких компонентов-контейнеров является JPanel. По умолчанию JPanel сама по себе ничего не отрисовывает за исключением фона. При работе с контейнерами, разработчику надо решить, как правило, две основные проблемы. Первая – задать расположение дочерних компонентов и вторая – осуществить добавление компонентов на контейнер.
Рассмотрим первую проблему – задание расположения дочерних компонентов. В Swing имеется механизм Layout Manager’ов для задания структуры расположения дочерних компонентов на контейнере. Кроме того Layout Manager определяет то, как будут реагировать компоненты на изменение размеров родительского контейнера. Задается Layout Manager для контейнера с помощью метода setLayout. Вторая проблема – добавление компонента. Добавление компонента выполняется с помощью метода add. В качестве параметров этому методу передается добавляемый компонент, а также и другие объекты, отвечающие за расположение компонента. Рассмотрим пример панели, которая в качестве Layout Manager’а будет использовать Border Layout.
Исходный код представлен ниже.
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public static void createGUI() JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame(«Test frame»);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
JButton northButton = new JButton(«North»);
panel.add(northButton, BorderLayout.NORTH);
JButton southButton = new JButton(«South»);
panel.add(southButton, BorderLayout.SOUTH);
JButton eastButton = new JButton(«East»);
panel.add(eastButton, BorderLayout.EAST);
JButton westButton = new JButton(«West»);
panel.add(westButton, BorderLayout.WEST);
JButton centerButton = new JButton(«Center»);
panel.add(centerButton, BorderLayout.CENTER);
frame.getContentPane().add(panel);
frame.setPreferredSize(new Dimension(500, 400));
frame.pack();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
>
public static void main(String[] args) javax.swing.SwingUtilities.invokeLater(new Runnable() public void run() createGUI();
>
>);
>
>
Как было сказано выше для того, чтобы задать у панели Layout Manager используется метод setLayout. В данном примере ему передается ссылка на только что созданный BorderLayout, но это может быть и FlowLayout к примеру или какой-то другой лейаут. Какие существуют еще Layout Manager’ы в Swing’е думаю рассмотреть потом. Если обратиться к методу setLayout, то окажется, что он принимает в качестве параметра любой класс, который будет реализовывать интерфейс LayoutManager. Поэтому при желании можно самому создать свой лейаут. Так, лейаут у компонента задан идем дальше. Далее мы создаем комопненты, которые хотим увидеть на панели, в данном случае кнопки. При помощи метода add добавляем их на панель. При вызове метода add мы передаем туда два параметра. Первый параметр – это компонент, который хотим добавить, второй – некие constraints, которые задают расположение компонента при данном лейауте. Например мы выбрали BorderLayout. Это значит, что вся панель условно разделится на 5 частей – север (north), юг (south), запад (west), восток (east) и центер (center). Поэтому при добавлении компонента, мы говорим, в каком регионе хотим его видеть. Если в центре, то в качестве constraints передаем константу BorderLayout.CENTER, если на севере, то BorderLayout.NORTH и так далее.
Class JPanel
JPanel is a generic lightweight container. For examples and task-oriented documentation for JPanel, see How to Use Panels, a section in The Java Tutorial.
Warning: Swing is not thread safe. For more information see Swing’s Threading Policy.
Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeans has been added to the java.beans package. Please see XMLEncoder .
Nested Class Summary
Nested classes/interfaces declared in class javax.swing.JComponent
Nested classes/interfaces declared in class java.awt.Container
Nested classes/interfaces declared in class java.awt.Component
Field Summary
Fields declared in class javax.swing.JComponent
Fields declared in class java.awt.Component
Fields declared in interface java.awt.image.ImageObserver
Constructor Summary
Method Summary
Methods declared in class javax.swing.JComponent
Methods declared in class java.awt.Container
Methods declared in class java.awt.Component
Methods declared in class java.lang.Object
Constructor Details
JPanel
JPanel
JPanel
Creates a new JPanel with FlowLayout and the specified buffering strategy. If isDoubleBuffered is true, the JPanel will use a double buffer.
JPanel
Method Details
updateUI
getUI
setUI
@BeanProperty(hidden=true, visualUpdate=true, description=»The UI object that implements the Component\’s LookAndFeel.») public void setUI (PanelUI ui)
getUIClassID
@BeanProperty(bound=false, expert=true, description=»A string that specifies the name of the L&F class.») public String getUIClassID ()
paramString
Returns a string representation of this JPanel. This method is intended to be used only for debugging purposes, and the content and format of the returned string may vary between implementations. The returned string may be empty but may not be null .
getAccessibleContext
Gets the AccessibleContext associated with this JPanel. For JPanels, the AccessibleContext takes the form of an AccessibleJPanel. A new AccessibleJPanel instance is created if necessary.
Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.
Java code for panel
Panel is the simplest container class. A panel provides space in which an application can attach any other component, including other panels. The default layout manager for a panel is the FlowLayout layout manager.
Nested Class Summary
Nested classes/interfaces inherited from class java.awt.Container
Nested classes/interfaces inherited from class java.awt.Component
Field Summary
Fields inherited from class java.awt.Component
Fields inherited from interface java.awt.image.ImageObserver
Constructor Summary
Method Summary
Methods inherited from class java.awt.Container
Methods inherited from class java.awt.Component
Methods inherited from class java.lang.Object
Constructor Detail
Panel
Creates a new panel using the default layout manager. The default layout manager for all panels is the FlowLayout class.
Panel
Method Detail
addNotify
Creates the Panel’s peer. The peer allows you to modify the appearance of the panel without changing its functionality.
getAccessibleContext
Gets the AccessibleContext associated with this Panel. For panels, the AccessibleContext takes the form of an AccessibleAWTPanel. A new AccessibleAWTPanel instance is created if necessary.
Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2023, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.
JPanel basic tutorial and examples
JPanel is a Swing’s lightweight container which is used to group a set of components together. JPanel is a pretty simple component which, normally, does not have a GUI (except when it is being set an opaque background or has a visual border).
In this article, we summarize the common practices when working with JPanel in Swing. At the end, we will create a sample program looks like this:
Table of content:
1. Creating a new JPanel
The JPanel class resides in the package javax.swing and it’s a subclass of the javax.swing.JComponent class.
- Normally we create new JPanel object as simple as follows:
JPanel newPanel = new JPanel();
public class UserDetail extends JPanel < // code to add components to the panel >
JPanel newPanel = new JPanel(true); // enable double buffering JPanel newPanel = new JPanel(false); // disable double buffering
JPanel newPanel = new JPanel(new GridBagLayout()); JPanel newPanel = new JPanel(new BorderLayout());
// use grid bag layout and no double buffering: JPanel newPanel = new JPanel(new GridBagLayout(), false);
2. Setting a layout manager for JPanel
- We can call the method setLayout(LayoutManager) to specify a layout manager for the panel (after the panel is created):
JPanel newPanel = new JPanel(); newPanel.setLayout(new GridBagLayout());
// NOT recommended: JPanel newPanel = new JPanel(); // a FlowLayout manager is created by default newPanel.setLayout(new GridBagLayout()); // RECOMMENDED: JPanel newPanel = new JPanel(new GridBagLayout());
// exception: JPanel newPanel = new JPanel(); newPanel.setLayout(new BoxLayout(newPanel, BoxLayout.X_AXIS));
3. Adding components to JPanel
To add GUI components such as JLabel, JTextField, JButton. to the panel, we use the add() method. There are different versions of the add() method, so which method to be used is depending on the layout manager of the panel.
- Use the add(Component) method for the following layout managers: FlowLayout , BoxLayout , GridLayout , or SpringLayout . For example:
JLabel label = new JLabel("Enter username:"); JTextField userName = new JTextField(20); newPanel.add(label); newPanel.add(userName);
JPanel newPanel = new JPanel(new BorderLayout()); JLabel label = new JLabel("Enter username:"); JTextField userName = new JTextField(20); newPanel.add(label, BorderLayout.NORTH); newPanel.add(userName, BorderLayout.SOUTH);
GridBagConstraints constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.WEST; constraints.insets = new Insets(10, 10, 10, 10); constraints.gridx = 0; constraints.gridy = 0; newPanel.add(labelUsername, constraints);
JPanel wizardPanel = new JPanel(new CardLayout()); wizardPanel.add("Step1", step1Panel); wizardPanel.add("Step2", step2Panel);
4. Adding JPanel to a parent container
The panel cannot stand alone. It must be added to a parent container such as a JFrame or another JPanel . For example:
frame.add(newPanel); anotherPanel.add(newPanel);
5. Customizing appearance for JPanel
Normally, a JPanel does not render its own GUI. However we can set its background color, transparent background or border when necessary.
newPanel.setBackground(Color.CYAN);
newPanel.setOpaque(false); // make transparent background
newPanel.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
newPanel.setBorder(BorderFactory.createEtchedBorder());
newPanel.setBorder(BorderFactory.createLineBorder(Color.RED));
newPanel.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), "Login Panel"));
6. JPanel Sample application
We created the following program to demonstrate the typical usages of JPanel in a Swing application. The program uses a JPanel to group some labels, textfields and a button to form a login panel as follows:
As you can notice, the panel used in this program has a titled border “Login Panel”. Here is complete source code of the program:
package net.codejava.swing.jpanel; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.UIManager; /** * This program demonstrates how to use JPanel in Swing. * @author www.codejava.net */ public class SwingJPanelDemo extends JFrame < private JLabel labelUsername = new JLabel("Enter username: "); private JLabel labelPassword = new JLabel("Enter password: "); private JTextField textUsername = new JTextField(20); private JPasswordField fieldPassword = new JPasswordField(20); private JButton buttonLogin = new JButton("Login"); public SwingJPanelDemo() < super("JPanel Demo Program"); // create a new panel with GridBagLayout manager JPanel newPanel = new JPanel(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.anchor = GridBagConstraints.WEST; constraints.insets = new Insets(10, 10, 10, 10); // add components to the panel constraints.gridx = 0; constraints.gridy = 0; newPanel.add(labelUsername, constraints); constraints.gridx = 1; newPanel.add(textUsername, constraints); constraints.gridx = 0; constraints.gridy = 1; newPanel.add(labelPassword, constraints); constraints.gridx = 1; newPanel.add(fieldPassword, constraints); constraints.gridx = 0; constraints.gridy = 2; constraints.gridwidth = 2; constraints.anchor = GridBagConstraints.CENTER; newPanel.add(buttonLogin, constraints); // set border for the panel newPanel.setBorder(BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), "Login Panel")); // add the panel to this frame add(newPanel); pack(); setLocationRelativeTo(null); >public static void main(String[] args) < // set look and feel to the system look and feel try < UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); >catch (Exception ex) < ex.printStackTrace(); >SwingUtilities.invokeLater(new Runnable() < @Override public void run() < new SwingJPanelDemo().setVisible(true); >>); > >
You can download the code as well as an executable jar file of this program in the attachments section.
Other Java Swing Tutorials:
About the Author:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.