如何使这个JButton可见?当我有渐进扫描背景的JWindow()时?

5
我该如何使JButton可见?
1) 当没有渐进式背景时:JButton是可见的。 enter image description here 2) 当没有渐进式背景时,即使按下JButton也不会闪烁: enter image description here 3) 当渐进式背景被打开时,JButton变得不可见,并且在按下按钮时出现闪烁,JButton()出现并自动隐藏。<<问题就在这里,那我该怎么解决呢? enter image description here
import java.awt.Color;
import java.awt.AlphaComposite;
import java.awt.BorderLayout;
import java.awt.Graphics;
import javax.swing.*;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

public class ButtonTest extends JWindow implements MouseListener, MouseMotionListener {

    private static final long serialVersionUID = 1L;
    private JFrame frame = new JFrame();
    private SoftJButton softButton1;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                ButtonTest j = new ButtonTest();
                j.createAndShowGUI();
            }
        });
    }

    public void createAndShowGUI() {
        softButton1 = new SoftJButton("Transparent Button");
        softButton1.setBackground(Color.GREEN);
        softButton1.setAlpha(0.5f);
        softButton1.setDoubleBuffered(true);
        this.setLayout(new BorderLayout());
        this.setBounds(100, 30, 200, 100);
        this.setBackground(new Color(0, 0, 0, 255));
        this.setVisible(true);
        add(softButton1);
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
    }

    public void mouseDragged(MouseEvent e) {
    }

    public void mousePressed(MouseEvent e) {
    }

    public void mouseMoved(MouseEvent e) {
    }

    public void mouseClicked(MouseEvent e) {
    }

    public void mouseReleased(MouseEvent e) {
    }

    public void mouseEntered(MouseEvent e) {
    }

    public void mouseExited(MouseEvent e) {
    }

    public static class SoftJButton extends JButton {

        private static final JButton lafDeterminer = new JButton();
        private static final long serialVersionUID = 1L;
        private boolean rectangularLAF;
        private float alpha = 1f;

        public SoftJButton() {
            this(null, null);
        }

        public SoftJButton(String text) {
            this(text, null);
        }

        public SoftJButton(String text, Icon icon) {
            super(text, icon);
            setOpaque(false);
            setFocusPainted(false);
        }

        public float getAlpha() {
            return alpha;
        }

        public void setAlpha(float alpha) {
            this.alpha = alpha;
            repaint();
        }

        @Override
        public void paintComponent(java.awt.Graphics g) {
            java.awt.Graphics2D g2 = (java.awt.Graphics2D) g;
            g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
            if (rectangularLAF && isBackgroundSet()) {
                Color c = getBackground();
                g2.setColor(c);
                g.fillRect(0, 0, getWidth(), getHeight());
            }
            super.paintComponent(g2);
        }

        @Override
        public void updateUI() {
            super.updateUI();
            lafDeterminer.updateUI();
            rectangularLAF = lafDeterminer.isOpaque();
        }
    }
}

当启用渐进式背景时,您的意思是什么? - mKorbel
1
我又不得不问一遍,关于发布一个 SSCCE,你到底哪个部分不明白???评论掉代码不是我们的责任。你需要发布我们可以复制、粘贴、编译和执行的代码。这是你对这个问题的第五个问题了。为什么这么简单的概念对你来说那么难理解呢??? - camickr
通过阅读&camickr的帖子,我来顶一下....你尝试使用JLabel代替JButton了吗?JLabel(具有半大小功能的JPanel) - mKorbel
2
@camickr,@mKorbel:请看这里,使用Timer和后台溢出的方式不会影响Swing,但是当使用真实的网络摄像头到jWindow时会被终止。例如:https://gist.github.com/1087947 - user285594
2
@camickr:这个:java版本“1.6.0_26”Java(TM) SE运行时环境(构建1.6.0_26-b03),Java HotSpot(TM)服务器虚拟机(构建20.1-b02,混合模式) - user285594
显示剩余8条评论
2个回答

4
你的视频源如何工作并不清楚,但由于混合重量级和轻量级组件,它似乎与Swing不兼容。虽然awt组件不是透明的,但你可以在Frame上绘制自己的半透明文本,并进行手动的命中测试,如下所示。你还可以检查一下你的视频源API是否支持双缓冲和页面翻转

enter image description here

import java.awt.Color;
import java.awt.AlphaComposite;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Rectangle2D;

/** @see https://dev59.com/wVnUa4cB1Zd3GeqPZVOj */
public class AlphaFrame extends Frame {

    private static final Font font = new Font("Dialog", Font.BOLD, 24);
    private float alpha = 1f;
    private Rectangle rect = new Rectangle();

    public static void main(String[] args) {
        AlphaFrame af = new AlphaFrame();
        af.setTitle("Translucent Button");
        af.setAlpha(0.5f);
        af.setForeground(Color.green);
        af.setBackground(Color.black);
        af.setVisible(true);
    }

