【问题标题】:JLabel Width Not WorkingJLabel 宽度不起作用
【发布时间】:2015-06-01 09:15:46
【问题描述】:

我已将 JLabel 的宽度设置为字符串的宽度,但是当我这样做时,JLabel 会使用 ... 切断中间的字符串,因此不是“问我一个问题!”,它最终成为“问我一个问题......”。这可能是我使用的字体的问题,但我不确定。有什么帮助吗?

这是我的自定义 JLabel 类,名为 BLANKJLabel:

package BLANK.BLANK.menufeatures;

import BLANK.BLANK.main.QnABotJPanel;

import javax.swing.*;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;

public class BLANKJLabel extends JLabel {

    public AffineTransform affineTransform = new AffineTransform();
    public FontRenderContext fontRenderContext = new FontRenderContext(affineTransform, true, true);

    public BLANKJLabel(ImageIcon icon, String text, int x, int y) {
        int stringWidth = (int) (QnABotJPanel.font.getStringBounds(text, fontRenderContext).getWidth());
        int stringHeight = (int) (QnABotJPanel.font.getStringBounds(text, fontRenderContext).getHeight());

        this.setText(text);
        this.setFont(BLANKJPanel.font);
        this.setLocation(x, y);
        this.setIcon(icon);
        this.setSize(stringWidth, stringHeight);
    }

    public BLANKLabel(String text, int x, int y) {
        int stringWidth = (int) (QnABotJPanel.font.getStringBounds(text, fontRenderContext).getWidth());
        int stringHeight = (int) (QnABotJPanel.font.getStringBounds(text, fontRenderContext).getHeight());

        Dimension d = new Dimension(this.getPreferredSize());

        this.setText(text);
        this.setFont(BLANKJLabel.font);
        this.setLocation(x, y);
        this.setSize(d);
    }

}

这是使用它的类,BLANKJPanel:

package BLANK.BLANK.main;

import BLANK.BLANK.menufeatures.BLANKButton;
import BLANK.BLANK.menufeatures.BLANKJLabel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;

public class QnABotJPanel extends JPanel {

    public AffineTransform affineTransform = new AffineTransform();
    public FontRenderContext fontRenderContext = new FontRenderContext(affineTransform, true, true);

    static QnABotButton submitButton;
    static QnABotJLabel askMeAQuestionLabel;

    public static Font font = new Font("Avenir Next", Font.PLAIN, 20);

    String askMeAQuestion = "Ask me a question!";

    int askMeAQuestionWidth = (int)(font.getStringBounds(askMeAQuestion, fontRenderContext).getWidth());
    int askMeAQuestionHeight = (int)(font.getStringBounds(askMeAQuestion, fontRenderContext).getHeight());

    public QnABotJPanel() {
        setLayout(new GroupLayout(this));

        submitButton = new QnABotButton("Submit", "/submit", QnABotWindow.windowWidth / 2 - 100, (QnABotWindow.windowHeight / 4) * 3 - 50);

        askMeAQuestionLabel = new QnABotJLabel(askMeAQuestion, QnABotWindow.windowWidth / 4 - askMeAQuestionWidth / 2, QnABotWindow.windowHeight / 3 - askMeAQuestionHeight / 2);

        this.add(submitButton);
        this.add(askMeAQuestionLabel);

        this.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (QnABotJPanel.submitButton.getActionCommand().equalsIgnoreCase(e.getActionCommand())) {

                }
            }

        });
    }

    public void addActionListener(ActionListener listener) {
        submitButton.addActionListener(listener);
    }

}

【问题讨论】:

  • 为什么要使用 setLocation 和 setSize 却不让布局管理器去做呢?
  • @MadProgrammer 因为 LayoutManager 可能不会做我想做的事。我希望它们在特定的地方,而 LayoutManager 可能不会把它们放在那里。
  • 在设置文本和字体后尝试使用 getPreferredSize,但您可能会遇到可变宽度字体的问题
  • @MadProgrammer 但是我必须设置一个特定的大小......
  • 为什么?你有什么保证任何字体是固定或可变宽度的,Java没有它自己的字体格式,它只是使用系统字体(TFT或其他)。 getPreferredSize 是一个可用于从 Component 扩展的任何组件的方法,因此它也可用于任何 Swing 组件...

