简体   繁体   English

Java Swing - 制作透明的 JButton,不透明的边框

[英]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.我有一个 JFrame,其中有一个由地图图像填充的 JLabel。 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.为此,我制作了一个很大的 JButton 网格,并将其添加到包含地图的 JLabel 中。 However, the Map cannot be seen, so I have made the JButtons completely transparent.但是,无法看到地图,因此我使 JButton 完全透明。 However, when they are Transparent, I can't see where one JButton ends, and where another one starts.但是,当它们是透明的时,我看不到一个 JButton 在哪里结束,另一个从哪里开始。 I want to create a JButton that is totally transparent on the inside, but still has a visible border around it.我想创建一个内部完全透明的 JButton,但它周围仍然有一个可见的边框。 I have tried setOpaque(false) and then setBorderPainted(true) but that makes them opaque again.我尝试过setOpaque(false)setBorderPainted(true)但这又使它们变得不透明。 I have tried everything I could find, but nothing happens.我已经尝试了我能找到的一切,但没有任何反应。 Any suggestions?有什么建议?

Once again, all I want is a Transparent JButton with Visible Borders再一次,我想要的只是一个带有可见边框的透明 JButton

You should be able to replace border with you own...你应该能够用你自己的替换边框......

边框按钮

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)您可能需要在内部使用带有EmptyBorderCompoundBorder来提供一些填充(我尝试使用setMargins但它似乎不起作用)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM