【问题标题】:How do I create an array of JTextField and retrieve the text from an array of String?如何创建 JTextField 数组并从 String 数组中检索文本?
【发布时间】:2020-02-26 05:14:09
【问题描述】:

我对 Java 还是很陌生,而且还是个学生。我希望你能理解我。

从下面的代码可以看出,我只对框架和标签进行了编码。用户应该能够写一些歌曲推荐。应该至少有几个由数组创建的文本字段。当用户进行更改时,应使用 JOptionPane.WARNING_MESSAGE 显示新文本。

我需要一些关于如何创建 JTextField 数组并从 String 数组中检索文本的指导。另外,如何使用 JOptionPane 显示所有文本?

谢谢。

import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;

class TextFrame extends JFrame 
{
    private final JLabel cLabel;

    public TextFrame() 
    {
        super("Hello there!");
        setLayout(new FlowLayout());

        cLabel = new JLabel("Please write some song recommendations.");
        cLabel.setToolTipText("Write below.");
        add(cLabel);
    }
}

public class TestFrame
{
  public static void main (String [] args)
    {
        TextFrame frame = new TextFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 400); 
        frame.setVisible(true); 
    }
}

【问题讨论】:

  • 文本字段数组? JTextField[] NAME = new JTextField[size of array];

标签: java arrays swing jtextfield joptionpane


【解决方案1】:

您应该创建一个 actionListener 来检查您是否输入了任何内容。您可以有另一个侦听器或助记符,因此当您按 Enter 时,它将更新所有内容。当您按 Enter 键时,您可以从 JTextFieldJTextArea 获取文本,然后将其保存到字符串数组中(即 String[] stringArray = new String[<num of items>] 这样您就可以只有一个文本字段,您就可以将所有内容存储在一个 String[] 而不是一个文本字段数组?我希望这会有所帮助!

【讨论】:

    【解决方案2】:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class framearray2 extends JFrame implements ActionListener
    {
    JCheckBox c1[];
    JTextField t1[];
    int i;
    framearray2(String p)
    {
    super(p);
    c1=new JCheckBox[2];
    t1=new JTextField[2];
    for(i=0;i<2;i++)
    {
    t1[i]=new JTextField(40);
    c1[0]=new JCheckBox("Singing");
    c1[0].setBackground(Color.red);
    c1[1]=new JCheckBox("Cricket",true);
    }
    for(i=0;i<2;i++)
    {
    add(t1[i]);
    add(c1[i]);
    t1[i].addActionListener(this);
    }
    setLayout(new FlowLayout());
    setFont(new Font("Arial",Font.ITALIC,40));
    }
    public void actionPerformed(ActionEvent e)
    {
    for(i=0;i<2;i++)
    {
    if(e.getSource().equals(t1[0]))
    {
    t1[0].setBackground(Color.red);
    }
    if(e.getSource().equals(t1[1]))
    {
    t1[1].setBackground(Color.blue);
    }
    }
    }
    public static void main(String s[])
    {
    framearray2 f1=new framearray2("hello");
    f1.setSize(600,500);
    f1.setVisible(true);
    }
    
    }
    

    【讨论】:

    • @dr-varun-tiwari:请添加一些信息来解释您的代码如何解决问题 - 这将有助于未来的其他人
    猜你喜欢
    • 2020-03-28
    • 1970-01-01
    • 2019-09-17
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    相关资源
    最近更新 更多