JLabel的变量不会居中?

时间:2015-08-19 10:34:59

标签: java swing jlabel

我目前正在使用Absolute布局,我希望将一个String变量放置到面板(此框架类似于弹出对话框)并进行水平对齐。这是我的代码片段。

JLabel label = new JLabel(loggedInAs);
label.setBounds(10, 61, 314, 23);
label.setHorizontalAlignment(SwingConstants.CENTER);
contentPane.add(label);

当我运行此文本时,文本似乎从右侧稍微开始,但是如果我在标签上输入预设文本,例如

JLabel label = new JLabel("Hello");

它会居中。无论如何我能解决这个问题吗?

(我也使用了miglayout,但是从我的主JFrame运行它时结果完全不同)

一个例子:

enter image description here

Here is an example of what I mean by it being slightly to the right

1 个答案:

答案 0 :(得分:4)

我认为您的问题是使用绝对布局,因为您使用硬编码的数字来放置JLabel。标签文本本身就很好,但如果在标签周围放置边框,您可能会看到标签本身而不是文本向右倾斜。最简单的解决方案是让布局经理为您解决问题。例如,下面的代码创建了一个成功登录的对话框,该对话框使用布局管理器的组合来实现您在图像中尝试执行的操作:

enter image description here

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class LoginPanelEg extends JPanel {
    private JTextField nameField = new JTextField(20);
    private Action LoginAction = new LoginAction("Login");

    public LoginPanelEg() {
        nameField.setAction(LoginAction);
        add(new JLabel("Login Name:"));
        add(nameField);
        add(new JButton(LoginAction));
    }

    private class LoginAction extends AbstractAction {
        public LoginAction(String name) {
            super(name);
            int mnemonic = (int) name.charAt(0);
            putValue(MNEMONIC_KEY, mnemonic); // alt-key comb
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            LoginPanel loginPanel = new LoginPanel(nameField.getText());

            Window win = SwingUtilities.getWindowAncestor(LoginPanelEg.this);
            JDialog dialog = new JDialog(win, "Successfully Logged In", ModalityType.APPLICATION_MODAL);
            dialog.add(loginPanel);
            dialog.pack();
            dialog.setLocationRelativeTo(null);
            dialog.setVisible(true);
        }
    }

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

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

@SuppressWarnings("serial")
class LoginPanel extends JPanel {
    private static final int PREF_W = 350;
    private static final int PREF_H = 200;
    private static final String SUCCESSFULLY_LOGGED = "Successfully logged in as:";
    private static final int GAP = 20;
    private static final Font PROMPT_FONT = new Font(Font.SANS_SERIF, Font.PLAIN, 14);
    private static final Font NAME_FONT = new Font(Font.SANS_SERIF, Font.BOLD, 12);
    private JLabel successfullyLoggedLabel = new JLabel(SUCCESSFULLY_LOGGED, SwingConstants.CENTER);
    private JLabel nameLabel = new JLabel("", SwingConstants.CENTER);

    public LoginPanel() {
        successfullyLoggedLabel.setFont(PROMPT_FONT);
        nameLabel.setFont(NAME_FONT);

        JPanel innerPanel = new JPanel(new GridBagLayout());
        innerPanel.add(successfullyLoggedLabel, createGbc(0, 0));
        innerPanel.add(nameLabel, createGbc(0, 1));

        JPanel btnPanel = new JPanel();
        btnPanel.add(new JButton(new CloseAction("Close")));

        setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
        setLayout(new BorderLayout());
        add(innerPanel, BorderLayout.CENTER);
        add(btnPanel, BorderLayout.PAGE_END);
    }

    LoginPanel(String name) {
        this();
        nameLabel.setText(name);
    }

    public void setName(String name) {
        nameLabel.setText(name);
    }

    private GridBagConstraints createGbc(int x, int y) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = x;
        gbc.gridy = y;
        return gbc;
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }

    private class CloseAction extends AbstractAction {
        public CloseAction(String name) {
            super(name);
            int mnemonic = (int) name.charAt(0);
            putValue(MNEMONIC_KEY, mnemonic); // alt-key comb
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            Component component = (Component) e.getSource();
            if (component == null) {
                return;
            }
            Window win = SwingUtilities.getWindowAncestor(component);
            if (win == null) {
                return;
            }
            win.dispose();
        }
    }
}