有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

自定义边界外的java组件绘制

在这个自定义边框类中,我定义了一个RoundRectangle2D形状。此对象用于绘制边界。不幸的是,由于JComponentpaint方法在paintBorder之前调用paintComponent,因此将Graphics剪辑设置为RoundRectangle2D形状没有效果;即使我发repaint。因此,组件将在其边界外涂漆,这是可以理解的不可取的

所以,我想知道:如何让组件在自定义边框内以独占方式绘制

我考虑的一种方法是在paintComponent方法中获取组件的Border对象。然后将这个对象投射到适当的类中,我定义了影响剪辑的参数。但这似乎不是一个“合理”的设计


编辑-

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.RenderingHints;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.border.AbstractBorder;

class JRoundedCornerBorder extends AbstractBorder 
{   
    private static final long serialVersionUID = 7644739936531926341L;
    private static final int THICKNESS = 2;

    JRoundedCornerBorder()
    {
        super();
    }

    @Override
    public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) 
    {
        Graphics2D g2 = (Graphics2D)g.create();

        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        if(c.hasFocus())
        {
            g2.setColor(Color.BLUE);
        }
        else
        {
            g2.setColor(Color.BLACK);
        }
        g2.setStroke(new BasicStroke(THICKNESS, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
        g2.drawRoundRect(THICKNESS, THICKNESS, width - THICKNESS - 2, height - THICKNESS - 2, 20, 20);

        g2.dispose();
    }

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

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

    public boolean isBorderOpaque() {
        return false;
    }

    public static void main(String[] args) 
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run() 
            {
                final JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new FlowLayout());

                // Add button with custom border
                final JButton button = new JButton("Hello");
                button.setBorder(new JRoundedCornerBorder());
                button.setBackground(Color.YELLOW);
                button.setPreferredSize(new Dimension(200, 200));
                frame.add(button);

                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}

enter image description here

红色圆圈突出显示组件超出其边界的位置


共 (0) 个答案