简体   繁体   中英

Why JTextArea is not showing up in this code?

Why Jtextarea is not showing up in this code? I tried to add a Jtextarea in jpanel using gridbaglayout. The frame opens properly but there is no Jtextarea on it. I couldn't identify the problem.Someone helps me please.

    import javax.swing.*;
    import java.awt.*;
    public class ServerTest{
    //object declaration
    JFrame f;
    JPanel p;
    JTextArea ta;
    JTextField tf;
    JButton b1,b2;
    GridBagConstraints gbc;
    //constructor
    public ServerTest(){
        //instantiation
        f=new JFrame("Server");
        p=new JPanel();
        p.setBackground(Color.green);
        ta=new JTextArea("Hello");
        tf=new JTextField();
        b1=new JButton("EMO");
        b2=new JButton("VOICE");
        gbc=new GridBagConstraints();
        //end of instantiation

        //frame task
        f.setLayout(new FlowLayout());
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        p.setLayout(new GridBagLayout());

        gbc.gridx=0;
        gbc.gridy=0;
        gbc.gridwidth=3;
        gbc.gridheight=5;
        p.add(ta,gbc);
        f.add(p);
        f.pack();
        f.setVisible(true);
        //end of frame task

    }

    //Main method
    public static void main(String []args){
        ServerTest st = new ServerTest();
    }
}

The simple answer, there is...

你看见我看到的了吗

Here's proof...

证明

You might have better luck if you make use of the JTextArea(int, int) constructor and use a JScrollPane , for example...

也许更好的主意

public ServerTest() {
    //...
    ta = new JTextArea(10, 20);
    //...
    p.add(new JScrollPane(ta), gbc);
}

You should set some properties of the GridBagLayout to initialize the background grid of the layout:

columnWeights 
columnWidths
rowWeights
rowHeights

Also it is not bad to change the layout of the whole frame from FlowLayout to BorderLayout :

f.setLayout(new BorderLayout());

you change your code like this sample and it will work:

//frame task
f.setLayout(new BorderLayout());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout bagLayout = new GridBagLayout();

bagLayout.columnWeights = new double[]{1.0,1.0,1.0,1.0,1.0};
bagLayout.columnWidths = new int[]{25,25,25,25,25};
bagLayout.rowWeights = new double[]{1.0,1.0,1.0,1.0,1.0};
bagLayout.rowHeights = new int[]{25,25,25,25,25};
p.setLayout(bagLayout);

gbc.gridx=0;
gbc.gridy=0;
gbc.gridwidth=3;
gbc.gridheight=5;
gbc.fill = GridBagConstraints.BOTH;

Also GridBagConstraints#fill property has a significant role on sizing the components when using GridBagLayout .

If you want to see some detailed examples: SWING - GridBagLayout Class

Good Luck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM