如何在Swing中使用内部阴影创建这样的JButton
?
我想用不同的JButton
边框创建Color
,例如上边框和左边框颜色应为黑色,右下边框颜色应为白色。
但总的来说,我想要像上面的图像一样,在顶部和左侧都有深灰色的内部阴影。
答案 0 :(得分:4)
首先我认为你可以通过一个简单的BevelBorder
来实现这个目标,但不幸的是你不能轻松地设置边框的厚度......所以我必须基本上做一个自定义的Border
。如果您不喜欢paintBorder
方法中的按钮样式,则可以对其进行更多自定义,但您必须知道如何使用Graphics
。这就是我所拥有的:
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.border.Border;
/**
*
*/
public class MyBorder implements Border {
private int thickness_ = 4;
private Color white = Color.WHITE;
private Color gray = Color.GRAY;
private Color black = Color.BLACK;
public static void main(String[] args) {
JFrame frm = new JFrame("Border Test");
frm.setLayout(new FlowLayout());
JButton btn = new JButton("Button");
MyBorder border = new MyBorder();
btn.setBorder(border);
btn.setFocusPainted(false);
btn.setPreferredSize(new Dimension(60,30));
btn.setBackground(Color.LIGHT_GRAY);
frm.add(btn);
frm.setSize(200,200);
frm.setVisible(true);
}
public void paintBorder(Component c, Graphics g, int x, int y, int width,
int height) {
Color oldColor = g.getColor();
int i;
for (i = 0; i < thickness_; i++) {
g.setColor(white);
g.drawRect(x + i, y + i, width - i - i - 1, height - i - i - 1); //White Rectangle
}
for (i = 0; i < thickness_/2; i++) {
g.setColor(black);
g.drawLine(x + i, y + i, (width - x) - (i * 2), y + i); //Top Outer Edge
g.drawLine(x + i, y + i, x + i, (height - y) - (i * 2)); //Left Outer Edge
}
for (i = thickness_/2; i < thickness_; i++) {
g.setColor(gray);
g.drawLine(x + i, y + i, (width - x) - (i * 2), y + i); //Top Inner Edge
g.drawLine(x + i, y + i, x + i, (height - y) - (i * 2)); //Left Inner Edge
}
g.setColor(oldColor);
}
public int getThickness() {
return thickness_;
}
public void setThickness(int i) {
thickness_ = i;
}
public boolean isBorderOpaque() {
return true;
}
public Insets getBorderInsets(Component c) {
return new Insets(thickness_, thickness_, thickness_, thickness_);
}
}