0

您好,我想在运行时在面板上创建文本框,即当我在两个文本框中输入 3 和 4 时,它将在 Swing 中的按钮单击事件中打印 3 行和 4 列的文本框。这是我的代码。

JFrame jf=new JFrame();
JPanel jp=new JPanel();
JTextField jt1=new JTextField();
JTextField jt2=new JTextField();
JLabel jl1=new JLabel("Enter Row");
JLabel jl2=new JLabel("Enter Column");
JButton jb1=new JButton("OK");
JButton jb2=new JButton("Cancel");

jf.setContentPane(jp);
jp.setLayout(null);
jp.setBackground(Color.CYAN);
jp.add(jb1);
jp.add(jt1);
jp.add(jt2);
jp.add(jl1);
jp.add(jl2);
jp.add(jb2);

jf.setVisible(true);
jf.setSize(500,500);

jt1.setBounds(200,20,50,30);
jt2.setBounds(200,60,50,30);

jl1.setBounds(90, 20, 80, 30);
jl2.setBounds(90,60,80,30);
jb1.setBounds(150, 100, 80, 80);

jb1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
}
4

2 回答 2

0

actionPerformed()您可以根据从文本框中获取的值在方法中使用循环

于 2013-03-25T10:29:58.547 回答
0

这是一个粗略的代码,没有任何验证和布局考虑。您可以使用它来进一步满足您的要求。

public class ClsCreateTextBoxes extends javax.swing.JFrame{
    private javax.swing.JPanel jpInputPanel = null;
    private javax.swing.JTextField jtfRows = null;
    private javax.swing.JTextField jtfColumns = null;
    private javax.swing.JButton jbCreateMatrix = null;
    private javax.swing.JPanel jpMatrixPanel = null;

    public ClsCreateTextBoxes(){
        setSize(400, 400);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        getContentPane().setLayout(new java.awt.BorderLayout());
        jpInputPanel = new javax.swing.JPanel(new java.awt.FlowLayout());
        jtfRows = new javax.swing.JTextField(10);
        jpInputPanel.add(jtfRows);
        jtfColumns = new javax.swing.JTextField(10);
        jpInputPanel.add(jtfColumns);
        jbCreateMatrix = new javax.swing.JButton("Create");
        jbCreateMatrix.addActionListener(new java.awt.event.ActionListener(){
            public void actionPerformed(java.awt.event.ActionEvent ae){
                //  Assuming proper number is given
                jpMatrixPanel.setLayout(new java.awt.GridLayout(Integer.parseInt(jtfRows.getText()), Integer.parseInt(jtfColumns.getText())));
                for(int rowIndex = 0; rowIndex < Integer.parseInt(jtfRows.getText()); rowIndex ++){
                    for(int columnIndex = 0; columnIndex < Integer.parseInt(jtfColumns.getText()); columnIndex ++){
                        jpMatrixPanel.add(new javax.swing.JTextField(10));
                        pack();
                    }
                }
            }
        });
        jpInputPanel.add(jbCreateMatrix);
        getContentPane().add(jpInputPanel, java.awt.BorderLayout.NORTH);
        jpMatrixPanel = new javax.swing.JPanel();
        getContentPane().add(jpMatrixPanel, java.awt.BorderLayout.SOUTH);
        pack();
    }
    public static void main(String[] args){
        ClsCreateTextBoxes createdTextBoxes = new ClsCreateTextBoxes();
        createdTextBoxes.setVisible(true);
    }
}
于 2013-03-25T11:54:52.600 回答