Aire
Aire

Reputation: 127

Can't add JTextfield to JPanel

I've been doing some GUI stuff to practice for finals and I think I've gotten the basics down. However, every time I try to add a JTextField to my JPanel, my JButton gets erased and the entire interface disappears. Ultimately, I wanted the text area to change when I clicked the button but I can't even see the text area. I know I probably made a really novice mistake so don't kill me please. The code below doesn't work- however once I strip off the JTextField it runs fine.

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.JTextField;

public class test5 {

    private JFrame f;
    private JPanel p;
    private JButton b1;
    private JTextField jt; 

    public test5 () {
        gui();
    }
    public void gui () {
        f = new JFrame(); 
        f.setVisible(true);
        f.setSize(600,400);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

        jt = new JTextField(20);
        jt.setEditable(false);

        p = new JPanel(); 
        p.setBackground(Color.YELLOW);
        b1 = new JButton("TEST"); 
        b1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null, "Hey, hey, hey!");
                jt.setText("Hello");
            }
        });

        p.add(b1);
        p.add(jt);

        f.add(p, BorderLayout.SOUTH);
    }
    public static void main (String args[]) {
        test5 test = new test5(); 
    }
}

Upvotes: 0

Views: 867

Answers (1)

camickr
camickr

Reputation: 324108

You should add all components to the frame BEFORE you make the frame visible. Try the following:

f.add(p, BorderLayout.SOUTH);
f.pack();
f.setVisible(true);

Upvotes: 4

Related Questions