强制 JFrame 在 setResizable(false) 之后不调整大小.命令不起作用 [英] Forcing JFrame to not resize after setResizable(false). Command wont work

查看:47
本文介绍了强制 JFrame 在 setResizable(false) 之后不调整大小.命令不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I have a simple Atari breakout program, and long story short, one of my powerups is to allow the user to resize the window for a few seconds, then make the window non-resizable again.Everything works fine, and the window goes from being not-resizable, to being resizable for a few seconds. What's supposed to happen, is after the few seconds are up, the window should stop accepting input for resizing the window (IE: should not be resizable). The only problem, is that whenever it's supposed to be set to non-resizable, if you keep your cursor dragging on the window to resize it, it keeps resizing. It will only activate the non-resizable state of the window after you let go of the window. My question, is how do I make this happen before you let go of the window, taking away your control of resizing, once the timer is up?

P.S: I want to program to immediately keep you from resizing the window once the command is called, not waiting for you to let go of the mouse. Any suggestions?

Here is a simplified case: (You are given 6 seconds to resize the window and play with it)

package test;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;

public class Test {

    public static void main(String[] args) {        
        JFrame testFrame = new JFrame();
        testFrame.setResizable(true);
        testFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        long endingTime = System.currentTimeMillis() + 6000;
        Timer testTimer = new Timer(100, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if((endingTime - System.currentTimeMillis()) < 0){
                    testFrame.setResizable(false);
                }
            }
        });
        testFrame.setVisible(true);
        testTimer.start();
    }
}

解决方案

Use Java's Robot class to force a mouse release. I've modified your example code below:

public static void main(String[] args) {        
  JFrame testFrame = new JFrame();
  testFrame.setResizable(true);
  testFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  Timer testTimer = new Timer(6000, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
            testFrame.setResizable(false);
      Robot r;
      try {
        r = new Robot();
        r.mouseRelease( InputEvent.BUTTON1_DOWN_MASK);
      } catch (AWTException ex) {
        ex.printStackTrace();
      }
    }

  });
  testFrame.setVisible(true);
  testTimer.start();
}

这篇关于强制 JFrame 在 setResizable(false) 之后不调整大小.命令不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