问题
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();
}
}
回答1:
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();
}
回答2:
Well one way I could think of is setting the size back after a resizing event if the frame is not resizable.
Not sure how well it would work though.
frame.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
if (!frame.isResizable()) {
frame.setSize(...);
}
}
});
回答3:
Have you tried revalidating the JFrame immediately after the power up ends? This will most likely solve your issue (though I wouldn't know given that you have neither an SSCCE, or an MVCE). I hope this helps, and best of luck.
来源:https://stackoverflow.com/questions/29321523/forcing-jframe-to-not-resize-after-setresizablefalse-command-wont-work