Search code examples
javaswingjframejtextfield

Java/Swing - Set title for TextField


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!


Solution

  • 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:

    1. Create a JPanel and set the layout to a vertical BoxLayout
    2. Create and add the JLabel to the panel
    3. Create and and the JTextField to the panel
    4. Add the panel to the frame.

    Read 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.