我有一个 JScrollPane
填充了一个 JPanel
(这是我的 JFrame
的内容面板)。 JPanel
执行自定义绘图 - 但是,它不会出现在 JScrollPane
之上。我应该覆盖 paintComponent
以外的东西吗?
这是一个演示:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.LayoutManager;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
public class Test {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// Create the frame.
JFrame frame = new JFrame();
frame.setPreferredSize(new Dimension(1024, 768));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel custom = new CustomPanel(new BorderLayout());
// Add the scroll pane.
JScrollPane scroll = new JScrollPane();
scroll.setBorder(BorderFactory.createLineBorder(Color.blue));
custom.add(scroll, BorderLayout.CENTER);
// Display the frame.
frame.setContentPane(custom);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
@SuppressWarnings("serial")
class CustomPanel extends JPanel {
public CustomPanel(LayoutManager lm) {
super(lm);
}
@Override
public void paintComponent(Graphics g) {
g.setColor(Color.red);
g.drawRect(200, 200, 200, 200);
}
}
最佳答案
I'd like for the paint on the JPanel to go over top of the paint on the JScrollPane
你可以画到
非常相似(就像今天的 JLayer)正在绘制到
GlassPane
,注意GlassPane
到consume()
(默认情况下)MouseEvent
如果添加了一些JComponent
(s),GlassPane
可以覆盖整个RootPane
或仅可用 Rectangle 的一部分,取决于使用的LayoutManager
和Dimension
从 layedJComponent
(s) 返回
关于java - 如何在 JScrollPane 之上绘制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16741658/