使用JRadioButtons和JButton同时使用getSource()

时间:2014-04-05 20:29:10

标签: java arrays swing jbutton jradiobutton

我是Java GUI的新手。我有项目要求我使用它。我基本上创建一个4x4网格(已完成),用户只需单击方块(JButton)即可在网格上的任何位置输入数字(1-4)。我有4个标有1-4的单选按钮。我想知道是否有办法,所以当我填充其中一个单选按钮时,我可以点击网格上的任意位置,文本将被设置为该单选按钮的文本。我的构造函数工作正常。我在代码中遇到了actionPerformed方法的问题...

public class Sym4GUI extends JFrame
{
    private JButton [][] buttons = new JButton [4][4];
private JRadioButton [] RButtons = new JRadioButton [4];
private JPanel pane1;
private JPanel pane2;
private ButtonHandler bh;
private Sym4 sym;
public Sym4GUI()
{
    super ("Welcome to Sym4.");
    Container c = getContentPane();

    sym = new Sym4();

    pane1 = new JPanel();
    pane2 = new JPanel();

    //c.setLayout(new FlowLayout());
    pane1.setLayout(new FlowLayout());
    pane2.setLayout(new GridLayout(4,4));

    bh = new ButtonHandler();

    for (int i = 0; i < buttons.length; i++)
        for (int j = 0; j < buttons[i].length; j++)
        {
            buttons[i][j] = new JButton( "" );
            pane2.add(buttons[i][j]);
            buttons[i][j].addActionListener(bh);
        }

    ButtonGroup btngrp = new ButtonGroup();
    for (int i = 0; i < RButtons.length; i++)
    {
        RButtons[i] = new JRadioButton(i+1 + "");
        btngrp.add(RButtons[i]);
        pane1.add(RButtons[i]);
        RButtons[i].addActionListener(bh);
    }

    c.add(pane1, BorderLayout.NORTH);
    c.add(pane2, BorderLayout.CENTER);

    setSize(500, 500);
    setVisible(true);

    //JOptionPane.showMessageDialog(null, "Click an open space to place chosen number there...");
}

private class ButtonHandler implements ActionListener
{
    public void actionPerformed(ActionEvent ae)
    {

这就是我想知道如何填充单选按钮,然后单击网格上的任意位置以将网格方形文本设置为填充的单选按钮文本。

        for (int i = 0; i < RButtons.length; i++)
            if (ae.getSource() == RButtons[i])
            {
                for (int k = 0; k < buttons.length; k++)
                    for (int j = 0; j < buttons[k].length; j++) 
                        if (ae.getSource() == buttons[k][j])
                            buttons[k][j].setText(RButtons[i].getText());
            }
    }
}

public static void main (String [] args)
{
    Sym4GUI s1 = new Sym4GUI();
    s1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

}

如果您需要更多说明,请与我们联系。

0 个答案:

没有答案