【问题标题】:Show JLabel on JButton click在 JButton 点击​​时显示 JLabel
【发布时间】:2013-07-09 20:51:09
【问题描述】:

我想在我的节目JButton 被点击时看到Jlabel,但它不起作用!

public class d5 extends JFrame implements ActionListener {

    JButton showButton;
    static JLabel[] lbl;
    JPanel panel;

    public d5() {

        showButton = new JButton("Show");
        showButton.addActionListener(this);
        add(showButton, BorderLayout.PAGE_START);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 500);
        setLocation(300, 30);
        setVisible(true);
    }

    public JPanel mypanel() {
        panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        lbl = recordsLabel();
        for (JLabel jLabel : lbl) {
            panel.add(jLabel);
        }
        return panel;
    }

    public static void main(String[] args) {
        new d5();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == showButton) {
            add(mypanel(), BorderLayout.PAGE_START);
            setVisible(true);
            System.out.println("show button clicked");
        }
    }

    public JLabel[] recordsLabel() {
        ArrayList<String> lableList = new ArrayList<>();
        lableList.add("one");
        lableList.add("two");
        lableList.add("three");
        Object[] arrayResultRow = lableList.toArray();

        int rows = 3;

        lbl = new JLabel[rows];
        for (int i = 0; i < rows; i++) {
            lbl[i] = new JLabel(arrayResultRow[i].toString());
        }
        return lbl;
    }
}

【问题讨论】:

  • 你期待什么?你得到什么?错误是什么?它在哪里?
  • 在任何给定时间只能将一个组件添加到任何给定位置,要么观察你的代码,要么在同一位置添加两个东西add(showButton, BorderLayout.PAGE_START); 和你的actionPerformed() 方法add(mypanel(), BorderLayout.PAGE_START);
  • @MarounMaroun 问题已解决,谢谢...
  • 问题出在BorderLayout.PAGE_START 部分,我应该在另一个BorderLayout 部分定义另一个组件,但我在BorderLayout.PAGE_START 模式下定义了其中两个!

标签: java swing jbutton jlabel


【解决方案1】:

作为@nicecow 评论,您已经在与面板相同的位置add(showButton, BorderLayout.PAGE_START);。您只能在同一位置添加一个组件。

调用 validate 也不错。

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == showButton) {
        add(mypanel(), BorderLayout.PAGE_START); // set another position or remove previous component here
        validate(); 
        System.out.println("show button clicked");

    }
}

顺便说一句,我不建议在JFrame 类中实现ActionListener,你也不需要扩展JFrame

public class D5 { 

private JFrame frame;

.
. // is some part in constrcutor
.
  showButton.addActionListener(new ActionListener(){
        @Override 
         public void actionPerformed(ActionEvent evt){
              frame.add(mypanel(),BorderLayout.PAGE_START);
              frame.validate();
         }
  })
}

【讨论】:

    猜你喜欢
    • 2021-07-26
    • 2021-07-29
    • 2013-01-07
    • 1970-01-01
    • 2016-06-09
    • 1970-01-01
    • 2021-02-11
    • 2013-01-20
    • 1970-01-01
    相关资源
    最近更新 更多