In this tutorial you will learn about the Swing JPanel and its application with practical example.
Swing JPanel
JPanel is a lightweight container. In Application or Frame it provides some space so that we can use it by putting other components.
JPanel Class Declaration
1 |
public class JPanel extends JComponent implement Accessible |
JPanel Constructor
Let’s get more understand about JPanel, Some of important constructor are listed below.
JPanel(): This constructor construct new JPanel with double buffer and flow layout.
JPanel(boolean isDoubleBuffered): This constructor construct a new JPanel with FlowLayout and given buffering strategy .
JPanel(LayoutManager layout): This constructor construct a new JPanel with the given layout manager.
JPanel(LayoutManager layout, boolean isDoubleBuffered): This constructor is used to construct new JPanel with given layout manager and buffering strategy.
JPanel Methods
Some of commonly used methods are listed below. It will help to know more about JPanel.
AccessibleContext getAccessibleContext(): This method is used to get AccessibleContext which is associated with JPanel.
void setUI(PanelUI ui): This method is used to set look and feel object.
void updateUI(): This method is used to resets the UI property with the value from current look and feel.
Example :-
An simple example to get understand about JPanel. Hopefully this will work for you.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package w3addaswing; import java.awt.Color; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class W3ADDASwing { W3ADDASwing() { JFrame frame = new JFrame("JPanel Example W3Adda"); JPanel panel = new JPanel(); panel.setBounds(40, 80, 200, 200); panel.setBackground(Color.gray); JButton btn = new JButton("JPanel Button"); btn.setBounds(50, 100, 80, 30); btn.setBackground(Color.ORANGE); panel.add(btn); frame.add(panel); frame.setSize(400, 400); frame.setLayout(null); frame.setVisible(true); } public static void main(String[] args) { // TODO code application logic here new W3ADDASwing(); } } |
Output :-
Output of this code will look like below image. You just need to copy this code and paste it in you program.