ankit
ankit

Reputation: 77

How to Change a Swing JFrame Size on the fly

What I am trying to achieve is

  1. Create a custom component (mypanel) that extends JPanel with JLabels and JButtons in it arranged via GridBagLayout.

  2. Have a JFrame that would display multiple mypanel in a vertical stack and have its height change accordingly, depending on the number of mypanels added to it (width of the JFrame = width of mypanel).

  3. When the JFrame's height becomes greater than the screen height, have a vertical scrollbar appear for scrolling

I have created mypanel successfully but having lot of trouble with the adding to the JFrame and setting its size, scrollbars part.

this is the code for my 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);

Upvotes: 2

Views: 3395

Answers (1)

bragboy
bragboy

Reputation: 35542

Try this example out (for dynamic expanding 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;
    }
}

Upvotes: 2

Related Questions