setOpaque() in java

天大地大妈咪最大 提交于 2019-11-27 09:20:25
trashgod

You may get some insight from the section on Opacity in the article Painting in AWT and Swing. In particular, setting the opaque property does not mean, "Make the component's background transparent." An sscce that demonstrates the problem may also be fruitful.

Addendum: Simplifying your example, it looks like the text area itself can be made transparent, but the Nimbus defaults are affecting the area's borders. You might try changing them accordingly.

A few notes on your code:

  • Always build you GUI on the event dispatch thread.
  • Don't draw from another thread.
  • Don't swallow exception.

Addendum: See changes to create().

Addendum: You might want to look at the isPalette property, too

jif.putClientProperty("JInternalFrame.isPalette", Boolean.TRUE);

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import javax.swing.JInternalFrame;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.UIManager;

public class TransparentTextArea extends JTextArea {

    int alpha;

    public TransparentTextArea(int alpha) {
        super(4, 16);
        this.alpha = alpha;
        this.setBackground(new Color(0, 0, 0, alpha));
        this.setFont(new Font("Serif", Font.ITALIC, 24));
        this.setEditable(false);
        this.setText("Twas brillig and the slithy toves,\n"
            + "Did gyre and gimble in the wabe;\n"
            + "All mimsy were the borogoves,\n"
            + "And the mome raths outgrabe.");
    }

    private static void create() {
        JFrame f = new JFrame();
        f.setLayout(new FlowLayout());
        f.getContentPane().setBackground(new Color(0xffffc0));
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JInternalFrame jif = new JInternalFrame();
        JPanel panel = new JPanel();
        panel.setBackground(new Color(0xffffc0));
        panel.add(new TransparentTextArea(0));
        jif.add(panel);
        jif.setVisible(true);

        f.add(jif);
        f.pack();
        f.setVisible(true);
    }

    public static void main(String[] args) {

        try {
            UIManager.setLookAndFeel(
                "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        } catch (Exception e) {
            e.printStackTrace();
        }

        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                create();
            }
        });
    }
}
Yishai

As explained here, setOpaque does not do what you would think that it does, and that failure is made obvious in Nimbus. The other answer which refers to the alpha color is the correct way to accomplish what you want.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!