我使用基於this answer中代碼的自定義類來繪製形狀像對話框的背景。無論何時我調整應用程序的窗口大小以使組件的頂部或底部突出,所述組件的輪廓在其他組件的頂部被繪製在JScrollPane
之外;在這種情況下是JPanel
。paintComponent()繪製在其他組件上
在左側圖像中,由於組件仍然可見,繪製了JScrollPane
底部組件的邊框;而在右側圖像中,所提到的組件不再可見,並且一切看起來都如預期的那樣。
我認爲這與我使用JScrollPane
來包含組件並因此允許組件在JPanel
下滑動的事實有關。我如何防止這種情況?
主營:
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;
}
}
這個'g2d.setClip(rect);'會給你提出問題,因爲你已經改變了原來的'Graphics'上下文的剪輯,現在允許你在你不應該的地方繪畫,這就是爲什麼我不玩'剪輯'。取而代之的是,創建一個符合你想要生成的形狀的'形狀'和'繪製'/'填充',這個形狀是 – MadProgrammer
FYI:調用'paintComponent'之後繪製'邊框',這意味着它們在內容上繪製。 。意思是如果你填充邊框,你在內容上繪畫... – MadProgrammer
@MadProgrammer'draw/fill'將在文本的頂部繪製而不是在文本的後面,使得JLabel內的文本不可讀。 – Spitz