我正在尝试重叠JPanel实例.将面板直接放在另一个面板上,位置和尺寸完全相同.每次我这样做,它将另一个面板移动到另一侧或下面,前一个面板位于另一个更大的面板内,并且其中有按钮.
我该怎么做?请记住,它使用的是Window Builder工具.
解决方法:
您可能还想查看OverlayLayout
,见于here.它不包含在传统的gallery中,但它可能是有意义的.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.OverlayLayout;
/** @see https://*.com/a/13437388/230513 */
public class OverlaySample {
public static void main(String args[]) {
JFrame frame = new JFrame("Overlay Sample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new OverlayLayout(panel));
panel.add(create(1, "One", Color.gray.brighter()));
panel.add(create(2, "Two", Color.gray));
panel.add(create(3, "Three", Color.gray.darker()));
frame.add(panel, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private static JLabel create(final int index, String name, Color color) {
JLabel label = new JLabel(name) {
private static final int N = 64;
@Override
public boolean isOpaque() {
return true;
}
@Override
public Dimension getPreferredSize() {
return new Dimension(index * N, index * N);
}
@Override
public Dimension getMaximumSize() {
return new Dimension(index * N, index * N);
}
};
label.setHorizontalAlignment(JLabel.RIGHT);
label.setVerticalAlignment(JLabel.BOTTOM);
label.setBackground(color);
label.setAlignmentX(0.0f);
label.setAlignmentY(0.0f);
return label;
}
}