为什么我的Java GUI会“跳转"?第一次移动时? [英] Why does my java gui "jump" when moving it the first time?

查看:76
本文介绍了为什么我的Java GUI会“跳转"?第一次移动时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的Java gui(下面的代码),由于某些原因,当我显示它时,它将在我第一次尝试移动或调整大小时跳回"它的原始位置.因此,基本上,我将必须两次移动gui才能使其移动一次,因为在我第一次释放鼠标时,它就立即回到原始位置.

I have a simple java gui (code below) which for some reason when displayed, will "jump" back to it's original position the first time I try to move or resize it. So basically I will have to move the gui twice to get it to move once because as soon as I release the mouse the first time it snaps back to where it originally came up.

import javax.swing.*;

public class JFrameTester {

  public static void main(String[] args) {

    JFrame f = new JFrame("A JFrame");
    f.setSize(250, 250);
    f.setLocation(300,200);
    f.getContentPane().add(new JTextArea(10, 40));    
    //f.pack();    
    f.setVisible(true);
    //f.validate();
  }

}

我正在具有Java 1.6的 GNU Linux上运行.我将显示导出回Windows计算机,并想知道它是否与X11转发有关,因为在Windows中运行gui时,它不显示此行为.但是,当我在Fedora Linux盒(带有Java 1.7)上运行此gui时,它根本不显示此行为-无论是否导出显示.

I am running on GNU Linux with java 1.6. I am exporting the display back to my Windows machine and wondering if it has something to do with the X11 forwarding because it does not show this behavior when I run the gui in Windows. However, when I run this gui on a Fedora Linux box (with java 1.7) it does not show this behavior at all - whether exporting the display or not.

推荐答案

一些问题很明显:

  • Construct and manipulate Swing GUI objects only on the event dispatch thread. Failing to do so creates a race condition that may be obscure until a different platform or network latency exposes it.

使用pack(),它使Window的大小适合其子组件的首选大小和布局."否则,无效的Container在移动或调整大小时将得到验证.当过早可见的组件移动到定义的位置时,它们似乎跳起来".

Use pack(), which "Causes this Window to be sized to fit the preferred size and layouts of its subcomponents." Failing to do so causes the invalid Container to be validated when moved or resized. When the prematurely visible components move to the defined positions, they appear to "jump."

使setVisible()会影响初始外观的 last 操作.

Make setVisible() the last operation that affects the initial appearance.

以下示例结合了这些建议:

The following example combines these suggestions:

import java.awt.EventQueue;
import javax.swing.*;

public class JFrameTester {

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame f = new JFrame("A JFrame");
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                f.add(new JScrollPane(new JTextArea(10, 40)));
                f.pack();
                f.setLocationByPlatform(true);
                f.setVisible(true);
            }
        });
    }
}

这篇关于为什么我的Java GUI会“跳转"?第一次移动时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