[英]Change Border Color of a JButton in Java Swing preserving the insets
[英]Swing - How to modify the border color of a JButton?
我在下面尝试了一个示例,一切似乎都很好,除非您正在做不同的事情:
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
public class TestApp {
public TestApp() {
createAndShowGui();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(TestApp::new);
}
private void createAndShowGui() {
JFrame frame = new JFrame("TestApp");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setBorder(new EmptyBorder(20, 20, 20, 20));
panel.setBackground(Color.WHITE);
JButton button = new JButton("Primary");
button.setOpaque(false);
button.setBackground(null);
button.setFocusPainted(false);
button.setForeground(new Color(69, 143, 253));
RoundedBorder blueLineBorder = new RoundedBorder(new Color(69, 143, 253), 10);
Border emptyBorder = BorderFactory.createEmptyBorder(button.getBorder().getBorderInsets(button).top, button.getBorder().getBorderInsets(button).left, button.getBorder().getBorderInsets(button).bottom, button.getBorder().getBorderInsets(button).right);
button.setBorder(BorderFactory.createCompoundBorder(blueLineBorder, emptyBorder));
panel.add(button);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
private static class RoundedBorder implements Border {
private int radius = 10;
private Color color;
private RoundedBorder(Color color, int radius) {
this.color = color;
this.radius = radius;
}
@Override
public Insets getBorderInsets(Component c) {
return new Insets(this.radius + 1, this.radius + 1, this.radius + 1, this.radius + 1);
}
@Override
public boolean isBorderOpaque() {
return true;
}
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
g.setColor(color);
g.drawRoundRect(x, y, width - 1, height - 1, radius, radius);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.