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