2016-11-18 119 views
0

所以我试图用java制作浏览器。我想让用户能够滚动网站的内容。我试过把Janel放在JScrollPane中,但是JPanel没有显示出来。我得到这个问题后,我做了一个新的Java项目来测试这个问题,问题仍然存在。 下面是测试项目的代码:JScrollPane不显示JPanel

package exp; 

import java.awt.Color; 

import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.JScrollPane; 

public class test { 
    public static void main(String[] args) { 
     JFrame f = new JFrame("test"); 
     JScrollPane s = new JScrollPane(); 
     JPanel p = new JPanel(); 
     s.add(p); 
     f.add(s); 
     f.setVisible(true); 
     f.setSize(800, 600); 
     p.setBackground(Color.WHITE); 
     p.getGraphics().drawString("test", 50, 50); 

    } 
} 

这是它显示: This is what the code dipslayed

回答

6
JScrollPane s = new JScrollPane(); 
JPanel p = new JPanel(); 
s.add(p); 

不要直接将组件添加到滚动窗格。该组件需要被添加到滚动窗格的viewport。通过使用这样做:

JPanel p = new JPanel(); 
JScrollPane s = new JScrollPane(p); 

JPanel p = new JPanel(); 
JScrollPane s = new JScrollPane(); 
s.setViewportView(p); 

不要使用getGraphics(...)方法做画:

// p.getGraphics().drawString("test", 50, 50); 

你应该重写一个JPanelpaintComponent()方法将面板添加到框架。请参阅Custom Painting上的Swing教程部分以获取更多信息和工作示例。

保持一个链接教程方便所有的Swing基础。

+0

非常感谢 –