Add Clickable Buttons

Learn to create clickable buttons with actions.

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.

  1. In initGUI(), create a JButton object called moreRedButton, with “+” as the text. (Hint: creating a JButton with text is very similar to creating a JLabel with text.)
  2. Set the color of moreRedButton to red. Use JButton’s setBackground() method.
  3. Add moreRedButton to buttonPanel. Use JPanel’s add() method. Because you are adding to a JPanel with FlowLayout, you only need to use the component parameter value.
  4. Create a similar JButton object called lessRedButton, with “-” as the button’s text. Then set the button color to red, and add the button to buttonPanel.
  5. Create similar button objects called moreGreenButton, lessGreenButton, moreBlueButton, and lessBlueButton, set appropriate text and color, and add them to buttonPanel.
...
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.