我正在为Java中的数据结构制作GUI。我想要一个功能,每当用户单击位于表单顶部的最大化按钮时,随着窗口的扩展,组件和表单中的所有内容也应重新调整大小,反之亦然。我已经搜索了很多,但是找不到解决方案。

如何缩放GUI?

最佳答案

您能帮我一些简短的代码吗,例如当按下最大化按钮时如何调整工具栏的大小。


我会做的更好这是一个简短的代码示例,其中显示了其中5个具有不同的调整大小行为,具体取决于它们在BorderLayout中的放置位置。



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

public class ResizableToolBars {

    public static void showFrameWithToolBar(String toolBarPosition) {
        // the layout is important..
        JPanel gui = new JPanel(new BorderLayout());

        JToolBar tb = new JToolBar();
        // ..the constraint is also important
        gui.add(tb, toolBarPosition);
        tb.add(new JButton("Button 1"));
        tb.add(new JButton("Button 2"));
        tb.addSeparator();
        tb.add(new JButton("Button 3"));
        tb.add(new JCheckBox("Check 1", true));

        JFrame f = new JFrame(toolBarPosition + " Sreeeetchable Tool Bar");
        f.setContentPane(gui);
        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        f.setLocationByPlatform(true);
        f.pack();

        // we don't normally set a size, this is to show where
        // extra space is assigned.
        f.setSize(400,120);
        f.setVisible(true);
    }
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run() {
                showFrameWithToolBar(BorderLayout.PAGE_START);
                showFrameWithToolBar(BorderLayout.PAGE_END);
                showFrameWithToolBar(BorderLayout.LINE_START);
                showFrameWithToolBar(BorderLayout.LINE_END);
                showFrameWithToolBar(BorderLayout.CENTER);
            }
        });
    }
}



调整大小时,请仔细查看每个对象的效果。
在JavaDocs中查看BorderLayout
进行Java教程的Laying Out Components Within a Container课程。


如果之后再回到Nested Layout Example,您应该能够弄清楚如何将较小的组件组​​合在一起,每个组件在父容器的一个区域中以各自的布局(在面板中)放置。

08-06 03:15