检查是否已选中JRadioButton

时间:2013-07-25 20:56:11

标签: java swing object jradiobutton

我开始使用Java而且我遇到了一个简单的问题,我想知道我的JCheckBox是否被选中。为此我知道我必须使用comboBox.isSelected(),但在我想要使用它的方法中,我无法引用对象JCheckBox。这是代码:

import java.awt.BorderLayout;

public class AgregarPlato extends JDialog {

    private final JPanel contentPanel = new JPanel();

    public static void main(String[] args) {
        try {
            AgregarPlato dialog = new AgregarPlato();
            dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            dialog.setVisible(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public AgregarPlato() {
        setBounds(100, 100, 546, 459);
        getContentPane().setLayout(new BorderLayout());
        contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
        getContentPane().add(contentPanel, BorderLayout.CENTER);
        contentPanel.setLayout(null);

        JRadioButton radio = new JRadioButton("\u00BFDesea llevar Stock?");
        radio.setFont(new Font("Tahoma", Font.PLAIN, 11));
        radio.setBounds(91, 207, 168, 23);

        contentPanel.add(radio);

        {
            JPanel buttonPane = new JPanel();
            buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
            getContentPane().add(buttonPane, BorderLayout.SOUTH);
            {
                JButton aceptarButton = new JButton("Aceptar");
                aceptarButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent arg0) {

                        if (radio.isSelected()) {
                            System.out.println("It doesnt work");
                        }

                    }

                });
                aceptarButton.setActionCommand("OK");
                buttonPane.add(aceptarButton);
                getRootPane().setDefaultButton(aceptarButton);
            }
            {
                JButton cancelarButton = new JButton("Cancelar");
                cancelarButton.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        setVisible(false);
                    }
                });
                cancelarButton.setActionCommand("Cancel");
                buttonPane.add(cancelarButton);
            }
        }
    }
}

2 个答案:

答案 0 :(得分:2)

宣布您的radio变量final或您的班级中的私人会员,它会有效。

final JRadioButton radio代替JRadioButton radio

答案 1 :(得分:1)

您的意思是JRadioButton - 该应用程序不包含JCheckbox

编译器不允许在内部类中访问非final变量。变量radio final

final JRadioButton radio = new JRadioButton("\u00BFDesea llevar Stock?");

此外,Swing旨在使用layout managers。该应用程序仍然具有相对较少的组件,因此过渡到使用它应该很容易。

相关问题