How to set padding at JLabel

bircastri picture bircastri · Oct 16, 2015 · Viewed 12.1k times · Source

I want to display a Multiline JLabel into JPanel. So I have this code but I'm not able to show the multiline JLabel.

public class NotificationFrame extends JFrame{
    public NotificationFrame(){
        JPanel panelBody = new JPanel();
        panelBody.setBackground(Color.white);
        GridBagConstraints GBC2 = new GridBagConstraints();
        Container CR2 = new Container();
        GridBagLayout GBL2 = new GridBagLayout();
        CR2.setLayout(GBL2);     
        panelBody.add(CR2);

        GBC2 = new GridBagConstraints();
        CR2.add(labelTesto);
        GBC2.gridx=0;
        GBC2.gridy=0;
        GBC2.insets.left = 10;
        GBC2.insets.top=0;
        GBL2.setConstraints(labelTesto,GBC2);
        panelBody.setLayout(new FlowLayout(FlowLayout.CENTER)); 


        add(panelBody,BorderLayout.CENTER);
    }
}

If I change the last line of code in

add(labelTest,BorderLayout.CENTER);

I can show that I want. But it is not correct because I want to set a padding on JLabel

EDIT

I have use this code now:

JPanel panelBody = new JPanel();
panelBody.setBackground(Color.white);
SpringLayout layout = new SpringLayout();
panelBody.setLayout(layout);
panelBody.add(labelTesto);
layout.putConstraint(SpringLayout.NORTH, labelTesto, 15, SpringLayout.NORTH, panelBody);
add(panelBody,BorderLayout.CENTER);

This is the layout:

enter image description here

This is the all test that I should see: "Il 31 Dicembre scadrà l'assistenza, ricorda di rinnovare l'assistenza per ricevere sempre assistenza ed aggiornamenti."

Answer

tec picture tec · Jan 23, 2017

Multiline it's not padding. For achieve multiline text in JLabel or JButton you need to use HTML.

To wrap text (or multiline):

btn.setText("<html><p>Il 31 Dicembre scadrà l'assistenza, ricorda di rinnovare l'assistenza per ricevere sempre assistenza ed aggiornamenti</p></html>");
label.setText("<html>Date:<br></html>"+getDateFromSomeWhere);

To set padding:

    label.setBorder(new EmptyBorder(0,10,0,0));//top,left,bottom,right