import javax.swing.JButton; public class MyButton extends JButton { public MyButton() { super("Click Me"); setPreferredSize(new Dimension(100, 50)); } }
import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; public class MyFrame extends JFrame { public MyFrame() { JPanel panel = new JPanel(); JTextField textField = new JTextField(20); textField.setPreferredSize(new Dimension(200, 30)); panel.add(textField); add(panel); pack(); setVisible(true); } public static void main(String[] args) { new MyFrame(); } }This example creates a JFrame that contains a JPanel with a single JTextField. In the constructor, we call the setPreferredSize method on the JTextField to set its preferred size to 200 pixels wide and 30 pixels tall. We then add the JTextField to the JPanel and add the JPanel to the JFrame. Finally, we call pack() to resize the JFrame to fit its contents and set it to visible. The package used in both examples is javax.swing.