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);
}
}