Kasun Pradeep
Kasun Pradeep

Reputation: 1

Change JFrame color with button click

I want to change the frame color with a button, without adding any panels.

How to do this?

This is my code:

import javax.swing.*;
import java.awt.*;

public class demo{

public static void main (String [] args ){

JFrame frame = new JFrame("Gui");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(400,400,400,300);
frame.setLayout(null);
frame.setVisible(true);

JButton butt = new JButton("Change Color");
butt.setBounds(50,50,150,30);
frame.add(butt);

}
}

Upvotes: 0

Views: 3477

Answers (2)

Lukas Rotter
Lukas Rotter

Reputation: 4188

Add an ActionListener to the button.

butt.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        frame.getContentPane().setBackground(Color.BLACK);
    }
});

Btw, don't use setBounds() and null-layout, instead take a look at layout managers. You should also call setVisible() after you added all components, not before.

Full code:

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class demo {

    public static void main(String[] args) {

        JFrame frame = new JFrame("Gui");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JButton butt = new JButton("Change Color");
        butt.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                frame.getContentPane().setBackground(Color.BLACK);
            }
        });

        frame.getContentPane().setLayout(new FlowLayout());
        frame.getContentPane().add(butt);

        frame.setSize(500, 500);
        frame.setVisible(true);

    }

}

Upvotes: 2

Sh4d0wsPlyr
Sh4d0wsPlyr

Reputation: 968

First you need to add an ActionListener to this. Otherwise it will no know what to do when you click the button. Below is a link that you will find useful.

https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

From there setting the background color is quite easy. Simply call something similar to this..

if(e.getSource() == myButtonName) {
    frame.getContentPane().setBackground(Color.BLUE);
}

Upvotes: 1

Related Questions