Reputation: 5092
I created a JDialog
which I want to move and resize. My program draws JDialog
on the screen. When the user clicks it, it should stretch to the width of the screen and then gain height. I tried it like this.
for(int i = 150; i <= width; i += 3) {
dialog.setSize(i, 80);
try {
Thread.sleep(0, 1);
} catch(Exception e2) {}
}
for(int i = 80; i <= 200; i++) {
dialog.setSize(width, i);
try {
Thread.sleep(1);
} catch(Exception e3) {}
}
When the code is executed, it will take a while and then the JDialog will be shown stretched immediately. No expanding is shown.
Well, when the user clicks the dialog again, it will reverse the opening animation and close.
for(int i = 200; i >= 80; i--) {
newMsg.setSize(width, i);
try {
Thread.sleep(0, 1);
} catch(Exception e4) {}
}
for(int i = 0; i >= -width; i -= 3) {
newMsg.setLocation(i, 100);
try {
Thread.sleep(0, 1);
} catch(Exception e5) {}
}
This one works correctly. The movement is able to be seen. As far as I understand, these codes are otherwise identical except they are reversed. Why doesn't the opening work as expected but the closing does?
Upvotes: 0
Views: 781
Reputation: 159754
Don't call Thread.sleep
in the EDT
. This causes the UI to "freeze". You could use a Swing Timer here instead. Here is how the initial "expand" might be handled::
Timer timer = new Timer(0, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateDialogSize();
}
});
timer.setDelay(5); // short delay
timer.start();
Update dialog:
void updateDialogSize() {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
if (dialog.getWidth() < screenSize.getWidth()) { // 1st size width
dialog.setSize(dialog.getWidth() + 5, dialog.getHeight());
} else if (dialog.getHeight() < screenSize.getHeight()) { // then size height
dialog.setSize(dialog.getWidth(), dialog.getHeight() + 5);
} else {
timer.stop(); // work done
}
dialog.setLocationRelativeTo(myFrame);
}
I'll leave the dialog "contraction" as an excercise ;)
Upvotes: 4