简体   繁体   中英

Painting on a JPanel and adding it to a JScrollPane

As the title suggests, i want to paint on a JPanel and have it displayed within a JScrollpane so if the contents in the JPanel is large, scrollbars are displayed. I tried to accomplish this by:

import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class Main extends JFrame{

DrawPanel dp;
JScrollPane jsp;

public Main(){
    setTitle("Test");
    setSize(400,400);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    dp = new DrawPanel();
    jsp = new JScrollPane(dp);
    getContentPane().add(jsp);
}

public class DrawPanel extends JPanel{

    @Override
    protected void paintComponent(Graphics grphcs) {
        super.paintComponent(grphcs);
        Graphics2D g2d = (Graphics2D) grphcs;
        g2d.drawString("..long text....long text....long text....long text....long text....long text....long text....long text..", 10, 20);
    }

}

public static void main(String[] args) {
    new Main().setVisible(true);
}

}

Current Output

Expected Output: A window with the long text and horizontal scrollbar.

I have also tried overriding the getPreferredSize method (as some answers in other questions suggested) but it doesn't seem to work. Also, can someone explain why scrollbars appear (using jscrollpane) when there are labels or buttons in a panel which is added to the jscrollpane, but the same doesn't work in the case above? Any help will be much appreciated.

You can resize a JPanel via setting the size(s) or overriding them.

    Dimension d = new Dimension(800, 800);
    dp.setMinimumSize(d);
    dp.setMaximumSize(d);
    dp.setPreferredSize(d); 

Scroll bars appear when I do that.

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