gpt4 book ai didi

java - 使用 JTextArea 和 JButton 修改 txt 文件

转载 作者:行者123 更新时间:2023-11-30 03:06:46 25 4
gpt4 key购买 nike

我对java比较陌生,我正在尝试创建一个程序,从txt文件中读取有关不同歌曲的一系列信息(位置、标题、艺术家、标签),并允许用户直接修改文件通过程序中包含的 JTextArea(按下 JButton 后)。我能够确保程序正确识别文件中包含的所有不同信息(事实上,我可以手动添加更多歌曲,没有任何问题),但我不知道如何允许用户从JTextArea。

文件内容:

1;X;ED SHEERAN;ASYLUM;

2;IN THE LONELY HOUR;SAM SMITH;CAPITOL;

3;NEVER BEEN BETTER;OLLY MURS;EPIC;

4;FOUR;ONE DIRECTION;SYCO MUSIC;

5;WANTED ON VOYAGE;GEORGE EZRA;COLUMBIA;

CD面板:

import java.io.*;
import java.util.*;
import javax.swing.*;

public class CDPanel {

private static String newLine = "\n";
public static CD myCD;
public static JTextArea myTextArea = new JTextArea(15, 30);

public static void main(String[] args) throws FileNotFoundException, IOException {

List<Integer> position = new ArrayList<>();
List<String> title = new ArrayList<>();
List<String> artist = new ArrayList<>();
List<String> label = new ArrayList<>();

JButton addCD = new JButton("Press to add the CD");

JFrame frame = new JFrame("CD List");
JPanel panel = new JPanel();

int numberOfLines = 0;

BufferedReader br = new BufferedReader(new FileReader("cd.dat"));
String line = null;
while ((line = br.readLine()) != null) {
String data[] = line.split(";");

for (int i=0; i<4; i++) {
if (i == 0) {
int value = Integer.parseInt(data[i]);
position.add(value);
}

if (i == 1) {
title.add(data[i]);
}

if (i == 2) {
artist.add(data[i]);
}

if (i == 3) {
label.add(data[i]);
}
}
numberOfLines++;
}

for (int i=0; i<numberOfLines; i++) {
myCD = new CD(position.get(i), title.get(i), artist.get(i), label.get(i));
myTextArea.append(String.valueOf(myCD + newLine));
}
panel.add(myTextArea);
panel.add(addCD);
frame.add(panel);
frame.setSize(30, 15);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

光盘:

public class CD {

public int position;
public String title, artist, label;

public CD (int positionInit, String titleInit, String artistInit, String labelInit) {
position = positionInit;
title = titleInit;
artist = artistInit;
label = labelInit;
}

public String toString() {
return position + ";" + title + ";" + artist + ";" + label + ";";
}
}

提前感谢您的帮助,如果我的代码(和我的英语)不完美,我很抱歉,但我还是这个世界的新手,我正在努力尽快提高我的知识:)

最佳答案

您应该使用JTable或者信任用户在 TextArea 上修改它;

ActionListener 添加到 JButton 并使用 myTextArea.write() 写入 cd.dat 文件.

JButton addCD = new JButton("Press to add the CD");
addCD.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {

FileWriter fw = null;
try {
fw = new FileWriter("cd.dat");
myTextArea.write(fw);
} catch (IOException e1) {
e1.printStackTrace();
} finally {
try {
fw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
});

关于java - 使用 JTextArea 和 JButton 修改 txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34570341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com