1

我有一个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);
    }

}
4

4 回答 4

3

我想让 JPanel 上的油漆越过 JScrollPane 上的油漆

你可以画到

  • JViewport 你可以在这里这里看到

  • 使用基于 JXlayer(Java6) 的 JLayer(Java7)

  • 非常相似(如今天的 JLayer)正在绘画GlassPane,注意GlassPaneconsume()默认情况下)MouseEvent在添加一些JComponent(s)的情况下,GlassPane可以覆盖整个RootPane或仅部分可用的 Rectangle,取决于使用LayoutManagerDimension从layed JComponent( s)

于 2013-05-24T19:14:46.463 回答
0

只是一个简单的问题。您正在将滚动窗格添加到隐藏您正在绘制的内容的自定义面板中。相反,请考虑使用 cutsompanel 作为其内容来初始化您的滚动窗格。

例子:

JScrollPane scrlPane = new JScrollPane(customPanel);
于 2013-05-24T18:48:34.290 回答
0

当您将单个组件添加到 aBorderLayout并指定BorderLayout.CENTER时,该组件将扩展以完全填充其父级。如果组件是不透明的,您将无法在父组件中看到您正在执行的任何自定义绘画。

于 2013-05-24T18:50:35.393 回答
0

有效的方式(正如@mKorbel 建议的那样)是使用 JViewport:

scroll.setViewport(new CustomViewPort());

whereCustomViewPort是一个JViewport覆盖该paintComponent方法的扩展类。

于 2013-05-24T19:12:21.523 回答