import javax.swing.*; import javax.imageio.ImageIO; import java.awt.Color; import java.awt.Font; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.io.File; import java.io.IOException; public class BackgroundImageWithJFrameAndButton implements ActionListener { public static void main(String[] args) { // Create an instance of the 'BackgroundImageWithJFrameAndButton' class new BackgroundImageWithJFrameAndButton(); } // Constructor public BackgroundImageWithJFrameAndButton() { // Create an instance of a JFrame JFrame frame = new JFrame(); // Allow objects to be placed anywhere on the JFrame frame.setLayout(null); // Allow the JFrame to be closed via the "X" frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Set the JFrame size and title frame.setSize(500, 250); frame.setTitle("Demo: JFrame with Background Image and Button"); // Set the JFrame background color; note that this background // color will not be visible if the background image (below) // is visible frame.getContentPane().setBackground(Color.BLACK); // Set the JFrame background image try { frame.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("data_files/space.gif"))))); System.out.println(); } catch (IOException error) { System.out.println("ERROR: " + error.getMessage()); } // Position the JFrame in the center of the screen frame.setLocationRelativeTo(null); // Don't let the JFrame be resized frame.setResizable(false); // Create and set up a JButton JButton button = new JButton("Quit Program"); button.setFont(new Font("Arial", Font.BOLD, 18)); button.setForeground(Color.BLUE); button.setSize(150, 35); button.setLocation(334, 180); button.setFocusable(true); // Allow this button to have the focus button.setVisible(true); // Allow the button to respond to being pressed button.addActionListener(this); // Add the JButton to the JFrame frame.add(button); // Make the JFrame (and everything on it) visible frame.setVisible(true); } public void actionPerformed(ActionEvent e) { // See if the EXIT button was clicked if (e.getActionCommand() == "Quit Program") System.exit(0); } }