我正在使用基于中的代码的自定义类这个答案 https://stackoverflow.com/a/16909994/5686799,绘制一个形状像讲话泡泡的背景。每当我将应用程序的窗口大小调整到足以使组件在顶部或底部突出时,该组件的轮廓就会绘制在窗口之外JScrollPane
在其他组件之上;在这种情况下JPanel
.
在左侧图像中,组件底部的边框JScrollPane
由于组件仍然可见,因此被绘制;而在右侧图像中,所提到的组件不再可见,并且一切看起来都按预期进行。
我相信这与我使用的事实有关JScrollPane
包含组件,从而允许组件在JPanel
。我该如何防止这种情况?
Main:
public class Main {
public static void main(String[] args) {
JPanel panel = new JPanel(), panelbar = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panelbar.setLayout(new FlowLayout());
JScrollPane scroll = new JScrollPane(panel,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
JFrame frame = new JFrame("");
frame.setLayout(new BorderLayout());
frame.setSize(200, 223);
for (int i = 0; i < 6; i++) {
JLabel label = new JLabel("JLabel");
label.setBorder(new CustomBorder());
label.setOpaque(true);
label.setBackground(Color.ORANGE);
panel.add(label);
}
panelbar.add(new JLabel("JPanel"));
frame.add(scroll, BorderLayout.CENTER);
frame.add(panelbar, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
定制类:
public class CustomBorder extends AbstractBorder {
private static final long serialVersionUID = 1L;
Insets i;
CustomBorder() {
i = new Insets(10, 20, 10, 20);
}
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
super.paintBorder(c, g, x, y, width, height);
Polygon bubble = new Polygon();
bubble.addPoint(x + 10, y + 5);
bubble.addPoint(x + width - 10, y + 5);
bubble.addPoint(x + width - 10, y + height / 3);
bubble.addPoint(x + width, y + height / 2);
bubble.addPoint(x + width - 10, y + height * 2 / 3);
bubble.addPoint(x + width - 10, y - 5 + height);
bubble.addPoint(x + 10, y - 5 + height);
Graphics2D g2d = (Graphics2D) g;
Area rect = new Area(new Rectangle(x, y, width, height));
rect.subtract(new Area(bubble));
g2d.setClip(rect);
g2d.setColor(c.getParent().getBackground());
g2d.fillRect(0, 0, width, height);
g2d.setClip(null);
g2d.setColor(Color.BLACK);
g2d.draw(bubble);
}
@Override
public Insets getBorderInsets(Component c) {
return i;
}
@Override
public Insets getBorderInsets(Component c, Insets insets) {
return i;
}
}