java - JDialog 弹出窗口太小

标签 java swing timer jdialog preferredsize

每次我运行这段代码时,输​​出都是一个对话框出现在屏幕的左上角,但标题不显示。

有什么办法可以改变这个,让对话框出现在中间并且大小可以接受吗?

代码:

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 only appears at the top right hand corner instead of center of screen

最佳答案

当然。默认情况下,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/

相关文章:

java - RMI:将非远程对象类传递到服务器

java - 包本地类的 Class literal 和 Class.forName 的不同行为

java - 使用图像而不是 JDialog/frame 来容纳 swing 组件?

android - Activity 更改时如何设置计时器?

android - 延迟 Action 和 BroadcastReceiver

java - 用于使用 XML w/UI 和外部数据库调用的 API

java - 处理 3 中的音频输入流

java - JTABLE,当我清除所有行时,如果选择了一行,该行仍然出现在那里

java - 在 JSplitPane 上设置分隔线位置不起作用

timer - 如何使用 Tokio 产生许多可取消的计时器?