JScrollPane & Graphics2D

后端 未结 2 1483
夕颜
夕颜 2021-01-16 01:02

I am trying to draw graphics that is bigger than the JFrame and use JScrollPane to scroll the entire graphics. I created a simple example with two lines. The scroll bars app

2条回答
  •  伪装坚强ぢ
    2021-01-16 01:43

    The problem comes from the lines

    JPanel panel = new JPanel();
    panel.add(test);
    JScrollPane scrollPane = new JScrollPane(panel);
    

    You are adding test to panel which uses FlowLayout by default. This layout does not strech the components in it, so test on which you draw has dimensions 0x0 and what you see in the scroll pane is the empty panel.

    To fix this you can set panel to use BorderLayout which stretches the center component:

    JPanel panel = new JPanel(new BorderLayout());
    panel.add(test);
    JScrollPane scrollPane = new JScrollPane(panel);
    

    or add test directly to the scroll pane:

    JScrollPane scrollPane = new JScrollPane(test);
    

    Additionally:

    • Always call super.paintComponent(g) as the first line when overriding paintComponent.
    • Don't use null layouts (and consequently don't set bounds on components).
    • When you use setPreferredSize remember that if the dimensions are too large they will "flow off" the screen.

提交回复
热议问题