How can we set the background color to a JPanel in Java?

AWTJavaObject Oriented ProgrammingProgrammingSwing

A JPanel is a container and it is an invisible component in Java. The FlowLayout is a default layout for a JPanel. We can add most of the components like buttons, text fields, labels, table, list, tree and etc. to a JPanel. We can set a background color to JPanel by using the setBackground() method.

Example

import java.awt.*
import javax.swing.*;
public class JPanelBackgroundColorTest extends JFrame {
   private JPanel panel;
   public JPanelBackgroundColorTest() {
      setTitle("JPanelBackgroundColor Test");
      panel = new JPanel();
      panel.add(new JLabel("Welcome to Tutorials Point"));
      panel.setBackground(Color.green);
      add(panel, BorderLayout.CENTER);
      setSize(375, 250);
      setLocationRelativeTo(null);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
   }
   public static void main(String args[]) {
      new JPanelBackgroundColorTest();
   }
}

Output

raja
Published on 16-Jul-2019 15:14:01
Advertisements