Java Swing GUI

How to Change the Background Color of a JButton

In this tutorial, we are going to see how to change the background color of a JButton, using the method setBackground() of JButton class.


 

Java Program to Change the Background Color of a JButton:
import javax.swing.*;
import java.awt.*;

public class JButtonExample
{  
  public static void main(String[] args) 
  {
    //create a frame
    JFrame frame = new JFrame("JButton Example");
    //create button
    JButton btn = new JButton("Click here");
    //set button position
    btn.setBounds(70,80,100,30);
    //change the background color of JButton
    btn.setBackground(Color.RED);
    //add button to frame
    frame.add(btn);
    frame.setSize(250,250);
    frame.setLayout(null);
    frame.setVisible(true);  
  }
}

Output:

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *