【发布时间】: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