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

问题描述 投票:0回答:1

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

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

我将不胜感激任何有用的评论或评论!

谢谢!

java swing jpanel drawing jscrollpane
1个回答
0
投票

最终重写油漆方法就像@MadProgrammer建议的那样。我只是希望我可以在不必定义我的自定义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上提供源代码。

© www.soinside.com 2019 - 2024. All rights reserved.