标签: java fonts jpanel width jlabel


【解决方案1】:

我给你的第一条建议是避免使用null 布局,像素完美的布局是现代 UI 设计中的一种错觉。影响组件单个尺寸的因素太多,您无法控制。 Swing 旨在与核心的布局管理器一起工作,丢弃这些将导致无穷无尽的问题和问题,您将花费越来越多的时间来尝试纠正。

您可能遇到的下一个问题是尝试执行标签已经能够执行的操作,计算它的首选大小。

如果你在设置文本和字体之后使用JLabel#getPreferredSize,它会告诉你组件的大小应该是什么。这是布局管理器 API 默认执行的操作

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new QnABotJPanel());
                frame.setSize(200, 50);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public static class QnABotJPanel extends JPanel {

//      public AffineTransform affineTransform = new AffineTransform();
//      public FontRenderContext fontRenderContext = new FontRenderContext(affineTransform, true, true);

//      static QnABotButton submitButton;
//      static QnABotJLabel askMeAQuestionLabel;

        public static Font font = new Font("Avenir Next", Font.PLAIN, 20);

//      String askMeAQuestion = "Ask me a question!";
//
//      int askMeAQuestionWidth = (int) (font.getStringBounds(askMeAQuestion, fontRenderContext).getWidth());
//      int askMeAQuestionHeight = (int) (font.getStringBounds(askMeAQuestion, fontRenderContext).getHeight());

        public QnABotJPanel() {
            setLayout(null);

            add(new BLANKJLabel("This is a banana", 0, 0));

//          submitButton = new QnABotButton("Submit", "/submit", QnABotWindow.windowWidth / 2 - 100, (QnABotWindow.windowHeight / 4) * 3 - 50);
//
//          askMeAQuestionLabel = new QnABotJLabel(askMeAQuestion, QnABotWindow.windowWidth / 4 - askMeAQuestionWidth / 2, QnABotWindow.windowHeight / 3 - askMeAQuestionHeight / 2);
//
//          this.add(submitButton);
//          this.add(askMeAQuestionLabel);
//
//          this.addActionListener(new ActionListener() {
//
//              @Override
//              public void actionPerformed(ActionEvent e) {
//                  if (QnABotJPanel.submitButton.getActionCommand().equalsIgnoreCase(e.getActionCommand())) {
//
//                  }
//              }
//
//          });
        }

        public void addActionListener(ActionListener listener) {
//          submitButton.addActionListener(listener);
        }

    }

    public static class BLANKJLabel extends JLabel {

//      public AffineTransform affineTransform = new AffineTransform();
//      public FontRenderContext fontRenderContext = new FontRenderContext(affineTransform, true, true);
        public BLANKJLabel(ImageIcon icon, String text, int x, int y) {
//          int stringWidth = (int) (QnABotJPanel.font.getStringBounds(text, fontRenderContext).getWidth());
//          int stringHeight = (int) (QnABotJPanel.font.getStringBounds(text, fontRenderContext).getHeight());

            this.setText(text);
            this.setFont(QnABotJPanel.font);
            this.setLocation(x, y);
            this.setIcon(icon);
            this.setSize(getPreferredSize());
        }

        public BLANKJLabel(String text, int x, int y) {
//          int stringWidth = (int) (QnABotJPanel.font.getStringBounds(text, fontRenderContext).getWidth());
//          int stringHeight = (int) (QnABotJPanel.font.getStringBounds(text, fontRenderContext).getHeight());

            this.setText(text);
            this.setFont(QnABotJPanel.font);
            this.setLocation(x, y);
            this.setSize(getPreferredSize());
        }

    }
}

并利用布局管理 API...

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new QnABotJPanel());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public static class QnABotJPanel extends JPanel {

//      public AffineTransform affineTransform = new AffineTransform();
//      public FontRenderContext fontRenderContext = new FontRenderContext(affineTransform, true, true);

//      static QnABotButton submitButton;
//      static QnABotJLabel askMeAQuestionLabel;

        public static Font font = new Font("Avenir Next", Font.PLAIN, 20);

//      String askMeAQuestion = "Ask me a question!";
//
//      int askMeAQuestionWidth = (int) (font.getStringBounds(askMeAQuestion, fontRenderContext).getWidth());
//      int askMeAQuestionHeight = (int) (font.getStringBounds(askMeAQuestion, fontRenderContext).getHeight());

        public QnABotJPanel() {
            setLayout(new GridBagLayout());

            add(new BLANKJLabel("This is a banana"));

//          submitButton = new QnABotButton("Submit", "/submit", QnABotWindow.windowWidth / 2 - 100, (QnABotWindow.windowHeight / 4) * 3 - 50);
//
//          askMeAQuestionLabel = new QnABotJLabel(askMeAQuestion, QnABotWindow.windowWidth / 4 - askMeAQuestionWidth / 2, QnABotWindow.windowHeight / 3 - askMeAQuestionHeight / 2);
//
//          this.add(submitButton);
//          this.add(askMeAQuestionLabel);
//
//          this.addActionListener(new ActionListener() {
//
//              @Override
//              public void actionPerformed(ActionEvent e) {
//                  if (QnABotJPanel.submitButton.getActionCommand().equalsIgnoreCase(e.getActionCommand())) {
//
//                  }
//              }
//
//          });
        }

        public void addActionListener(ActionListener listener) {
//          submitButton.addActionListener(listener);
        }

    }

    public static class BLANKJLabel extends JLabel {

//      public AffineTransform affineTransform = new AffineTransform();
//      public FontRenderContext fontRenderContext = new FontRenderContext(affineTransform, true, true);
        public BLANKJLabel(ImageIcon icon, String text) {
//          int stringWidth = (int) (QnABotJPanel.font.getStringBounds(text, fontRenderContext).getWidth());
//          int stringHeight = (int) (QnABotJPanel.font.getStringBounds(text, fontRenderContext).getHeight());

            this.setText(text);
            this.setFont(QnABotJPanel.font);
            this.setIcon(icon);
        }

        public BLANKJLabel(String text) {
//          int stringWidth = (int) (QnABotJPanel.font.getStringBounds(text, fontRenderContext).getWidth());
//          int stringHeight = (int) (QnABotJPanel.font.getStringBounds(text, fontRenderContext).getHeight());

            this.setText(text);
            this.setFont(QnABotJPanel.font);
        }

    }
}

【讨论】:

  • 效果很好!谢谢!虽然,正如你所看到的,我确实使用了GroupLayout,所以我真的不知道你在说什么。
  • 那为什么要通过 x/y 位置呢?为什么要设置大小? GroupLayout 会自动处理它
  • 另外,GroupLayout 很麻烦,最好和表单编辑器一起使用
  • 好吧,如果它被设计成这样就可以了,不是吗?
【解决方案2】:

这是一种操作 JLabel 的方法(在本例中,它应用于 JPopupMenu)

JLabel labelPop = new JLabel("Options de la table", JLabel.CENTER); //  JLabel with centered text
labelPop.setMaximumSize(new Dimension(10000, 0));                   // Determine the width
labelPop.setPreferredSize(new Dimension(0, 25));                    // Determine the height
labelPop.setOpaque(true);                                           // Set transparency 
labelPop.setBackground(new Color(0, 0, 51));                        // Apply the background color
labelPop.setForeground(Color.decode("#FFFFFF"));                    // Apply the text color

【讨论】:

    【解决方案3】:

    通过添加一个常量来增加stringWidth的大小。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-09
      • 2014-11-01
      • 2023-03-29
      • 1970-01-01
      • 2018-03-03
      • 1970-01-01
      • 2012-07-27
      • 2012-10-25
      相关资源
      最近更新 更多