I am learning JRadioButtons
and I do not know why it is working in the tutorial I am watching and not in my code. Could someone please take a look at it?
Main Class:
import java.awt.*;
import javax.swing.*;
public class Calculator extends JPanel{
private static final long serialVersionUID = 1L;
public static void main(String[] args){
Screen screen = new Screen();
screen.setVisible(true);
}
}
Here is the Screen Class:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextArea;
public class Screen extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
JRadioButton b1, b2;
ButtonGroup group;
JTextArea tb;
public Screen(){
super("First GUI");
setSize(600,600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
JPanel p1 = new JPanel();
JTextArea tb = new JTextArea("Text Area");
group = new ButtonGroup();
group.add(b1);
group.add(b2);
b1 = new JRadioButton("Hello");
b1.setActionCommand("HELLO!");
b1.addActionListener(this);
b2 = new JRadioButton("Goodbye");
b2.setActionCommand("Goodbye! =)");
b2.addActionListener(this);
p1.add(b1);
p1.add(b2);
p1.add(tb);
add(p1);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
tb.setText(e.getActionCommand());
}
}
In my new Java head this should work perfectly. I initialize the buttons, initialize the group. I am getting an error after I click one of the buttons: AWT-EventQueue-0
. I do not know what that means so I do not know how to fix this issue.
You have declared twice the same variable. If you declare the same variable (JTextArea tb
) in the global and local scope, it will be a separate object. Remove the declaration in the local scope from the Screen()
constructor so it will work.
Try this
tb = new JTextArea("Text Area");
instead of
JTextArea tb = new JTextArea("Text Area");
Because of your current code, tb
is still not initialized in the global scope.