简体   繁体   English

如何将 JScrollpane 添加到 JPanel?

[英]How do I add JScrollpane to a JPanel?

I have a line that extends outside of my screen so I can't see it.我有一条线延伸到我的屏幕之外,所以我看不到它。 So I need a JScrollpane added to the Test2 class but when I try it doesn't show up.所以我需要将 JScrollpane 添加到 Test2 类中,但是当我尝试时它没有出现。

import javax.swing.*;
import java.awt.*;

public class Test extends JFrame {

    Test() {
        setSize(1000, 500);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setContentPane(new Test2());
        setVisible(true);
    }

    public static void main(String[] args) {
        new Test();
    }
}

class Test2 extends JPanel {

    protected void paintComponent(Graphics g) {
        g.drawLine(100, 100, 2000, 100);
    }
}

You didn't used the JscrollPanel in your code that's why you couldn't see the scrollbar!您没有在代码中使用 JscrollPanel 这就是为什么您看不到滚动条的原因! I think this will work我认为这会奏效

import javax.swing.*;
import java.awt.*;
public class Test extends JFrame {
Test() {
    setSize(1000, 500);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    getContentPane().setLayout(new FlowLayout());
    Test2 test2=new Test2();
    JScrollPane scrollableLine = new JScrollPane(test2);
scrollableLine.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    scrollableLine.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    setContentPane(scrollableLine);
    setVisible(true);
}

public static void main(String[] args) {
    new Test();
}
}

class Test2 extends JPanel {

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawLine(100, 100, 2000, 100);

}
@Override
public Dimension getPreferredSize() {
    return new Dimension(3000, 3000);
}

}

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

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