JButton不会展示组件

时间:2015-03-12 00:02:10

标签: java swing button

我想创建一个简单的框架,如果我点击一个按钮就会显示一个文本字段,如果我点击另一个按钮就显示一个JLabel,但它不起作用,我不知道为什么?

我尝试将变量设置为public但结果是一样的,我也在按钮命令中尝试了另一个命令,它就像showMessageDialog一样,所以我很困惑为什么它不能工作

import java.awt.*;
import javax.swing.*;


public class CheckBoxFrame extends JFrame
{
    private JTextField textField1;
    private JLabel label1;
    private JButton txt;
    private JButton label;
    public CheckBoxFrame()
    {

        super ("JCheckBox Test" );
        textField1= new JTextField ("Text Field 1", 20 );
        textField1.setFont ( new Font ("Serif", Font.PLAIN,14));
        add(textField1);
        textField1.setVisible(false);

        label1 = new JLabel("Label1", JLabel.CENTER);
        add(label1);
        label1.setVisible(false);

        txt = new JButton ("Text Field");
        ButtonHandler b1 = new ButtonHandler();
        txt.addActionListener(b1);
        add(txt);

        label = new JButton ("label ");
        add(label);

        setLayout( new FlowLayout() );
        setVisible(true);
        setSize(400,400);

    }


    private class ButtonHandler implements ActionListener
    {
        public void actionPerformed   (ActionEvent a)
        {
            if (a.getSource() == txt)
            {
                label1.setVisible(false);
                textField1.setVisible(true);

            }

            if (a.getSource() == label)
            {
                label1.setVisible(true);
                textField1.setVisible(false);

            }
        }
    }



}

2 个答案:

答案 0 :(得分:1)

这里有两件事 1.您尚未为标签按钮添加动作侦听器。 2.设置可见性后,尝试调用JFrame的repaint()。由于您使用的是单独的操作处理程序类,因此可能必须通过构造函数或setter方法将JFrame实例传递给操作处理程序。

始终建议将控件放在JPanel上而不是直接放在JFrame上

答案 1 :(得分:1)

请务必将ButtonHandler ActionListener添加到label ...

    label = new JButton("label ");
    add(label);
    label.addActionListener(b1);

revalidate添加到ButtonHandler的末尾(或修改容器的位置)以强制布局管理器更新布局。您可能还需要使用repaint

private class ButtonHandler implements ActionListener {

    public void actionPerformed(ActionEvent a) {
        if (a.getSource() == txt) {
            label1.setVisible(false);
            textField1.setVisible(true);

        }

        if (a.getSource() == label) {
            label1.setVisible(true);
            textField1.setVisible(false);
        }
        revalidate();
    }
}
相关问题