开发者

Swing Jpanel Autofit contents issue

I want to achieve following screen design using Swing:

-----------------------------------------------
File Type 1:   JTextfield1  Browse Button1  ADD ROW BUTTON
               JTextfield2  Bro开发者_如何学编程wse Button2

File Type 2:   JTextfield3  Browse Button3  ADD ROW BUTTON
               JTextfield4  Browse Button4

File Type 1:   JTextfield5  Browse Button5  ADD ROW BUTTON
               JTextfield6  Browse Button6

On click of ADD ROW BUTTON a new set of JTextfield & Browse Button gets added at appropriate file type section,Each file type section is a Jpanel having miglayout, but the problem is Upon addition of new row the Jpanel does not expand and thus new row shows up only partially and the sections dowm of the screen does not gets pushed down.

How to go about achieving the same. Please help.

Rajiv Jha


I don't exactly understand what you need. But try this example out. It should do what you're looking for.

Swing Jpanel Autofit contents issue

Swing Jpanel Autofit contents issue

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;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