Java 如何在 Jframe Swing 中居中 JLabel?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19506769/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 17:50:24  来源:igfitidea点击:

how to center JLabel in Jframe Swing?

javaswingjlabelcentering

提问by brain storm

I have this working code for a stop watch in Swing. I want to have the label Time Remaining 300 secondscentered on the second line`. here is my code. enter image description here

我有这个用于 Swing 秒表的工作代码。我想让标签Time Remaining 300 seconds居中在第二行`。这是我的代码。在此处输入图片说明

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;

public class TimerGUI extends JPanel {
    JLabel promptLabel, timerLabel;
    final int count = 30;
    JButton start;
    JButton end;
    Timer timer;

    public TimerGUI() {
        setLayout(new GridLayout(0,2));

        start = new JButton("Start");
        add(start);
        Event e = new Event();
        start.addActionListener(e);

        end = new JButton("End");
        end.setEnabled(false);
        add(end);
        end.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                timer.stop();
                start.setEnabled(true);
                end.setEnabled(false);
                timerLabel.setText("Time Remaining " + count + " seconds");

            }

        });

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

    }

    private class Event implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent e) {
            start.setEnabled(false);
            end.setEnabled(true);
            timerLabel.setText("Time Remaining " + count + " seconds");

            TimeClass tc = new TimeClass(count);
            timer = new Timer(1000, tc);
            timer.start();

        }
    }

    private class TimeClass implements ActionListener {
        int counter;

        public TimeClass(int count) {
            this.counter = count;

        }

        @Override
        public void actionPerformed(ActionEvent e) {
            counter--;
            if (counter <= 5) {
                Toolkit.getDefaultToolkit().beep();
            }

            if (counter >= 1) {
                timerLabel.setText("Time Remaining " + counter + " seconds");
            } else {
                timer.stop();
                timerLabel.setText("game over");
            }

        }
    }

    public static void main(String[] args) {
        JFrame myframe = new JFrame();
        TimerGUI timer = new TimerGUI();
        // myframe.getContentPane().add(content,BorderLayout.CENTER);
        myframe.getContentPane().add(timer, BorderLayout.CENTER);
        myframe.setTitle("Hangman Game");
        myframe.pack();
        myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myframe.setLocationRelativeTo(null);
        myframe.setVisible(true);

    }

}

EDIT: changing to this.

编辑:更改为此。

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

gives different ouput, kindly see the image

给出不同的输出,请看图片

enter image description here

在此处输入图片说明

采纳答案by Hovercraft Full Of Eels

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

更改 JLabel 的水平对齐方式。构造函数可以通过更改以下内容来帮助您执行此操作:

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

还使用自己的布局嵌套您的 JPanel。例如,

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();
         }
      });
   }
}

回答by Fermat's Little Student

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

阅读JLabel 的 JavaDoc。它具有类和所有 API 的描述,包括文本对齐。

回答by kakaday22

you can use this to center it horizontally

你可以用它来水平居中

labelVariable.setHorizontalAlignment(JLabel.CENTER);

回答by Jatin Bansal

You can use the following

您可以使用以下

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

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

50是标签从框架顶部的高度。