import javax.swing.*; import java.awt.*; public class MyPanel extends JPanel { public MyPanel() { JLabel label = new JLabel("Hello, world!"); add(label); setPreferredSize(new Dimension(200, 100)); // sets preferred size to 200x100 } }
import javax.swing.*; import java.awt.*; public class MyFrame extends JFrame { public MyFrame() { JPanel panel = new JPanel(); JButton button = new JButton("Click me!"); panel.add(button); panel.setPreferredSize(new Dimension(300, 200)); // sets preferred size to 300x200 add(panel); pack(); setVisible(true); } public static void main(String[] args) { new MyFrame(); } }This example creates a JFrame with a JPanel that contains a JButton labeled "Click me!". The preferred size of the panel is set to 300x200, and the pack() method is called to size the frame to fit the components. The result is a window with the button centered in a panel that takes up most of the available space.