简体   繁体   English

我想永久保留Textfield中的Textarea值(Java GUI)

[英]I want to keep the values of Textarea from Textfield permanently (Java GUI)

I want to keep the values of Textarea1 after inputting them through the textfield1 via a button. 我想通过按钮通过textfield1输入它们后,保留Textarea1的值。 Everytime I finish running it the value disappears for a new one. 每次我运行完它,新值都会消失。 The first time I do it I get the value of the name I inserted, however when i do it a second time it erases. 第一次执行时,我会得到插入的名称的值,但是第二次执行时,它将删除。 please help me, thanks. 请帮助我,谢谢。 Here is the code: 这是代码:

import javax.swing.UIManager.LookAndFeelInfo;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import javax.swing.border.Border;
import javax.swing.*;


public class GUI_project2 extends JFrame {

private JMenuBar menuBar;
private JButton button1;
private JTextArea textarea1;
private JTextField textfield1;

static String MYARRAY[] = new String[4];
static int COUNTER = 0;
static String NEWITEM = null;
//Constructor 
public GUI_project2(){

    this.setTitle("GUI_project2");
    this.setSize(1118,845);
    //menu generate method
    generateMenu();
    this.setJMenuBar(menuBar);

    //pane with null layout
    JPanel contentPane = new JPanel(null);
    contentPane.setPreferredSize(new Dimension(1118,845));
    contentPane.setBackground(new Color(192,192,192));


    button1 = new JButton();
    button1.setBounds(206,109,90,35);
    button1.setBackground(new Color(214,217,223));
    button1.setForeground(new Color(0,0,0));
    button1.setEnabled(true);
    button1.setFont(new Font("sansserif",0,12));
    button1.setText("Add Word");
    button1.setVisible(true);
    //Set methods for mouse events
    //Call defined methods
    button1.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent evt) {
            ButtonClicked(evt);
        }
    });


    textfield1 = new JTextField();
    textfield1.setBounds(203,46,90,35);
    textfield1.setBackground(new Color(255,255,255));
    textfield1.setForeground(new Color(0,0,0));
    textfield1.setEnabled(true);
    textfield1.setFont(new Font("sansserif",0,12));
    textfield1.setText("");
    textfield1.setVisible(true);


    textarea1 = new JTextArea();
    textarea1.setBounds(27,48,150,100);
    textarea1.setBackground(new Color(255,255,255));
    textarea1.setForeground(new Color(0,0,0));
    textarea1.setEnabled(true);
    textarea1.setFont(new Font("sansserif",0,12));
    textarea1.setText("");
    textarea1.setBorder(BorderFactory.createBevelBorder(1));
    textarea1.setVisible(true);

    //adding components to contentPane panel
    contentPane.add(button1);
    contentPane.add(textfield1);
    contentPane.add(textarea1);
    //adding panel to JFrame and seting of window position and close operation
    this.add(contentPane);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLocationRelativeTo(null);
    this.pack();
    this.setVisible(true);
}

//Method mouseClicked for button1
private void ButtonClicked (MouseEvent evt) {
        //TODO
        NEWITEM = textfield1.getText();
        if (NEWITEM.compareTo("end")!=0){
            MYARRAY[COUNTER] = NEWITEM;
            COUNTER++;
            if (COUNTER == MYARRAY.length){ 
                increaseArraySize();
            }
        }
        String NEWITEM = "";
        listArray();
}
public void listArray(){
        for (int X=0;X<MYARRAY.length;X++){
            textarea1.setText(textfield1.getText());
        }

}

 public static void increaseArraySize(){
        System.out.print("Here we increase the size to ");
        String TEMP[] = new String[MYARRAY.length*2];
        System.arraycopy(MYARRAY, 0, TEMP, 0, MYARRAY.length);
        MYARRAY = TEMP;
        System.out.println(TEMP.length);

}
//method for generate menu
public void generateMenu(){
    menuBar = new JMenuBar();

    JMenu file = new JMenu("File");
    JMenu tools = new JMenu("Tools");
    JMenu help = new JMenu("Help");

    JMenuItem open = new JMenuItem("Open   ");
    JMenuItem save = new JMenuItem("Save   ");
    JMenuItem exit = new JMenuItem("Exit   ");
    JMenuItem preferences = new JMenuItem("Preferences   ");
    JMenuItem about = new JMenuItem("About   ");


    file.add(open);
    file.add(save);
    file.addSeparator();
    file.add(exit);
    tools.add(preferences);
    help.add(about);

    menuBar.add(file);
    menuBar.add(tools);
    menuBar.add(help);
}



 public static void main(String[] args){
    System.setProperty("swing.defaultlaf", "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new GUI_project2();
        }
    });
}

} }

