我有一個包含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