java按钮插入文本,Java-如何通过单击按钮添加更多文本字段?

I have created a frame in Java which has some textfields and buttons in it. Assuming that user wants more textfields (for example to add more data), I want to put a button and when a user clicks the button, then a new textfield should appear. then user can fill data in it and again by clicking that button another textfield should appear.

How can I do this ? What code I need to write for the button to show more and more text fields by clicking button?

Thank you !

解决方案

It would be wise that instead of adding components to your JFrame directly, you add them to a JPanel. Though related to your problem, have a look at this small example, hopefully might be able to give you some hint, else ask me what is out of bounds.

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class JFrameExample

{

private JFrame frame;

private JButton button;

private JTextField tfield;

private String nameTField;

private int count;

public JFrameExample()

{

nameTField = "tField";

count = 0;

}

private void displayGUI()

{

frame = new JFrame("JFrame Example");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLayout(new GridLayout(0, 1, 2, 2));

button = new JButton("Add JTextField");

button.addActionListener(new ActionListener()

{

@Override

public void actionPerformed(ActionEvent ae)

{

tfield = new JTextField();

tfield.setName(nameTField + count);

count++;

frame.add(tfield);

frame.revalidate(); // For JDK 1.7 or above.

//frame.getContentPane().revalidate(); // For JDK 1.6 or below.

frame.repaint();

}

});

frame.add(button);

frame.pack();

frame.setLocationByPlatform(true);

frame.setVisible(true);

}

public static void main(String... args)

{

SwingUtilities.invokeLater(new Runnable()

{

@Override

public void run()

{

new JFrameExample().displayGUI();

}

});

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值