使用 JPanel 绘图使 JScrollPanel 可动态调整大小

Make JScrollPanel dynamically resizable with JPanel drawing

我添加了一个 JScrollPanel 和一个 JPanel。我想绘制到 JPanel 并使 JScrollPane 的滚动条在绘图超过面板大小时出现,并且能够垂直和水平滚动绘图。

我尝试咨询各种论坛和官方文档并尝试了一些方法(设置边框、首选大小等),但 none 似乎产生了预期的效果。

我有一个 JFrame(顺便说一句,带有 GridBagLayout。):

            JFrame frame1 = new JFrame("Application");
            frame1.setVisible(true);
            frame1.setMinimumSize(new Dimension(580,620));
            frame1.setResizable(false);
            frame1.setLocationRelativeTo(null);
            frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

相关组件是:

            JPanel panel1 = new JPanel();
            JScrollPane scrollPane = new JScrollPane(panel1);
            frame1.add(scrollPane, gbc_panel1); //added with layout constraints

J面板:

            panel1.setBackground(Color.BLACK);
            panel1.setPreferredSize(new Dimension(500,500));
            panel1.setMinimumSize(new Dimension(360,360));
            panel1.setMaximumSize(new Dimension(1000,1000));

滚动面板:

            scrollPane.setAutoscrolls(true);

动作事件的相关代码 绘图按钮的名称:

            Graphics g;
            g = panel1.getGraphics();
            panel1.paint(g);
            g.setColor(new Color(0,128,0));

            /* this is followed by some more code that 
            does the drawing of a maze with g.drawLine() methods */

代码完美地绘制了绘图,我似乎无法弄清楚如何进行滚动和动态调整大小。

如果有任何有用的意见或评论,我将不胜感激!

谢谢!

最终重写 paint 方法达到了@MadProgrammer 建议的目的。我只是希望我可以在不必定义我的自定义 JPanel class 的情况下进行绘画,但看起来它不能那样工作。

自定义 class 看起来像这样:

class Drawing extends JPanel {

int mazeSize;

public Drawing(JTextField jtf)
{
    try {
    this.mazeSize = Integer.parseInt(jtf.getText());
    }

    catch (Exception e) 
    {
        JOptionPane.showMessageDialog(this, "ERROR!  Invalid size value!");
    }
} // the constructor gets the size of the drawing from a textField

public Dimension getPreferredSize() {
    return new Dimension(mazeSize*10,mazeSize*10);
} //getPreferredSize - this method is used by the scroll pane to adjust its own size automatically

public void drawMaze (Graphics g) 
{
    /* some irrelevant code that does the desired drawing to the panel by calling g.drawLine()*/

} // drawMaze method that does the de facto drawing

@Override
public void paintComponent(Graphics g) 
{
    super.paintComponent(g);
    drawMaze(g);        
}// paintComponent() @Override method - this was the tricky part

}//Drawing JPanel subclass

还值得注意的是(如果像我这样的菜鸟碰巧遇到了这个问题),在动作事件中实例化新的 JPanel subclass 之后,我不得不将它添加到 JScrollPanel 中下面的方法,而不是简单地使用它的 add() 方法:

Drawing drawPanel = new Drawing(textfield1);
scrollPane.getViewport().add(drawPanel);

再次感谢您的建议!

一旦完成该程序(使用递归回溯算法的随机迷宫生成器),我将在我的 github profile.

提供源代码