如何动态更改Swing JFrame大小

时间:2011-12-02 20:58:52

标签: java swing

我想要实现的是

  1. 创建一个自定义组件(mypanel),该组件JPanel扩展JLabel,其中JButtonGridBagLayout通过JFrame排列。

  2. mypanel在垂直堆叠中显示多个mypanel并使其高度相应更改,具体取决于添加JFrame的数量(宽度) mypanel = JFrame的宽度。

  3. mypanel的高度大于屏幕高度时,会显示一个垂直滚动条以进行滚动

  4. 我已成功创建JFrame,但在添加 this.window = new JFrame("ADesktop Notifications"); this.window_panel = new JPanel(); this.window_panel_scroll = new JScrollPane(this.window_panel); this.window.setBounds(this.top_left_x,this.top_left_y, this.width, this.height); this.window_panel.setLayout(new FlowLayout()); this.window_panel.setAutoscrolls(true); this.window.add(this.window_panel); 并设置其大小,滚动条部分方面遇到了很多麻烦。

    这是我的jframe的代码

    {{1}}

1 个答案:

答案 0 :(得分:2)

尝试这个例子(用于动态扩展JFrame)。

enter image description here enter image description here

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class DynaFrame extends JFrame{

    private JPanel basePnl = new JPanel();

    public DynaFrame(){
        this.setTitle("Dynamic panel addition");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //this.setSize(600, 700);
        this.add(getMainPanel());
        this.setLocationRelativeTo(null);
        this.pack();
        this.setVisible(true);
    }

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

    public JPanel getMainPanel(){
        basePnl.setLayout(new BoxLayout(basePnl, BoxLayout.Y_AXIS));
        basePnl.add(getRowPanel());
        return basePnl;
    }

    public JPanel getRowPanel(){
        JPanel pnl = new JPanel();
        GridLayout gLayout = new GridLayout();
        gLayout.setColumns(4);
        gLayout.setRows(1);
        pnl.setLayout(gLayout);
        pnl.add(new JLabel("Filetype"));
        pnl.add(new JTextField());
        pnl.add(new JButton("Browse"));
        JButton addBtn = new JButton("Add");
        addBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                basePnl.add(getRowPanel());
                DynaFrame.this.pack();
            }
        });
        pnl.add(addBtn);
        return pnl;
    }
}