我如何制作像附加的gif一样的布局?

时间:2015-07-16 12:34:07

标签: java swing layout-manager

我的问题是关于Java Swing中的布局。

我想制作如下所示的屏幕。我在youtube上看到了这个视频,并制作了我想要的部分的gif。

我想要2个面板和一个这样的按钮:

enter image description here

当我点击按钮时,JPanel将被隐藏,JTable的宽度将像这样的html / css 100%; (当再次点击按钮时,将显示JPanel等。)

enter image description here

我该怎么做?我应该使用哪种布局?

1 个答案:

答案 0 :(得分:4)

有多种方法可以执行此操作,但这是一个使用BorderLayout作为主要布局的示例,并将按钮置于左对齐FlowLayout

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;

public class LayoutDemo {
    private LayoutDemo() {
        JFrame frame = new JFrame("Demo");
        frame.setLocationByPlatform(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel buttonHolder = new JPanel(new FlowLayout(FlowLayout.LEADING));
        frame.add(buttonHolder, BorderLayout.NORTH);
        JButton button = new JButton("Toggle visibility");
        buttonHolder.add(button);

        final JPanel left = new JPanel();
        left.setPreferredSize(new Dimension(100, 200));
        left.setBackground(Color.BLUE);
        frame.add(left, BorderLayout.LINE_START);

        JLabel table = new JLabel("This pretends to be a table", SwingConstants.CENTER);
        table.setPreferredSize(new Dimension(400, 200));
        frame.add(table);

        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                left.setVisible(!left.isVisible());
            }
        });

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new LayoutDemo();
            }
        });
    }
}

我使用setPreferredSize()为组件提供了一些合理的默认大小,但通常它应该由布局管理器根据子组件的大小自动计算,或者在自定义组件的情况下,您应该重写{ {1}}返回适合该组件的内容。

结果如下:

Image of the sample program

相关问题