简体   繁体   English

JScrollPane不显示JPanel

[英]JScrollPane does not show the JPanel

So I was trying to make a browser in java. 所以我试图用Java创建浏览器。 I wanted to make the user be able to scroll the content of the website. 我想让用户能够滚动网站的内容。 I tried the put a JPanel in a JScrollPane, but the JPanel did not show up. 我尝试将JPanel放在JScrollPane中,但未显示JPanel。 After I got that problem I made a new java project to test this problem on, the problem still occurred. 遇到问题后,我制作了一个新的Java项目来测试此问题,该问题仍然发生。 Here is the code of the test project: 这是测试项目的代码:

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 it displayed: 它显示的是: 这是代码浸入的内容

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

Don't add components directly to a scroll pane. 不要将组件直接添加到滚动窗格中。 The component needs to be added to the viewport of the scroll pane. 该组件需要添加到滚动窗格的viewport You do this by using: 您可以使用以下方法完成此操作:

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

or 要么

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

Don't use the getGraphics(...) method to do painting: 不要使用getGraphics(...)方法进行绘画:

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

You should be overriding the paintComponent() method of a JPanel and add the panel to the frame. 你应该重写paintComponent()一个的方法JPanel和面板添加到该帧。 Read the section from the Swing tutorial on Custom Painting for more information and working examples. 阅读有关定制绘画的Swing教程中的部分,以获取更多信息和工作示例。

Keep a link to the tutorial handy for all the Swing basics. 保留所有Swing基础知识到本教程的链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM