write a string on a jpanel centered

75,084

Solution 1

You could add the text as a JLabel component and change its font size.

public static void main(String[] args) {
    NewJFrame1 frame = new NewJFrame1();
    frame.setLayout(new GridBagLayout());
    JPanel panel = new JPanel();
    JLabel jlabel = new JLabel("This is a label");
    jlabel.setFont(new Font("Verdana",1,20));
    panel.add(jlabel);
    panel.setBorder(new LineBorder(Color.BLACK)); // make it easy to see
    frame.add(panel, new GridBagConstraints());
    frame.setSize(400, 400);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(NewJFrame1.EXIT_ON_CLOSE);
    frame.setVisible(true);
}

The code will run and look like this : GUI

see also Java layout manager vertical center for more info

Solution 2

JLabel supports HTML 3.2 formating, so you can use header tags if you don't want to mess with fonts.

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;


public class HtmlHeadersSample extends JFrame {

    public HtmlHeadersSample() {
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setSize(300,200);
    setLocation(100, 100);
    JLabel label1 = new JLabel();
    label1.setText("simple text");
    label1.setBounds(0, 0, 200, 50);
    JLabel label2 = new JLabel();
    label2.setText("<html><h1>header1 text</h1></html>");
    label2.setBounds(0, 20, 200, 50);
    JLabel label3 = new JLabel();
    label3.setText("<html><h2>header2 text</h2></html>");
    label3.setBounds(0, 40, 200, 50);
    JLabel label4 = new JLabel();
    label4.setText("<html><h3>header3 text</h3></html>");
    label4.setBounds(0, 60, 200, 50);

    add(label1);
    add(label2);
    add(label3);
    add(label4);

    setVisible(true);
    }

    public static void main(String[] args) {
        new HtmlHeadersSample();

    }

}

Here's how it looks like:

Here's how it looks like

Solution 3

Just set the size of your font

    JLabel bigLabel = new JLabel("Bigger text");
    bigLabel.setFont(new Font("Arial", 0, 30));
Share:
75,084
Mazzy
Author by

Mazzy

Updated on June 15, 2020

Comments

  • Mazzy
    Mazzy almost 4 years

    I would write on a JPanel a String much bigger respect than other element.which could be the way to paint a string in terms of simply?There is a method to do this?

  • trashgod
    trashgod almost 12 years
    The default horizontalAlignment is LEADING, which may work with default FlowLayout. Also consider specifying the font by family name, e.g. Font.SANS_SERIF.
  • trashgod
    trashgod almost 12 years
    This relies (fortuitously) on the default properties of new GridBagConstraints(). How would this work with other components? Other layouts?