I could not find any class to set a title for TextField. Therefore, I decided to make one. My question is really simple.
Do I really need to include JFrame in my class or maybe there is a different way to accomplish this problem.
Here is my GUI class.
public GUI() {
JFrame f = new JFrame("MyLibrary");
JTextField tf = new JTextField();
tf.setBounds(50, 50, 400, 30);
tf.setFont(new Font("Arial", Font.BOLD, 16));
FieldTitle ft = new FieldTitle(f, tf, "Book title");
f.add(tf);
f.setSize(1280, 720);
f.setLocationRelativeTo(null);
f.setLayout(null);
f.setVisible(true);
}
And here is my FieldTitle class.
public FieldTitle(JFrame f, Component c, String title) {
JLabel l = new JLabel(title);
l.setBounds(c.getBounds().x, c.getBounds().y - 20, c.getWidth(), 20);
f.add(l);
}
Thank you for your time and effort. Have a great day!
Don't use a null layout. Don't use setBounds().
Swing was designed to be used with layout managers. You can easily use a JPanel
with a BoxLayout
:
JPanel
and set the layout to a vertical BoxLayoutJLabel
to the panelJTextField
to the panelRead the Swing tutorial on Layout Managers for more information. You will find a working example that shows how to create a frame with a panel using a BoxLayout.