我正在尝试将JDialog保持在JFrame内部,无论JFrame是移动还是调整大小。
基本上,我有一个类(这不是真正的代码,只是一个例子)
import javax.swing.*;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.Dimension;
import java.awt.Color;
public class HelloWorldSwing extends ComponentAdapter implements AncestorListener {
private JDialog dialog;
private JFrame frame;
@Override
public void componentResized( ComponentEvent event ) {
//This value does not hcange when dragged from the left or right
System.err.println( " Location " + frame.getLocationOnScreen() );
recenter();
}
@Override
public void ancestorAdded( AncestorEvent evt ) {
}
@Override
public void ancestorRemoved( AncestorEvent evt ) {
}
@Override
public void ancestorMoved( AncestorEvent evt ) {
//This value does not hcange when dragged from the left or right
System.err.println( " Location " + frame.getLocationOnScreen() );
recenter();
}
private void recenter() {
dialog.setLocationRelativeTo( frame.getRootPane() );
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private void createAndShowGUI() {
//Create and set up the window.
frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getRootPane().addAncestorListener( this );
frame.getRootPane().setBackground( Color.WHITE );
frame.addComponentListener( this );
frame.setMinimumSize( new Dimension( 500, 500 ) );
frame.setMaximumSize( new Dimension( 500, 500 ) );
dialog = new JDialog();
dialog.setResizable( true );
dialog.setAlwaysOnTop( true );
dialog.setVisible( true );
dialog.setMaximumSize( new Dimension( 200, 200 ) );
dialog.setMinimumSize( new Dimension( 200, 200 ) );
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
HelloWorldSwing swing = new HelloWorldSwing();
swing.createAndShowGUI();
}
});
}
}
当从左侧或顶部调整JFrame的大小时,屏幕上的位置会发生变化,但getLocationOnScreen()不会更改其结果。似乎getLocationOnScreen应该因左上角由于调整大小而发生变化而改变。
我错过了什么?感谢。
更新::
此代码似乎在Windows上正常运行,但在Fedora 21,java 7上无法正常运行