java button形状,Java:具有自定义形状的JButton:具有金属外观和渐变感

本文档展示了如何创建一个继承自JButton的类,使其呈现为Enter按钮的形状。作者通过定义一个Polygon来实现自定义形状,并询问如何将此按钮填充为默认JButton的渐变色。建议查看JDK中javax.swing.plaf.metal.MetalButtonUI的update方法源码以获取灵感。
摘要由CSDN通过智能技术生成

I have a new class derived from JButton which gives me the shape of a Enter-Button.

Now I want to have it filled with the same gradient as the default JButton.

But I do not know. How I can do this?

At the moment it is filled with plain black color.

import java.awt.Graphics;

import java.awt.Graphics2D;

import java.awt.Point;

import java.awt.Polygon;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

public class EnterButton extends JButton {

private Polygon shape;

public EnterButton() {

this.shape = new Polygon();

// initialisiere Form

this.initialize();

}

protected void initialize() {

Point p1, p2, p3, p4, p5, p6;

this.setSize(90, 120);

p1 = new Point(0, 0);

p2 = new Point(0, 60);

p3 = new Point(30, 60);

p4 = new Point(30, 120);

p5 = new Point(90, 120);

p6 = new Point(90, 0);

this.shape.addPoint((int) Math.round(p1.getX()),

(int) Math.round(p1.getY()));

this.shape.addPoint((int) Math.round(p2.getX()),

(int) Math.round(p2.getY()));

this.shape.addPoint((int) Math.round(p3.getX()),

(int) Math.round(p3.getY()));

this.shape.addPoint((int) Math.round(p4.getX()),

(int) Math.round(p4.getY()));

this.shape.addPoint((int) Math.round(p5.getX()),

(int) Math.round(p5.getY()));

this.shape.addPoint((int) Math.round(p6.getX()),

(int) Math.round(p6.getY()));

this.setMinimumSize(this.getSize());

this.setMaximumSize(this.getSize());

this.setPreferredSize(this.getSize());

}

// Hit detection

public boolean contains(int x, int y) {

return this.shape.contains(x, y);

}

// Zeichne den Button

protected void paintComponent(Graphics g) {

Graphics2D gCopy = (Graphics2D) g.create();

gCopy.fillPolygon(this.shape);

}

// zeichne die Border

protected void paintBorder(Graphics g) {

}

public static void main(String[] args) {

JFrame frame = new JFrame();

JPanel panel = new JPanel();

EnterButton button = new EnterButton();

panel.add(button);

frame.add(panel);

frame.pack();

frame.setVisible(true);

}

}

Thank you!

解决方案

Also search for the source code of the update(Graphics, JComponent) method of class javax.swing.plaf.metal.MetalButtonUI. That's somewhere under your JDK.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值