java - Swing 中的重叠问题

标签 java swing layout-manager null-layout-manager

我在 Java Swing 中遇到这个问题:

Image of the problem

Magenta 和 Green 组件都是 JButton。我为此使用绝对布局。当悬停在绿色上时,即使没有应用布局管理器或使用 JLayeredPane,它也会与洋红色重叠。

这种行为有什么原因吗?如何确保在悬停至绿色时洋红色保持在顶部?

编辑 2: 为了明确我的目标,我的想法是制作一个类似于带有辅助触摸的 Android 通知栏的 UI。假设 Notification Bar 是一层,Assistive Touch 是最顶层。在 JLayeredPane 中使用透明层的问题是,如果一个层/面板占据整个框架,即使设置为透明,它下面的层也不会被绘制。

最佳答案

答案很简单:不要使用绝对布局,使用真正的 LayoutManager。在这种情况下,BorderLayout 似乎可以很好地完成这项工作。

Demo

看这个例子:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class TestLayout {

    protected void initUI() {
        JFrame frame = new JFrame("test");
        Container cp = frame.getContentPane();
        cp.setLayout(new BorderLayout());
        cp.add(createColoredButton(Color.BLACK, Color.MAGENTA, "Hello World 1"), BorderLayout.NORTH);
        cp.add(createColoredButton(Color.BLACK, Color.GREEN, "Hello World 2"), BorderLayout.EAST);
        cp.add(createColoredButton(Color.WHITE, Color.BLUE, "Hello World 3"), BorderLayout.CENTER);
        // frame.pack();
        frame.setSize(600, 600);
        frame.setVisible(true);
    }

    private JButton createColoredButton(Color fgColor, Color bgColor, final String text) {
        final JButton button = new JButton(text);
        button.setBorderPainted(false);
        button.setFocusPainted(false);
        button.setForeground(fgColor);
        button.setBackground(bgColor);
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(button, "You just clicked: " + text);
            }
        });
        return button;
    }

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

            @Override
            public void run() {
                new TestLayout().initUI();
            }
        });
    }
}

关于java - Swing 中的重叠问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28787204/

相关文章:

java - 如何让Java Frame不等待?

Java Graphics 图像刷新率

java - 计算给定设置宽度的 JTextArea 中的行数

java - 没有 AWT 的 Swing GUI 监听器

java - 如何按 Java 列表中对象的属性进行分组?

java - 在 Java 中对对象列表中的项目进行分组

java: 找不到符号;符号:可变长度

java - RadioButtons 和 boolean 值连接出现问题

java - GridLayout 中 JPanel 之间的差距

java - 在 JTabbedPane 中拆分标签