Notalexander
Notalexander

Reputation: 3

Java Swing - Making Transparent JButtons, Opaque borders

I have a JFrame, and within it, a JLabel that is filled by an image of a Map. I want to have clickable square “Tiles” in a grid over the image of the map. To do this, I made a large grid of JButtons that I have added to the JLabel containing the Map. However, the Map cannot be seen, so I have made the JButtons completely transparent. However, when they are Transparent, I can’t see where one JButton ends, and where another one starts. I want to create a JButton that is totally transparent on the inside, but still has a visible border around it. I have tried setOpaque(false) and then setBorderPainted(true) but that makes them opaque again. I have tried everything I could find, but nothing happens. Any suggestions?

Once again, all I want is a Transparent JButton with Visible Borders

Upvotes: 0

Views: 631

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347184

You should be able to replace border with you own...

Border Button

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setBackground(Color.RED);
            setLayout(new GridBagLayout());
            JButton btn = new JButton("Hello");
            btn.setOpaque(false);
            btn.setContentAreaFilled(false);
            btn.setBorderPainted(true);

            btn.setBorder(new LineBorder(Color.BLUE));

            add(btn);

        }

    }
}

You might need to use a CompoundBorder with a EmptyBorder on the inside to provide some padding (I tried using setMargins but it didn't seem to work)

Upvotes: 1

Related Questions