Adding background to frame
I couldnt add background color to frame although there is no errors showing.
hope there would be someone who can guide me as soon as possible:(
And the name of the class is a malay word but it means color
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Warna extends JFrame implements ActionListener {
private JButton b1;
Warna() {
//super(str);
setSize(310, 300);
setVisible(true);
setLayout(new FlowLayout());
//Label lname = new Label("MyFrame");
//JButton
b1 = new JButton("RED");
add(b1);
b1.addActionListener(this);
//ButtonHandler bh = new ButtonHandler()
}
public void actionPerformed(ActionEvent e) {
String a = e.getActionCommand();
Color c1 = getBackground();
if (a.equals("red")) {
c1 = Color.RED;
}
setBackground(c1);
repaint();
}
public static void main(String[] args) {
Warna w = new Warna();
}
}
Re: Adding background to frame
When posting code, make sure you use highlight tags to preserve formatting.
Which part of this isn't working? You're doing a few different things here: does the actionPerformed() method trigger? Does the code enter that if statement? Best to create an SSCCE and avoid the uncertainty by just setting the background color outright.
By the way, there is no reason to extend JFrame here. Best to prefer composition over inheritance.
Re: Adding background to frame
Code :
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Warna extends JFrame implements ActionListener {
private JButton b1;
Warna() {
//super(str);
setSize(310, 300);
setVisible(true);
setLayout(new FlowLayout());
//Label lname = new Label("MyFrame");
//JButton
b1 = new JButton("RED");
add(b1);
b1.addActionListener(this);
//ButtonHandler bh = new ButtonHandler()
}
public void actionPerformed(ActionEvent e) {
String a = e.getActionCommand();
System.out.println(a);
Color c1 = getBackground();
if (a.equals("RED")) {/* red != RED */
c1 = Color.RED;
}
this.getContentPane().setBackground(c1);/* I think U must select the contentpane before setting the background Color*/
repaint();
}
public static void main(String[] args) {
Warna w = new Warna();
}
}
Now it’s ok;)