【问题标题】:How can I make a JTextArea appear after clicking button单击按钮后如何使 JTextArea 出现
【发布时间】:2021-12-19 13:11:06
【问题描述】:

我正在做一个简单的程序,在单击 JButton 后在 JTextArea 中显示有关特定大学的信息。

如何让 JTextArea 在点击按钮后出现?

这是我的代码:

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


public class ToolBar extends JFrame {
    JFrame frame=new JFrame();
    JButton uni1=new JButton("Hasheimte University");
    JButton uni2=new JButton("The University of Jordan");
    JButton uni3=new JButton("German Jordanian University");
    JButton exit=new JButton("Close");
    JToolBar tb = new JToolBar();
    JTextArea text = new JTextArea("bla bla bla");
    
    
    public ToolBar(){
        setTitle("Jordanian universities");
        setSize(600,300);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        add(tb);
        tb.add(uni1);
        tb.add(uni2);
        tb.add(uni3);
        tb.add(exit);
        
        tb.setFloatable(false);
        setLayout(new FlowLayout (FlowLayout.CENTER));
        
        uni1.addActionListener(e ->{
            
        });
        
        exit.addActionListener(e -> {
            dispose();
        });
    }
}

【问题讨论】:

  • 有几种方法可以做到这一点,但您当然可以使用text.setVisible(false); 使其不可见,然后将其添加到jframe。要再次显示它,请在按钮事件中使用text.setVisible(true);
  • 最好使用 CardLayout 来交换组件。更好的是——显示 JTextArea,但通过 .seteEnabled(false) 将其禁用,然后在需要时启用它。
  • setEnabled 并不真正意味着是否可见,所以我猜 setVisible 选项更好。交换组件会使它运行起来有点“重”。对于刚起步的人来说也有点困难。不过,这可能是一个很好的后续行动

标签: java swing jbutton actionlistener jtextarea


【解决方案1】:

所有 Swing 组件都有一个可以使用的setVisible 方法。您从一个不可见的组件开始,并使其在按钮单击时可见。

另一种方法是在单击按钮时将其添加到父容器 (Container#add),但这需要重新验证布局。因此,第一个选项更容易。

【讨论】:

    猜你喜欢
    • 2012-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-05
    • 2016-06-25
    • 1970-01-01
    • 2016-09-05
    相关资源
    最近更新 更多