简体   繁体   English

如何将JComponent添加到指定大小和位置的JFrame中?

[英]How to add JComponent into a JFrame with size and location specified?

I am trying to code in a way that when user clicks a button, a new row of jlabel and jtextfield will be added to the the gridlayout of the jframe. 我试图以一种方式编写代码,当用户单击一个按钮时,jlabel和jtextfield的新行将被添加到jframe的gridlayout中。 like this: 像这样:

Let's say the JFrame is 800x600, and the height of each row is 50, after I reach the 13th line, I want to add in a vertical scrolling bar. 假设JFrame是800x600,每行的高度是50,在我到达第13行后,我想添加一个垂直滚动条。 But now I can't seem to add the components correctly as I wished, I have also tried other layouts and apparently not working out. 但现在我似乎无法按照我的意愿正确添加组件,我也尝试了其他布局,显然没有成功。

import javax.swing.*;

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

public class Testing extends JFrame implements ActionListener
{
   public static int x =0;
   JPanel panel;

   public Testing()
   {
      super("Add component on JFrame at runtime");
      setLayout(new BorderLayout());
      panel=new JPanel();
      panel.setPreferredSize(new Dimension(800,600));
      panel.setAutoscrolls(true);
      panel.setLayout(new GridLayout(0,2,0,20));
      add(panel,BorderLayout.CENTER);
      JButton button=new JButton("CLICK HERE");
      add(button,BorderLayout.SOUTH);

      button.addActionListener(this);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setSize(500,500);
      setVisible(true);
      pack();
   }

   public void actionPerformed(ActionEvent evt)
   {
      JLabel jlbl1 = new JLabel("Row"+x);
      JTextField jtf =new JTextField(10);
      jtf.setMaximumSize(new Dimension(400,50));
      jlbl1.setMaximumSize(new Dimension(400,50));
      panel.add(jlbl1);
      panel.add(jtf);
      panel.revalidate();
      x++;

      validate();
   }

   public static void main(String[]args)
   {
      Testing test=new Testing();
   }
}

Edit: Thanks and Props to MadProgrammer for showing guidelines, this is what I wanted, just in case someone else face the same problem as I did: 编辑:感谢和道具向MadProgrammer展示指导方针,这就是我想要的,以防其他人遇到与我一样的问题:

Thanks to MadProgrammer and Andrew Thompson for showing guidelines. 感谢MadProgrammer和Andrew Thompson展示指南。 After some tweaks, this is what I wanted. 经过一些调整,这就是我想要的。

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
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.JScrollPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TableExample {

    public static void main(String[] args) {
        new TableExample();
    }

    public TableExample() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {
        public GridBagConstraints c = new GridBagConstraints();


        private JPanel fieldsPanel;
        private int row;

        public TestPane() {
            c.gridx =0;
            c.gridy =0;
            c.fill = GridBagConstraints.NONE;
            setLayout(new BorderLayout());

            fieldsPanel = new JPanel(new GridBagLayout());

            add(new JScrollPane(fieldsPanel));

            JButton btn = new JButton("Add");
            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    fieldsPanel.add(new JLabel("Row " + (++row)),c);
                    c.gridx++;
                    fieldsPanel.add(new JTextField(10),c);
                    fieldsPanel.revalidate();
                    c.gridy++;
                    c.gridx--;
                }
            });
            add(btn, BorderLayout.SOUTH);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }
    }

}

Update with JTable example 使用JTable示例更新

表

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;

public class TableExample {

    public static void main(String[] args) {
        new TableExample();
    }

    public TableExample() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private DefaultTableModel model;

        public TestPane() {
            setLayout(new BorderLayout());
            model = new DefaultTableModel(
                    new Object[]{"Row", "Value"}, 
                    0);
            JTable table = new JTable(model);
            add(new JScrollPane(table));

            JButton btn = new JButton("Add");
            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    int count = model.getRowCount();
                    model.addRow(new Object[]{count + 1, ""});
                }
            });
            add(btn, BorderLayout.SOUTH);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }
    }

}

Updated with JScrollPane example 更新了JScrollPane示例

领域

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
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.JScrollPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TableExample {

    public static void main(String[] args) {
        new TableExample();
    }

    public TableExample() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JPanel fieldsPanel;
        private int row;

        public TestPane() {
            setLayout(new BorderLayout());

            fieldsPanel = new JPanel(new GridLayout(0, 2));
            add(new JScrollPane(fieldsPanel));

            JButton btn = new JButton("Add");
            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    fieldsPanel.add(new JLabel("Row " + (++row)));
                    fieldsPanel.add(new JTextField(10));
                    fieldsPanel.revalidate();
                }
            });
            add(btn, BorderLayout.SOUTH);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }
    }

}

Updated with GridBagLayout example 更新了GridBagLayout示例

GridBagLayout的

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
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.JScrollPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TableExample {

    public static void main(String[] args) {
        new TableExample();
    }

    public TableExample() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JPanel fieldsPanel;
        private JPanel filler;
        private int row;

        public TestPane() {
            setLayout(new BorderLayout());

            filler = new JPanel();
            fieldsPanel = new JPanel(new GridBagLayout());
            add(new JScrollPane(fieldsPanel));

            JButton btn = new JButton("Add");
            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    fieldsPanel.remove(filler);
                    GridBagConstraints gbc = new GridBagConstraints();
                    gbc.insets = new Insets(2, 2, 2, 2);
                    gbc.gridx = 0;
                    gbc.gridy = row;
                    gbc.fill = GridBagConstraints.HORIZONTAL;
                    fieldsPanel.add(new JLabel("Row " + (++row)), gbc);
                    gbc.gridx++;
                    gbc.weightx = 1;
                    fieldsPanel.add(new JTextField(10), gbc);

                    gbc.gridy++;
                    gbc.weighty = 1;
                    fieldsPanel.add(filler, gbc);
                    fieldsPanel.revalidate();
                }
            });
            add(btn, BorderLayout.SOUTH);
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM