我有一个包含JScrollPane的JFrame。 JScrollPane本身拥有一个派生自JPanel的类。我使用JPanel类在其上绘制图像和其他一些图元。不幸的是,即使JPanel扩展了JSrollPane的大小,JScrollPane的滚动条也不会发生。JScrollPane中的JPanel缺少滚动条
我创造它运行一些测试代码:
这是主类:
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
class ScrolledPane extends JFrame{
private JScrollPane scrollPane;
public ScrolledPane()
{
setTitle("Scrolling Pane Application");
setSize(300, 200);
setBackground(Color.gray);
TestPanel testPanel = new TestPanel();
testPanel.setLayout(new BorderLayout());
scrollPane = new JScrollPane(testPanel);
this.getContentPane().add(scrollPane, BorderLayout.CENTER);
}
public static void main(String args[])
{
// Create an instance of the test application
ScrolledPane mainFrame = new ScrolledPane();
mainFrame.setVisible(true);
}
}
这里是从JPanel的派生类的代码:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JPanel;
public class TestPanel extends JPanel {
private Image groundPlan;
public TestPanel(){
super();
this.setBackground(Color.green);
this.setLayout(new BorderLayout());
this.groundPlan = Toolkit.getDefaultToolkit().getImage("D:\\EclipseWorkspace\\img.png");
}
public void paint(Graphics graphics) {
super.paint(graphics);
if(groundPlan != null) {
graphics.drawImage(groundPlan, 0, 0, this);
}
}
}
有趣的是,如果我只是将JLabel和Image插入JScrollpane而不是JPanel,就会出现滚动条。这里该选项的代码:
public ScrolledPane() //Frame <- Scrollpane <- label <- image
{
setTitle("Scrolling Pane Application");
setSize(300, 200);
setBackground(Color.gray);
JPanel topPanel = new JPanel();
topPanel.setLayout(new BorderLayout());
Icon image = new ImageIcon("D:\\EclipseWorkspace\\img.png");
JLabel label = new JLabel(image);
scrollPane = new JScrollPane();
scrollPane.getViewport().add(label);
this.getContentPane().add(scrollPane, BorderLayout.CENTER);
}
我想如果并欣赏你能告诉我怎样才能让我是否在JScrollPane中使用的JPanel会出现滚动条。
问候&由于 马克
1)不要在'JPanel'中重写'paint()'。使用'paintComponent()'。 2)不要延长框架。 3)为什么要在添加标签时自定义图像? – 2012-02-16 10:36:18