How to modify the border color of a JButton?
I want to get something like this:
But I canĀ“t modify the color, the borde is black:
And If I try to add a LineBorder or any other borde, I am not able to remove the inner border:
Advertisement
Answer
I tried an example below and all seems fine, unless you are doing something different:
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); } } }