每次我运行这段代码时,输出都是一个对话框出现在屏幕的左上角,但标题不显示。
有什么办法可以改变这个,让对话框出现在中间并且大小可以接受吗?
代码:
public class Test {
public static void main(String[] args) {
JFrame f = new JFrame();
final JDialog dialog = new JDialog(f, "Hello world", true);
Timer timer = new Timer(10000, new ActionListener() {
public void actionPerformed(ActionEvent e) {
dialog.setVisible(false);
dialog.dispose();
}
});
timer.setRepeats(false);
timer.start();
dialog.setVisible(true);
System.out.println("Dialog closed");
}
}
最佳答案
当然。默认情况下,JDialog
(或 JFrame
)会像那样显示。您需要对其设置界限:
dialog.setBounds(xPosition, yPosition, width, height);
但是,如果你只是为它设置一些魔数(Magic Number),这将无法很好地扩展到其他系统。相反,获取屏幕尺寸,并以此为出发点:
//static and final because no reason not to be. Insert this at the class definition
static final Dimension SCREEN_DIMENSION = Toolkit.getDefaultToolkit().getScreenSize();
...
//I'd also make this static and final and insert them at the class definition
int dialogWidth = SCREEN_DIMENSION.width / 4; //example; a quarter of the screen size
int dialogHeight = SCREEN_DIMENSION.height / 4; //example
...
int dialogX = SCREEN_DIMENSION.width / 2 - dialogWidth / 2; //position right in the middle of the screen
int dialogY = SCREEN_DIMESNION.height / 2 - dialogHeight / 2;
dialog.setBounds(dialogX, dialogY, dialogWidth, dialogHeight);
或者,如果您将组件添加到 JDialog
,然后调用
dialog.pack();
对话框现在将是容纳组件的最小尺寸。如果您使用的组件应该紧密包装,请使用此方法;那么您就不必煞费苦心地手动构建正确的宽度和高度。
关于java - JDialog 弹出窗口太小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21084312/