how to center JLabel in Jframe Swing?

我只是一个虾纸丫 提交于 2019-12-01 03:30:23

Change your JLabel's horizontal alignment. The constructor can help you do this by changing:

timerLabel = new JLabel("Time Remaining 300 seconds");

to:

timerLabel = new JLabel("Time Remaining 300 seconds", SwingConstants.CENTER);

Also nest your JPanels each using its own layout. e.g.,

import java.awt.BorderLayout;
import java.awt.GridLayout;

import javax.swing.*;

public class TimerFoo extends JPanel {
   public TimerFoo() {
      JPanel centerPanel = new JPanel(new GridLayout(0, 2));
      centerPanel.add(new JButton("Foo"));
      centerPanel.add(new JButton("Bar"));

      JLabel bottomLabel = new JLabel("Bottom Label", SwingConstants.CENTER);

      int gap = 5;
      setLayout(new BorderLayout(gap, gap));
      setBorder(BorderFactory.createEmptyBorder(gap, gap, gap, gap));
      add(centerPanel, BorderLayout.CENTER);
      add(bottomLabel, BorderLayout.PAGE_END);
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("TimerFoo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new TimerFoo());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

you can use this to center it horizontally

labelVariable.setHorizontalAlignment(JLabel.CENTER);
Jatin Bansal

You can use the following

jLabelvariable.setLocation((this.getWidth()-jLabelvariable.getWidth())/2,50);

Here 50 is the height of label from top of the frame.

Read JavaDoc of JLabel. It has description for the class and all the APIs, including text alignment.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!