如何使内框架在主框架中心



我正在做一个java项目。我已经创建了带有桌面窗格的主框架和几个内部框架。我想让所有j个内部帧居中。谁能给我个建议,如何居中?谢谢。

试试这个逻辑。我只对一个JInternalFrame做了这个。

import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JDesktopPane;
import javax.swing.SwingUtilities;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.Component;
public final class CenterChild extends JFrame{
    private JDesktopPane   contentPane;
    private JInternalFrame child;
    @Override
    public void frameInit(){
        super.frameInit();
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(0,0,500,500);
        this.selfInitialize();
    }
    private void selfInitialize(){
        contentPane = new JDesktopPane();
        child       = new JInternalFrame("Centered Child");
        child.setClosable(true);
        child.setVisible(true);
        child.setSize(300,200);
        //Centering the JInternalFrame
        child.setLocation((getWidth() - child.getWidth())/2, (getHeight() - child.getHeight())/2);
        contentPane.add(child);
        this.setContentPane(contentPane);
        addComponentListener(new ResizeEventHandler());
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(()->{ new CenterChild();});
    }
    //Code that re positions JInternalFrame while main window size changes
    private class ResizeEventHandler extends ComponentAdapter{
        @Override
        public void componentResized(ComponentEvent e){
            Component invoker = e.getComponent();
            //re positioning the JInternalFrame to the main window's center
            child.reshape((invoker.getWidth() - child.getWidth())/2, (invoker.getHeight() - child.getHeight())/2,300,200);          
        }
    }
}

相关内容

  • 没有找到相关文章

最新更新