There is no need for your
Journal7A class to subclass
JFrame
. Instead, you can extends your class to
JPanel
, and create frame object in your main.
public class Journal7A extends JPanel implements ActionListener {
JPanel content = new JPanel();
JButton btnGreen = new JButton("Green");
JButton btnBlue = new JButton("Blue");
JButton btnRed = new JButton("Red");
public Journal7A() {
content.setLayout(new FlowLayout());
content.add(btnBlue, BorderLayout.SOUTH);
content.add(btnGreen, BorderLayout.SOUTH);
content.add(btnRed, BorderLayout.SOUTH);
btnBlue.addActionListener(this);
btnGreen.addActionListener(this);
btnRed.addActionListener(this);
add(content);
}
@Override
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton) e.getSource();
if (btn == btnBlue) {
content.setBackground(Color.BLUE);
} else {
content.setBackground(Color.GREEN);
}
content.setBackground(Color.RED);
}
public static void main(String[] args) {
Journal7A gui = new Journal7A();
Frame frame = new JFrame();
frame.add(gui);
frame.pack();
frame.setSize(300, 300);
frame.setTitle("First GUI App");
frame.setVisible(true);
}
}
If you like to use your own code , add
add(content);
after line
btnRed.addActionListener(this);