我在 Java Swing 中遇到这个问题:
Magenta 和 Green 组件都是 JButton。我为此使用绝对布局。当悬停在绿色上时,即使没有应用布局管理器或使用 JLayeredPane,它也会与洋红色重叠。
这种行为有什么原因吗?如何确保在悬停至绿色时洋红色保持在顶部?
编辑 2: 为了明确我的目标,我的想法是制作一个类似于带有辅助触摸的 Android 通知栏的 UI。假设 Notification Bar 是一层,Assistive Touch 是最顶层。在 JLayeredPane 中使用透明层的问题是,如果一个层/面板占据整个框架,即使设置为透明,它下面的层也不会被绘制。
最佳答案
答案很简单:不要使用绝对布局,使用真正的 LayoutManager
。在这种情况下,BorderLayout
似乎可以很好地完成这项工作。
看这个例子:
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/