Add Clickable Buttons
Learn to create clickable buttons with actions.
We'll cover the following
Buttons
Buttons are components that, when clicked, cause an event for which the program can perform an action. Adding a clickable button is the easiest way to add event-driven programming to a program.
Creating a button
Guess My Color will need two red buttons, two green buttons, and two blue buttons.
- In
initGUI()
, create aJButton
object calledmoreRedButton
, with “+” as the text. (Hint: creating aJButton
with text is very similar to creating aJLabel
with text.) - Set the color of
moreRedButton
to red. Use JButton’ssetBackground()
method. - Add
moreRedButton
tobuttonPanel
. Use JPanel’sadd()
method. Because you are adding to aJPanel
withFlowLayout
, you only need to use the component parameter value. - Create a similar
JButton
object calledlessRedButton
, with “-” as the button’s text. Then set the button color to red, and add the button tobuttonPanel
. - Create similar button objects called
moreGreenButton
,lessGreenButton
,moreBlueButton
, andlessBlueButton
, set appropriate text and color, and add them tobuttonPanel
.
...
private void initGUI() {
...
add(buttonPanel,BorderLayout.PAGE_END);
JButton moreRedButton = new JButton("+");
moreRedButton.setBackground(Color.RED);
buttonPanel.add(______________);
JButton lessRedButton = new JButton(______);
lessRedButton.setBackground(_______);
buttonPanel.add(____________);
__________ moreGreenButton = _______________;
moreGreenButton._________________________;
buttonPanel.______________________;
__________ lessGreenButton = _______________;
lessGreenButton._________________________;
buttonPanel.______________________;
__________ moreBlueButton = _______________;
moreBlueButton._________________________;
buttonPanel.______________________;
__________ lessBlueButton = _______________;
lessGreenButton._________________________;
buttonPanel.______________________;
}
...
Get hands-on with 1200+ tech skills courses.