I am working on an application and I am stuck in the incipient phase.
I have a JTextField
in a JPanel
in a JFrame
. JTextField
isn't there.
If I use
JPanel p0 = (JPanel) f.getContentPane();
it works. But Not with
JPanel p0 = new JPanel();
f.add(p0);
So the problems are:
- Why is not the field visible? (most important q)
- What's the difference between the 2 aforementioned approaches?
Code:
import java.awt.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
public class Main
{
static Font fontDefault = new Font("arial", Font.PLAIN, 15);
public static void main ( String [ ] args )
{
JFrame f = new JFrame("Liquid");
f.setSize(new Dimension(840, 400));
//f.setIconImage(image);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//JPanel p0 = (JPanel) f.getContentPane();// is it necessary?
JPanel p0 = new JPanel();
p0.setLayout(null);
JPanel p1 = new JPanel();
p1.setLayout(null);
JTextField tfHostName = new JTextField("default text", 20);
tfHostName.setBounds(50, 50, 200, 25);
tfHostName.setFont(fontDefault);
JButton bRequest = new JButton("request");
JButton bReset = new JButton("reset");
JTextArea taTest = new JTextArea("default text", 1, 20);
p0.add(tfHostName);
f.add(p0);
f.add(p1);
p0.add(taTest);
//f.pack();
f.setResizable(false);
f.setVisible(true);
}
}
As a reminder:
It works with JPanel p0 = (JPanel) f.getContentPane();
but why id doesn't with 2nd approach, which I'm more comfortable with? Plus, that way how do I add a second panel and how do I make components in each panel auto-arranged?
Update:
I realized that the code didn't work in the first place probably because I didn't specified any coordinates/position?...