简体   繁体   English

调整 jframe 大小时画布不调整大小

[英]canvas not resizing when jframe is resized

when i resize the window it resizes properly but the canvas that I'm using to hold the image doesn't resize with it.当我调整窗口大小时,它会正确调整大小,但我用来保存图像的画布不会随之调整大小。

heres the code:继承人的代码:

  image = new BufferedImage(gc.width,gc.height,BufferedImage.TYPE_INT_RGB);
    canvas = new Canvas();
    Dimension s = new Dimension((int)(gc.width*gc.scale),(int)(gc.height*gc.scale));
    canvas.setPreferredSize(s);
    canvas.setMaximumSize(s);
    canvas.setMinimumSize(s);

    frame = new JFrame(gc.title);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLayout(new BorderLayout());
    frame.add(canvas,BorderLayout.CENTER);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setResizable(true);
    frame.setVisible(true);

    canvas.createBufferStrategy(2);
    bs = canvas.getBufferStrategy();
    g = bs.getDrawGraphics();
}

public void update() {
    Dimension s = frame.getSize();
    canvas.setPreferredSize(s);
    canvas.setMaximumSize(s);
    canvas.setMinimumSize(s);

    g.drawImage(image,0, 0, canvas.getWidth(), canvas.getHeight(),null);
    bs.show();
}

help is appreciated.帮助表示赞赏。

How do you invoke update?你如何调用更新?

You should implement and add a ComponentListener (or ComponentAdapter) to the JFrame, in the componentResized method, you invoke update.您应该实现一个 ComponentListener(或 ComponentAdapter)并将其添加到 JFrame,在 componentResized 方法中,您调用更新。 Something like:就像是:

   this.addComponentListener(new ComponentAdapter(){
       componentResized(ComponentEvent e){
         //UPDATE YOUR CANVAS HERE
       }
   });

Another way is overriding update(Graphic) in your JFrame:另一种方法是在您的 JFrame 中覆盖 update(Graphic):

public class MyWindow extends JFrame{

   @Override
   public void update(Graphics g){
      super.update(g);
      //UPDATE YOUR CANVAS HERE
   }
}

I'd suggest switching to JavaFX.我建议切换到 JavaFX。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM