使用按钮将JTextField值添加到字符串数组的步骤如下:
以下是一个示例代码,演示如何使用按钮将JTextField值添加到字符串数组:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
public class TextFieldArrayExample {
public static void main(String[] args) {
JFrame frame = new JFrame("TextField Array Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextField textField = new JTextField(20);
JButton addButton = new JButton("Add to Array");
ArrayList<String> stringArray = new ArrayList<>();
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String text = textField.getText();
if (!text.isEmpty()) {
stringArray.add(text);
textField.setText("");
System.out.println("Value added to array: " + text);
}
}
});
frame.getContentPane().add(textField);
frame.getContentPane().add(addButton);
frame.getContentPane().setLayout(new FlowLayout());
frame.pack();
frame.setVisible(true);
}
}
在这个示例中,创建了一个包含一个文本框和一个按钮的用户界面。当点击按钮时,将获取文本框的值并将其添加到字符串数组中。如果文本框的值不为空,则将其添加到数组中,并在控制台打印出添加的值。
请注意,这只是一个简单的示例,用于演示如何实现所需的功能。在实际应用中,可能需要根据具体需求进行适当的修改和扩展。
领取专属 10元无门槛券
手把手带您无忧上云