    public AlphaFrame() {
        this.setSize(320, 240);
        this.setLocationRelativeTo(null);
        this.setBackground(Color.white);
        this.addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
        this.addMouseListener(new MouseAdapter() {

            @Override
            public void mousePressed(MouseEvent e) {
                if (rect.contains(e.getPoint())) {
                    System.out.println("Pressed.");
                }
            }
        });
        repaint();
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        Graphics2D g2 = (Graphics2D) g;
        g2.setComposite(AlphaComposite.getInstance(
            AlphaComposite.SRC_OVER, alpha));
        g2.setColor(getForeground());
        g2.setFont(font);
        FontMetrics fm = g2.getFontMetrics();
        String s = getTitle();
        Insets i = getInsets();
        int dx = i.left + 10;
        int dy = i.top + fm.getHeight() + 10;
        Rectangle2D bounds = fm.getStringBounds(s, g);
        rect.x = dx + (int) bounds.getX() - 1;
        rect.y = dy + (int) bounds.getY() - 1;
        rect.width = (int) bounds.getWidth() + 1;
        rect.height = (int) bounds.getHeight() + 1;
        System.out.println(i + " \n" + bounds + "\n" + rect);
        g2.drawRect(rect.x, rect.y, rect.width, rect.height);
        g2.drawString(s, dx, dy);
    }

    public float getAlpha() {
        return alpha;
    }

    public void setAlpha(float alpha) {
        this.alpha = alpha;
    }
}

谢谢。我用网络摄像头转储测试了您的代码,创建了AlphaFrame af = new AlphaFrame();,我看到我的摄像头正在捕获,但是您的GUI只是显示,没有任何透明度。 - user285594
我不知道你的源API;我猜你需要重写它的 paint() 方法来添加半透明层。 - trashgod
它是一个闭源的SDK(商业许可),只允许我在本地电脑上使用。我不能使用paint()方法来覆盖它。我只能使用thirdpartySDK.windowID(my JWindow or Window or Frame or Canvas or JFrame)这样的方法。然后它就开始捕捉摄像头。当它开始运行时,Java中的透明度都不起作用。我尝试了你的示例和其他示例,但都没有成功。 - user285594
你不能在作为参数传递给 thirdpartySDK.windowID() 的组件中重写 paint()(或 paintComponent(),根据情况而定)吗? - trashgod
不,这只是一段编译后的代码,它接受一个元素作为参数。例如:public void setWindowID(long handle) { //编译后的代码 throw new RuntimeException("编译后的代码"); } - user285594

1
import java.awt.event.*;
import java.awt.Color;
import java.awt.AlphaComposite;
import java.awt.Dimension;
import javax.swing.*;
import javax.swing.UIManager.LookAndFeelInfo;

public class ButtonTest {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new ButtonTest().createAndShowGUI();
            }
        });
    }
    private JFrame frame;
    private SoftJButton softButton1;

    public void createAndShowGUI() {
        softButton1 = new SoftJButton("Transparent Button");
        softButton1.setPreferredSize(new Dimension(800, 600));
        frame = new JFrame();
        frame.add(softButton1);
        frame.setLocation(150, 150);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
        Timer alphaChanger = new Timer(30, new ActionListener() {

            private float incrementer = -.03f;

            @Override
            public void actionPerformed(ActionEvent e) {
                float newAlpha = softButton1.getAlpha() + incrementer;
                if (newAlpha < 0) {
                    newAlpha = 0;
                    incrementer = -incrementer;
                } else if (newAlpha > 1f) {
                    newAlpha = 1f;
                    incrementer = -incrementer;
                }
                softButton1.setAlpha(newAlpha);
            }
        });
        alphaChanger.start();
        Timer uiChanger = new Timer(5500, new ActionListener() {

            private LookAndFeelInfo[] laf = UIManager.getInstalledLookAndFeels();
            private int index = 1;

            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    UIManager.setLookAndFeel(laf[index].getClassName());
                    SwingUtilities.updateComponentTreeUI(frame);
                } catch (Exception exc) {
                    exc.printStackTrace();
                }
                index = (index + 1) % laf.length;
            }
        });
        uiChanger.start();
    }

    public static class SoftJButton extends JButton {

        private static final JButton lafDeterminer = new JButton();
        private static final long serialVersionUID = 1L;
        private boolean rectangularLAF;
        private float alpha = 1f;

        public SoftJButton() {
            this(null, null);
        }

        public SoftJButton(String text) {
            this(text, null);
        }

        public SoftJButton(String text, Icon icon) {
            super(text, icon);

            setOpaque(false);
            setFocusPainted(false);
        }

        public float getAlpha() {
            return alpha;
        }

        public void setAlpha(float alpha) {
            this.alpha = alpha;
            repaint();
        }

        @Override
        public void paintComponent(java.awt.Graphics g) {
            java.awt.Graphics2D g2 = (java.awt.Graphics2D) g;
            g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
            if (rectangularLAF && isBackgroundSet()) {
                Color c = getBackground();
                g2.setColor(c);
                g.fillRect(0, 0, getWidth(), getHeight());
            }
            super.paintComponent(g2);
        }

        @Override
        public void updateUI() {
            super.updateUI();
            lafDeterminer.updateUI();
            rectangularLAF = lafDeterminer.isOpaque();
        }
    }
}

1
是的,当我在上面应用网络摄像头时,它会闪烁并且所有按钮都消失了。当鼠标悬停在窗口上时,也会出现闪烁。 - user285594
@89899.3K http://processing.org/reference/libraries/video/index.html 这是 Processing 视频库的链接,其中一些大师(我忘记是谁了)是成员。 - mKorbel
2
这段代码已经过验证,但并没有解决问题。Swing GUI适用于轻量级任务,但我的情况是重量级的,需要在主Frame()中加载视频。 - user285594

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接