Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set padding at JLabel

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

like image 882
bircastri Avatar asked Oct 16 '15 14:10

bircastri


People also ask

How do you add padding to a swing?

When you need padding inside the JPanel generally you add padding with the layout manager you are using. There are cases that you can just expand the border of the JPanel . Adding padding to the layout manager (In my case, GridLayout) adds padding in between the adjacent panels, but not within an individual panel.

How do you add spacing to a Java Swing?

There are a number of ways in a Swing GUI to provide a separation between components, and white space around components: JToolBar has the methods addSeparator() & addSeparator(Dimension) . JMenu uses a spacing component better suited to menus, available through addSeparator() .


1 Answers

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
like image 84
tec Avatar answered Sep 22 '22 15:09

tec