简体   繁体   English

我不明白为什么该代码不起作用(JRadioButtons的新手)

[英]I do not understand why this code won't work(new to JRadioButtons)

I am learning JRadioButtons and I do not know why it is working in the tutorial I am watching and not in my code. 我正在学习JRadioButtons ,但不知道为什么它在我正在观看的教程中而不是在我的代码中起作用。 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. 在我的新Java头中,这应该可以完美地工作。 I initialize the buttons, initialize the group. 我初始化按钮,初始化组。 I am getting an error after I click one of the buttons: AWT-EventQueue-0 . 单击以下按钮之一后出现错误: 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. 如果在全局和局部范围内声明相同的变量( JTextArea tb ),它将是一个单独的对象。 Remove the declaration in the local scope from the Screen() constructor so it will work. Screen()构造函数中删除本地作用域中的声明,这样它将起作用。 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. 由于您当前的代码,因此tb仍未在全局范围内初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM