java 在java中圆角JLabel的最简单代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25796572/
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-11-02 08:42:50  来源:igfitidea点击:

Simplest Code to round corners of JLabel in java

javaswinggraphicsjlabelrounded-corners

提问by Airy

I have many JLabel's and want smooth around corners on them. How can I make this? I already searched on SO but I didn't find any answer.

我有很多JLabel并且希望它们的拐角处平滑。我怎样才能做到这一点?我已经在 SO 上搜索过,但没有找到任何答案。

Could someone help me with a simple and exact code for making round corners for JLabel's?

有人可以用简单而准确的代码帮助我为JLabel's制作圆角吗?

Other questions are asking some extra details like border and others but I want just exact and simplest code for making round corners for JLabel's.

其他问题正在询问一些额外的细节,例如边框等,但我只想要精确和最简单的代码来为JLabel's制作圆角。

回答by MadProgrammer

Seriously, the easiest solution would be to paint a RoundRectangle2Daround the JLabel...

说真的,最简单的解决方案是在RoundRectangle2D周围画一个JLabel...

Now, you could do this within the label's paintComponentor paintBordermethods, but why would you bother, when you could just make your own border which did the job in a reusable manner, for example...

现在,您可以在标签paintComponentpaintBorder方法中执行此操作,但是当您可以制作自己的边框以可重用的方式完成工作时,您为什么还要麻烦,例如......

RoundedBorder

圆形边框

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.geom.RoundRectangle2D;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.AbstractBorder;

public class TestRoundedBorder {

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

    public TestRoundedBorder() {
        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 TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setBackground(Color.RED);
            setLayout(new GridBagLayout());
            JLabel label = new JLabel("Test");
            label.setBorder(new RoundedBorder(Color.BLACK, 20));
            add(label);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }

    public class RoundedBorder extends AbstractBorder {

        private final Color color;
        private final int gap;

        public RoundedBorder(Color c, int g) {
            color = c;
            gap = g;
        }

        @Override
        public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setColor(color);
            g2d.draw(new RoundRectangle2D.Double(x, y, width - 1, height - 1, gap, gap));
            g2d.dispose();
        }

        @Override
        public Insets getBorderInsets(Component c) {
            return (getBorderInsets(c, new Insets(gap, gap, gap, gap)));
        }

        @Override
        public Insets getBorderInsets(Component c, Insets insets) {
            insets.left = insets.top = insets.right = insets.bottom = gap / 2;
            return insets;
        }

        @Override
        public boolean isBorderOpaque() {
            return false;
        }
    }

}

Now, if you want "smooth" edges, you're going to have to supply RenderingHintsto the Graphicscontext, for example...

现在,如果你想“平稳”的边缘,你将必须提供RenderingHintsGraphics背景下,例如...

Smoothed Edges

平滑边缘

public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
    Graphics2D g2d = (Graphics2D) g.create();
    g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
    g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
    g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
    g2d.setColor(color);
    g2d.draw(new RoundRectangle2D.Double(x + 1, y + 1, width - 2, height - 2, gap, gap));
    g2d.dispose();
}

回答by Santiago Benoit

You cannot round corners on the actual JLabelarea; they are always rectangular. However, a simple alternative is to set the ImageIconof the JLabelto an image with rounded edges and not use a border. To set an ImageIcon:

您不能在实际JLabel区域上圆角;它们总是矩形的。然而,一个简单的办法是设置ImageIconJLabel与圆形边缘的图像,而不是使用边框。设置一个ImageIcon

yourLabel.setIcon(new ImageIcon(getClass().getResource("/path/to/your/image.png"));
// Note: Relative path, starts from root of project

Your image should have the dimensions of your JLabel. Note that this will throw a NullPointerExceptionif the image is not found. Make sure you get the right path!

您的图像应该具有您的JLabel. 请注意,NullPointerException如果找不到图像,这将抛出一个。确保你走对了路!

To create an ImageIconthat resizes to the size of the JLabel:

要创建一个ImageIcon调整到 大小的JLabel

ImageIcon ico = new ImageIcon("/path/to/your/image.png");
Image img = ico.getImage();
BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.createGraphics();
g.drawImage(img, 0, 0, yourLabel.getWidth(), yourLabel.getHeight(), null);
IconImage newIco = new IconImage(bi);
yourLabel.setIcon(newIco);

EDIT:

编辑:

Here is the best way to make a border with rounded corners, using Graphics2D. First, make a new class called RoundedBorder. Paste this code into it:

这是使用圆角制作边框的最佳方法Graphics2D。首先,创建一个名为 RoundedBorder 的新类。将此代码粘贴到其中:

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.geom.Line2D;
import javax.swing.border.AbstractBorder;

public class RoundedBorder extends AbstractBorder {

public RoundedBorder(Color c, int g) {
    color = c;
    gap = g;
}

@Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
    super.paintBorder(c, g, x, y, width, height);
    Graphics2D g2d;
    if (g instanceof Graphics2D) {
        g2d = (Graphics2D) g;
        g2d.setColor(color);
        System.out.println(x + y);
        g2d.draw(new Line2D.Double((double)x, (double)y + 10, (double)x + 3, (double)y + 3));
        g2d.draw(new Line2D.Double((double)x + 3, (double)y + 3, (double)x + 10, (double)y));
        g2d.draw(new Line2D.Double((double)x + 10, (double)y, (double)x + 30, (double)y));
        g2d.draw(new Line2D.Double((double)x + 30, (double)y, (double)x + 33, (double)y + 2));
        g2d.draw(new Line2D.Double((double)x + 33, (double)y + 2, (double)x + 36, (double)y + 8));
        g2d.draw(new Line2D.Double((double)x + 36, (double)y + 8, (double)x + 36, (double)y + 28));
        g2d.draw(new Line2D.Double((double)x + 36, (double)y + 28, (double)x + 34, (double)y + 31));
        g2d.draw(new Line2D.Double((double)x + 34, (double)y + 31, (double)x + 32, (double)y + 33));
        g2d.draw(new Line2D.Double((double)x + 32, (double)y + 33, (double)x + 6, (double)y + 33));
        g2d.draw(new Line2D.Double((double)x + 6, (double)y + 33, (double)x + 3, (double)y + 31));
        g2d.draw(new Line2D.Double((double)x + 3, (double)y + 31, (double)x, (double)y + 27));
        g2d.draw(new Line2D.Double((double)x, (double)y + 27, (double)x, (double)y + 10));
    }
}

@Override
public Insets getBorderInsets(Component c) {
    return (getBorderInsets(c, new Insets(gap, gap, gap, gap)));
}

@Override
public Insets getBorderInsets(Component c, Insets insets) {
    insets.left = insets.top = insets.right = insets.bottom = gap;
    return insets;
}

@Override
public boolean isBorderOpaque() {
    return true;
}

// Variable declarations
private final Color color;
private final int gap;
}

Then, in your JFrame class, to set this as the border of a JLabel, do:

然后,在您的 JFrame 类中,要将其设置为 a 的边框JLabel,请执行以下操作:

yourLabel.setBorder(new RoundedBorder(Color.black, 10));

As MadProgrammer mentioned, a more efficient way than drawing lines is to use a RoundRectangle2D. To use this, replace all of the drawlines with

正如 MadProgrammer 所提到的,比画线更有效的方法是使用RoundRectangle2D. 要使用它,请将所有draw行替换为

g2d.draw(new RoundRectangle2D.Double(x, y, width - 1, height - 1, gap, gap));

Feel free to modify the border as you wish. Here is the syntax for using Graphics2D:

随意修改边框。这是使用的语法Graphics2D

g2d.draw(new Line2D.Double((double)x1, (double)y1, (double)x2, (double)y2));

OR

或者

g2d.draw(new Line2D.Double(Point2D p1, Point2D p2));

I hope this helped!

我希望这有帮助!

回答by RealHowTo

The simplestis to use the LineBorder class.

最简单的就是使用LineBorder类。

import java.awt.BorderLayout;
import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;

public class RoundedLineBorder extends JPanel {

  public RoundedLineBorder() {
    super(true);

    JLabel label = new JLabel("<html>Stack<br/>Overflow</html>");
    LineBorder line = new LineBorder(Color.blue, 1, true); // color, thickness, rounded
    label.setBorder(line);
    add(label, BorderLayout.CENTER);
  }

  public static void main(String s[]) {
    JFrame frame = new JFrame("Rounded Line Border");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500, 200);
    frame.setContentPane(new RoundedLineBorder());
    frame.setVisible(true);
  }
} 

but the result is not really the best looking rounded corners in town ;-)

但结果并不是城里最好看的圆角;-)