import javax.swing.*; import java.awt.*; public class JPanelExample extends JFrame { public JPanelExample() { JPanel panel = new JPanel(new GridLayout(2, 2)); JButton button1 = new JButton("Button 1"); JButton button2 = new JButton("Button 2"); JButton button3 = new JButton("Button 3"); JButton button4 = new JButton("Button 4"); panel.add(button1); panel.add(button2); panel.add(button3); panel.add(button4); // Set horizontal alignment of panel to center panel.setAlignmentX(Component.CENTER_ALIGNMENT); add(panel); setTitle("JPanel Example"); setSize(300, 200); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); } public static void main(String[] args) { new JPanelExample().setVisible(true); } }
import javax.swing.*; import java.awt.*; public class JPanelExample extends JFrame { public JPanelExample() { JPanel panel1 = new JPanel(); JPanel panel2 = new JPanel(); // Set background colors for panels panel1.setBackground(Color.GREEN); panel2.setBackground(Color.YELLOW); // Set horizontal alignment of panel1 to right and panel2 to left panel1.setAlignmentX(Component.RIGHT_ALIGNMENT); panel2.setAlignmentX(Component.LEFT_ALIGNMENT); add(panel1, BorderLayout.WEST); add(panel2, BorderLayout.EAST); setTitle("JPanel Example"); setSize(300, 200); setLocationRelativeTo(null); setDefaultCloseOperation(EXIT_ON_CLOSE); } public static void main(String[] args) { new JPanelExample().setVisible(true); } }In this example, we create two JPanels and set their background colors to green and yellow respectively. We set the horizontal alignment of panel1 to right and panel2 to left using the setAlignmentX method. We add them to the frame using BorderLayout such that panel1 is on the left and panel2 is on the right. The package library for the JPanel setAlignmentX method is javax.swing.