Why .paintComponent() is defined on JComponent?

霸气de小男生 提交于 2019-12-02 10:47:00

Swing is based on AWT. So the initial restriction is based on how AWT paints it components. Because Swing is light weight, when a components root component is painted, the child, Swing, components need to be notified that they need to update as well. This is done by calling the paint methods of all the child components affected by the update (which in turn call the paintComponent methods).

Much of the decisions about the Swing API's paint chain are based around the concept of customisation. It reduces the complexity involved (by discouraging the overriding of paint and focus the functionality down t the paintComponent method).

The Look and Feel API is based on a "delegate" model. This means that the functionality used to perform a said action is "delegated" to some other object. This means that the UI delegate UI doesn't actually know when a component "needs" to be painted, but instead is told, by the component, that it needs to be painted. This makes it much more flexible and in many cases, easier to customise.

Based on your previous question a custom ButtonUI is probably one the better choices, this way you gain much more control over how the button is painted.

Trying to get the buttons to follow the current look and feels color schemes would be very difficult, but you could try having a look at the src.jar which is installed with the JDK, which includes many implementations of look and feels (and if your on Windows you should get the Windows look and feel as well, if your on Mac, then you don't get either Mac or Windows 🙄)

I started by having a look at BasicButtonUI and ButtonUI to get a better understanding of there properties. I pulled some of more interesting methods into a custom ShapeButtonUI...

public class ShapeButtonUI extends BasicButtonUI {

    private Shape shape;

    public ShapeButtonUI(Shape shape) {
        this.shape = shape;
    }

    protected Color getSelectColor() {
        return UIManager.getColor(getPropertyPrefix() + "select");
    }

    protected Color getDisabledTextColor() {
        return UIManager.getColor(getPropertyPrefix()
                        + "disabledText");
    }

    protected Color getFocusColor() {
        return UIManager.getColor(getPropertyPrefix() + "focus");
    }

    @Override
    protected void installDefaults(AbstractButton b) {
        super.installDefaults(b);
    }

    @Override
    protected void uninstallDefaults(AbstractButton b) {
        super.uninstallDefaults(b);
    }

    @Override
    public void paint(Graphics g, JComponent c) {
        Graphics2D g2d = (Graphics2D) g.create();
        g2d.setClip(shape);
        Rectangle bounds = shape.getBounds();
        LinearGradientPaint lgp = new LinearGradientPaint(
                        new Point(bounds.x, bounds.y),
                        new Point(bounds.x, bounds.y + bounds.height),
                        new float[]{0, 1},
                        new Color[]{c.getBackground().brighter(), c.getBackground().darker()});
        g2d.setPaint(lgp);
        g2d.fill(shape);
        g2d.dispose();
        g2d = (Graphics2D) g.create();
        g2d.setColor(c.getForeground());
        g2d.draw(shape);
        g2d.dispose();
        super.paint(g, c);
    }

    @Override
    protected void paintButtonPressed(Graphics g, AbstractButton b) {
        super.paintButtonPressed(g, b);
    }

    @Override
    protected void paintFocus(Graphics g, AbstractButton b,
                    Rectangle viewRect, Rectangle textRect, Rectangle iconRect) {
        super.paintFocus(g, b, viewRect, textRect, iconRect);
    }

    @Override
    protected void paintText(Graphics g, AbstractButton b, Rectangle textRect, String text) {
        super.paintText(g, b, textRect, text);

//          ButtonModel model = b.getModel();
//          FontMetrics fm = SwingUtilities2.getFontMetrics(c, g);
//          int mnemIndex = b.getDisplayedMnemonicIndex();
//
//          /* Draw the Text */
//          if (model.isEnabled()) {
//              /**
//               * * paint the text normally
//               */
//              g.setColor(b.getForeground());
//          } else {
//              /**
//               * * paint the text disabled **
//               */
//              g.setColor(getDisabledTextColor());
//          }
//          SwingUtilities2.drawStringUnderlineCharAt(c, g, text, mnemIndex,
//                          textRect.x, textRect.y + fm.getAscent());

    }

    @Override
    public Dimension getMinimumSize(JComponent c) {
        Rectangle bounds = shape.getBounds();
        return new Dimension(bounds.x + bounds.width + 1, bounds.y + bounds.height + 1);
    }

    @Override
    public Dimension getPreferredSize(JComponent c) {
        Rectangle bounds = shape.getBounds();
        return new Dimension(bounds.x + bounds.width + 1, bounds.y + bounds.height + 1);
    }

    @Override
    public Dimension getMaximumSize(JComponent c) {
        Rectangle bounds = shape.getBounds();
        return new Dimension(bounds.x + bounds.width + 1, bounds.y + bounds.height + 1);
    }

}

Most of these you probably don't need to worry about, but you should at least know they exist as you may want to customise some of the other properties/functionality later.

This delegate is intended to be installed on a button as needed, as apposed to installing it as the default UI delegate for buttons. The reason for this is the need for the shape object. This allows each button to have it's own shape if you want.

You could seed a single shape into the UIManager's properties as well and use that instead, but I've not bothered for this example.

I then created my own shape/path...

public class PointerPath extends Path2D.Double {

    public PointerPath() {
        moveTo(1, 1);
        lineTo(150, 1);
        lineTo(198, 100);
        lineTo(150, 198);
        lineTo(1, 198);
        lineTo(50, 100);
        closePath();
    }

}

And the applied it to a button...

ShapeButtonUI shapeUI = new ShapeButtonUI(new PointerPath());
JButton btn = new JButton("That way");
btn.setUI(shapeUI);

Which finally generated something like...

Now, this is a really basic example, as realistically, the button should be sizing itself around the text (with some additional padding/margin information), but this would require a multi part shape, so we knew which sections could be resized and in what directions, so, complicated.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!