简体   繁体   中英

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.

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! 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);
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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