How to resize frame dynamically with Timer?

萝らか妹 提交于 2019-12-02 00:41:59

You need to re-pack your JFrame to resize it. For instance at the end of your ActionListener:

Window win = SwingUtilities.getWindowAncestor(panel);
win.pack();

A question for you though: Why in heaven's name is your class extending JApplet and not JPanel? Or if it needs to be an applet, why are you stuffing it into a JFrame?


Edit
Regarding your comment:

Wouldn't it usually be extending JFrame not JPanel? I'm stuffing it into a JFrame to allow it to run as an application as well as an applet. That's how 'Introduction to Java Programming' tells me how to do it :p Adding your code at the end of the actionPerformed method didn't do anything for me ;o

Most of your GUI code should be geared towards creating JPanels, not JFrames or JApplets. You can then place your JPanels where needed and desired without difficulty. Your book has serious issues and should not be trusted if it is telling you this.


Edit 2
Works for me:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

@SuppressWarnings("serial")
public class ShrinkingGui extends JPanel {
   private static final int INIT_W = 400;
   private static final int INIT_H = INIT_W;
   private static final int TIMER_DELAY = 20;
   private int prefW = INIT_W;
   private int prefH = INIT_H;

   public ShrinkingGui() {
      new Timer(TIMER_DELAY, new TimerListener()).start();;
   }

   public Dimension getPreferredSize() {
      return new Dimension(prefW, prefH);
   }

   private class TimerListener implements ActionListener {
      @Override
      public void actionPerformed(ActionEvent e) {
         if (prefW > 0 && prefH > 0) {
            prefW--;
            prefH--;
            Window win = SwingUtilities.getWindowAncestor(ShrinkingGui.this);
            win.pack();
         } else {
            ((Timer)e.getSource()).stop();
         }
      }
   }

   private static void createAndShowGUI() {
      ShrinkingGui paintEg = new ShrinkingGui();

      JFrame frame = new JFrame("Shrinking Gui");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(paintEg);
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGUI();
         }
      });
   }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!