import javax.swing.*; public class MyPanel extends JPanel { public MyPanel() { // Creating a new JPanel and setting its background color to blue setBackground(Color.BLUE); } }
import javax.swing.*; public class MyFrame extends JFrame { public MyFrame() { // Creating a new JFrame and setting its background color to red getContentPane().setBackground(Color.RED); // Set frame properties setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(300, 300); setVisible(true); } public static void main(String[] args) { new MyFrame(); } }In this example, we are creating a new JFrame and setting its background color to red using the JComponent setBackground method. We are setting the content pane's background color instead of frame's background color because JFrame does not provide a setBackground method.