The first time I do it I get the value of the name I inserted, however when i do it a second time it erases 第一次执行时,我会得到插入的名称的值,但是第二次执行时,它将删除

What do you think the setText(..) method does? 您认为setText(..)方法有什么作用? Did you read the API for a description of the method? 您是否已阅读API以获取该方法的说明?

textarea1.setText(textfield1.getText());

should be: 应该:

textarea1.append(textfield1.getText());

You can't program if you don't read the API! 如果您不阅读API,则无法编程! Take the time now to read the JTextArea API for other methods you may find useful in the future. 现在花点时间阅读JTextArea API,以了解将来可能会发现有用的其他方法。

Every time you call textarea1.setText(someText) , you are setting a fresh new content on the textarea that comes and replaces any other text that was here before. 每次调用textarea1.setText(someText) ,都在即将到来的textarea上设置新的新内容,并替换以前的任何其他文本。 What you should do is: 您应该做的是:

final StringBuilder content = new StringBuilder();
for (int X=0;X<MYARRAY.length;X++){
    sb.append(MYARRAY[X]);
    //Add this line if you eventually want to add a new line
    sb.append("\r\n");
}
textarea1.setText(sb.toString());

Hello CSStudent I tried to stay as close as your code as possible and edited your listArray method in order to achieve what you are Aiming for. 您好CSStudent,我试着尽可能地靠近您的代码,并编辑了listArray方法,以实现您的目标。

I want to keep the values of Textarea1 after inputting them through the textfield1 via a button. 我想通过按钮通过textfield1输入它们后,保留Textarea1的值。 Everytime I finish running it the value disappears for a new one. 每次我运行完它,新值都会消失。 The first time I do it I get the value of the name I inserted, however when i do it a second time it erases. 第一次执行时,我会得到插入的名称的值,但是第二次执行时,它将删除。 please help me, thanks. 请帮助我,谢谢。 Here is the code: 这是代码:

What your current code does is 'SETTING' the text of your textarea. 您当前的代码所做的是“设置”文本区域的文本。

According to the Docs setText does this: 根据文档setText这样做:

Sets the text of this TextComponent to the specified text. 将此TextComponent的文本设置为指定的文本。 If the text is null or empty, has the effect of simply deleting the old text. 如果文本为null或为空,则可以简单地删除旧文本。 When text has been inserted, the resulting caret location is determined by the implementation of the caret class. 插入文本后,最终插入符号的位置由插入符号类的实现确定。

So lets take a look at your listArray method. 因此,让我们看一下您的listArray方法。

public void listArray(){
    for (int X=0;X<MYARRAY.length;X++){
        textarea1.setText(textfield1.getText());
    }
}

It loops through your String Array which starts at the Size of 4 and increases by *2 if required. 它循环遍历您的字符串数组,该数组以4的大小开始,并根据需要增加* 2。 The problem is that since the size of the Array is 4 and you add the String on position 0 the array looks like this {"First thing you insert",null,null,null} according to the quote from the docs if the value is null or empty it will simply delete the old text. 问题在于,由于数组的大小为4,并且您在位置0处添加了字符串,根据文档中的引号,如果值是0,则数组看起来像这样{“首先插入的东西”,null,null,null} null或为空,它将仅删除旧文本。 This is why it erases as you say. 这就是为什么它会如您所说擦除。

However if you slighty modify it you will achieve what you desire 但是,如果您稍加修改,就可以实现您想要的

public void listArray(){
    textarea1.setText("");
    for (int X=0;X<MYARRAY.length;X++){
        if(MYARRAY[X] != null)
            textarea1.append(MYARRAY[X]+"\n");
    }
}

As stated earlier I tried to stay as close to your code as possible, let me explain what this does aswell. 如前所述,我试图尽可能地靠近您的代码,让我解释一下它的作用。 First of all it clears the textarea by inserting "" which is a blank String, followed by that it will loop through your Array and only IF it IS NOT (!=) null it will append the saved String and a linebreak ("\\n"). 首先,它通过插入作为空白字符串的“”来清除文本区域,然后它将循环遍历您的数组,并且仅当它不是(!=)null时,它将追加保存的字符串和一个换行符(“ \\ n ”)。 (This check prevents the textarea from getting erased) (此检查可防止删除文本区域)

If this reply solved your Problem please make sure to mark my answer as accepted, click on the check mark beside the answer to toggle it from hollow to green 如果此答复解决了您的问题,请确保将我的回答标记为已接受,单击答案旁边的复选标记,将其从空心切换为绿色

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

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