Home > OS >  How can I make a JTextArea appear after clicking button
How can I make a JTextArea appear after clicking button

Time:11-06

I'm doing a simple program that display information about specific university in a JTextArea after clicking a JButton.

How can I make the JTextArea appears after clicking the button?

Here's my code:

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();
        });
    }
}

CodePudding user response:

All Swing components have a setVisible method you can use. You start with an invisible component, and make it visible on the button click.

An alternative is to add it to the parent container on a button click (Container#add), but this requires revalidating the layout. As such, the first option is easier.

  • Related