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

时间:2019-01-20 23:23:59

标签: java swing jpanel drawing jscrollpane

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

我尝试过与各种论坛和官方文档进行协商,并尝试了一些方法(设置边界,首选大小等),但似乎没有一种方法可以产生预期的效果。

我有一个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

JPanel:

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

JScrollPane:

            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 */

该代码可以完美地绘制图形,但我似乎无法弄清楚如何实现滚动和动态调整大小。

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

谢谢!

1 个答案:

答案 0 :(得分:0)

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

自定义类如下:

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子类之后,我必须以以下方式将其添加到JScrollPanel中,只需使用其add()方法即可:

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

再次感谢您的建议!

完成程序(使用递归回溯算法的随机迷宫生成器)后,我将在github profile上提供源代码。