Course Content
Advanced Java 2077
Advanced Java 2077
Creating Basic GUI Components
In the previous chapters, we learned about the basics of Java GUI development, including the main libraries used to develop GUIs and the different types of layout managers. In this chapter, we will learn about creating basic GUI components, such as buttons, labels, and text fields.
Buttons
Buttons are one of the most basic GUI components. They are used to perform an action when a user clicks on them. To create a button in Java, you can use the JButton
class. Here are some examples of different types of buttons.
Main
JButton button1 = new JButton("Click me"); JButton button2 = new JButton("Submit"); JButton button3 = new JButton("Cancel");
These codes create three different buttons with the text "Click me"
, "Submit"
, and "Cancel"
, respectively.
Labels
Labels are used to display text or images in a GUI application. To create a label in Java, you can use the JLabel
class. Here are some examples of different types of labels.
Main
JLabel label1 = new JLabel("Enter your name:"); JLabel label2 = new JLabel("Password:"); JLabel label3 = new JLabel("Email address:");
These codes create three different labels with the text "Enter your name:"
, "Password:"
, and "Email address:"
, respectively.
Text Fields
Text fields are used to allow users to enter text in a GUI application. To create a text field in Java, you can use the JTextField
class. Here are some examples of different types of text fields.
Main
JTextField textField1 = new JTextField(20); JTextField textField2 = new JPasswordField(20); JTextField textField3 = new JTextField("example@gmail.com", 20);
The first code creates a text field with a width of 20
characters. The second code creates a password field with a width of 20
characters. The third code creates a text field with a default value of "example@gmail.com"
and a width of 20
characters.
You can also create text fields that only accept certain types of inputs, such as numbers or dates. To do this, you can use specialized text fields classes, such as JFormattedTextField
or JDateChooser
.
Main
JFormattedTextField formattedTextField = new JFormattedTextField(NumberFormat.getIntegerInstance()); JDateChooser dateChooser = new JDateChooser();
The first code creates a text field that only accepts integer values. The second code creates a date chooser that allows users to select a date.
Thanks for your feedback!