import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.*; public class Label extends JPanel { // Opens class Label // Variable to use for label JLabel text; // Class constructor where the label // is created. public Label() { // Opens constructor for Label objects // Uncomment the line below if you want // the panel itself to be white as well. // This line of code sends the method // message to the super class, which is // JPanel. // super.setBackground(Color.white); // Creates the label with a text String // and centers it. text = new JLabel( "Label displaying red text " + "with a white background.", JLabel.CENTER); // Sets the labels background // color to white. text.setBackground(Color.white); // Sets the foreground color, in this // case the text, to the color red. text.setForeground(Color.red); // Make certain the label object is // opaque. If you don't call this // method, the background color white // won't show, as it will be // transparent. text.setOpaque(true); // Adds the label to the panel. add(text); } // Closes constructor public static void main(String[] args) { // Opens main method // Create a window using JFrame JFrame frame = new JFrame("Label Demonstration"); // Code to close down the app cleanly. frame.addWindowListener(new WindowAdapter() { // Opens addWindowListener method public void windowClosing(WindowEvent e) { // Opens windowClosing method System.exit(0); } // Closes windowClosing method }); // Closes addWindowListener // method. frame.setContentPane(new Label()); frame.pack(); frame.setVisible(true); } // Closes main method } // Closes class