Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
834 views
in Technique[技术] by (71.8m points)

linux - Why does my java gui "jump" when moving it the first time?

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();
  }

}

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Several problems are apparent:

  • 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.

  • 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."

  • 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);
            }
        });
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...