【问题标题】:Modifying JLabel text changes its alignement修改 JLabel 文本会更改其对齐方式
【发布时间】:2016-02-27 11:05:26
【问题描述】:

我正在尝试让对话框显示带有标签的进度条。我已将标签设置为与 JLabel.Center 居中对齐并使用框。

最初,标签显示为居中,这是我正在寻找的。但是,当更改标签的文本时(通过使用代码“creatingQueriesLabel.setText(text)”,标签现在显示为左对齐。

任何帮助将不胜感激!这是我的代码。

    JFrame frame = new JFrame("Creating queries ...");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Box box = Box.createVerticalBox();

    JPanel panel = new JPanel();
    panel.setLayout(null);

    creatingQueriesLabel = new JLabel("Initializing ... ");
    creatingQueriesLabel.setSize(480, 160);
    creatingQueriesLabel.setLocation(10, 10);
    creatingQueriesLabel.setAlignmentX(JLabel.CENTER_ALIGNMENT);

    box.setLocation(0, 10);
    box.setSize(480, 160);
    box.add(creatingQueriesLabel);

    progressBar = new JProgressBar();
    progressBar.setSize(480, 50);
    progressBar.setValue(0);
    progressBar.setStringPainted(true);
    progressBar.setLocation(creatingQueriesLabel.getX(),
            creatingQueriesLabel.getY() + creatingQueriesLabel.getHeight());

    panel.add(progressBar);

    frame.add(box);
    frame.add(panel);

    // Display the window.
    frame.pack();
    frame.setSize(520, 280);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

/**
 * Invoked when task's progress property changes.
 */
public void propertyChange(PropertyChangeEvent evt)
{
    if ("progress" == evt.getPropertyName())
    {
        int progress = (Integer) evt.getNewValue();
        progressBar.setValue(progress);
    }
    if ("currentQueryText" == evt.getPropertyName())
    {
        String text = (String) evt.getNewValue();
        creatingQueriesLabel.setText(text);
    }
}

【问题讨论】:

  • 我故意遗漏了一些代码,因为它没有为这个问题带来任何启示(例如如何调用 propertyChange 以及一切)。 JLabel 上的操作都在这里展示。

标签: java swing alignment jlabel


【解决方案1】:

问题:

  • 您正在使用绝对定位设置大小和位置 - 不要因为这不是 Swing 的工作方式,这将导致 GUI 很难维护和增强,正如您所发现的那样。
  • 在构造 JLabel 时使用 SwingConstants.CENTER int 使其文本居中
  • 将其添加到使用 BorderLayout 的容器中,可能在 BorderLayout.PAGE_START 位置。
  • 不相关的问题——不要这样做:if ("currentQueryText" == evt.getPropertyName()) {。这测试了您不想测试的引用相等性。请改用 equals 方法。
  • 这个 GUI 看起来应该是一个对话窗口,一个显示主父窗口(JFrame 窗口)中未显示的信息的临时窗口,因此它应该显示在 JDialog 中,而不是 JFrame 中。李>

例如:

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

@SuppressWarnings("serial")
public class CreatingSpeciesPanel extends JPanel {
    public static final String INITIALIZING = "Initializing...";
    public static final String DONE = "DONE!";
    private static final int PREF_W = 480;
    private static final int PREF_H = 150;
    private static final int GAP = 20;
    private static final float TITLE_SIZE = 24f;

    private JLabel title = new JLabel(INITIALIZING, SwingConstants.CENTER);
    private JProgressBar progressBar = new JProgressBar();

    public CreatingSpeciesPanel() {
        title.setFont(title.getFont().deriveFont(Font.BOLD, TITLE_SIZE));
        progressBar.setValue(0);
        progressBar.setStringPainted(true);

        JPanel centerPanel = new JPanel(new BorderLayout());
        centerPanel.add(progressBar, BorderLayout.PAGE_END);

        setLayout(new BorderLayout());
        setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
        add(title, BorderLayout.PAGE_START);
        add(centerPanel, BorderLayout.CENTER);

    }

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

    public void setValue(int value) {
        progressBar.setValue(value);
    }

    public void setTitleLabelText(String text) {
        title.setText(text);
    }

    private static void createAndShowGui() {
        final CreatingSpeciesPanel creatingSpeciesPanel = new CreatingSpeciesPanel();
        final JFrame mainFrame = new JFrame("Main Frame");

        JButton createSpeciesBtn = new JButton(new AbstractAction("Create Species") {

            @Override
            public void actionPerformed(ActionEvent e) {
                creatingSpeciesPanel.setTitleLabelText(CreatingSpeciesPanel.INITIALIZING);
                final JDialog dialog = new JDialog(mainFrame, "Creating Species", ModalityType.APPLICATION_MODAL);
                dialog.add(creatingSpeciesPanel);
                dialog.pack();
                dialog.setLocationRelativeTo(mainFrame);

                new Timer(200, new ActionListener() {
                    private int doneCount = 0;
                    private int value = 0;
                    private static final int MAX_DONE_COUNT = 10;

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if (value < 100) {

                            value += (int) Math.random() * 5 + 5;
                            value = Math.min(100, value);

                            creatingSpeciesPanel.setValue(value);
                            if (value == 100) {
                                creatingSpeciesPanel.setTitleLabelText(CreatingSpeciesPanel.DONE);
                            }
                        } else {
                            // let's display the dialog for 2 more seconds
                            doneCount++;
                            if (doneCount >= MAX_DONE_COUNT) {
                                ((Timer) e.getSource()).stop();
                                dialog.setVisible(false);
                            }
                        }
                    }
                }).start();

                dialog.setVisible(true);
            }
        });

        JPanel panel = new JPanel();
        panel.add(createSpeciesBtn);
        panel.setPreferredSize(new Dimension(500, 400));

        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.getContentPane().add(panel);
        mainFrame.pack();
        mainFrame.setLocationRelativeTo(null);
        mainFrame.setVisible(true);
    }

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

【讨论】:

  • 感谢您非常彻底的回答!效果很好!我明白为什么设置位置很难维护,但我不应该设置尺寸吗?
  • 如果我可以再问一次,似乎从 JFrame 更改为 JDialog 会破坏我的代码的功能。显示框架后,我有以下几行:task = new Task(); task.addPropertyChangeListener(this);任务.执行();但是,该对话框似乎不再拾取属性更改。
  • @BenoitGoderre:如果您使用模态 JDialog 或 JOptionPane,所有需要在对话框可见时运行的代码都必须在 之前在 JDialog 上调用 setVisible(true) .注意我上面是怎么做的。对setvisible(true) 的调用是最后完成的。
猜你喜欢
  • 2018-01-04
  • 1970-01-01
  • 2018-09-03
  • 2016-10-23
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 2023-03-24
  • 2016-05-28
相关资源
最近更新 更多