在
Linux平台上,Frame :: getBounds和Frame :: setBounds不能一致地工作.这已在2003年(!)报道,见这里:
为方便起见,我简化了导致错误的声明代码,并将其粘贴为:
import java.awt.Button;
import java.awt.Frame;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/** Demonstrates a bug in the java.awt.Frame.getBounds() method.
* @author Mirko Raner,PTSC
* @version 1.0 (2003-01-22) **/
public class GetBoundsBug extends Frame implements ActionListener {
public static void main(String[] arg) {
GetBoundsBug frame = new GetBoundsBug();
Button button = new Button("Click here!");
button.addActionListener(frame);
frame.add(button);
frame.setSize(300,300);
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent event) {
Rectangle bounds = getBounds();
bounds.y--;
setBounds(bounds);
bounds.y++;
setBounds(bounds);
}
}
意外行为:点击按钮后窗口略微移动! (在我的系统上每次点击28个像素.)
这种行为已存在了13年,因此官方可能不会有任何变化.
有没有人有这个bug的解决方法?具体来说,我想在所有平台上可靠地存储和恢复前一个位置的窗口/框架/对话框.
PS:我的Java安装是jdk1.8.0_102,适用于Oracle在Ubuntu 16 Linux上的amd64.由于我最近从Windows迁移到Ubuntu,我知道在Windows上,上面的代码按预期工作.
使用SwingWorker适应Swing会产生相同的效果:
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingWorker;
public class GetBoundsBug extends JFrame implements ActionListener {
public static void main(String[] arg) {
GetBoundsBug myJFrame = new GetBoundsBug();
JButton myJButton = new JButton("Click here!");
myJButton.addActionListener(myJFrame);
myJFrame.setContentPane(myJButton);
myJFrame.setSize(300,300);
myJFrame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent event) {
SwingWorker mySwingWorker = new SwingWorker() {
@Override
public Void doInBackground() {
Rectangle myRectangle = getBounds();
myRectangle.y--;
setBounds(myRectangle);
myRectangle.y++;
setBounds(myRectangle);
return null;
}
};
mySwingWorker.execute();
}
}