强制 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();
}
相关文章