如何放置一个包含每个字符串列表的下拉列表,当我在该列表中选择一个项目然后按下加载按钮时,它只会显示该字符串上的内容。这是我的代码,我实际上输入了字符串的编号,并使用 while 语句显示字符串的数据。
我如何才能真正放置一个下拉列表,它的内容将是每个字符串上注册的数字。像这样
1 231231
2 123124
3 123124
4 232312
如果我选择 4 并按“加载”,它将显示“232312”,每次我保存数据时,每行都会注册一个唯一编号,就像“4”是唯一编号一样。232312 是它的数据
package datasaving;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.*;
public class Datasaving {
/**
* @param args the command line arguments
* @throws FileNotFoundException
* @throws IOException
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
JPanel panel = new JPanel();
JFrame frame = new JFrame();
final JTextField input0 = new javax.swing.JTextField(20);
final JTextField input1 = new javax.swing.JTextField(20);
final JTextField out = new javax.swing.JTextField(20);
final JTextField line = new javax.swing.JTextField(20);
JButton save = new javax.swing.JButton("Save");
JButton load = new javax.swing.JButton("Load");
frame.add(panel);
frame.setSize(240,200);
panel.add(input0);
panel.add(input1);
panel.add(save);
panel.add(line);
panel.add(out);
panel.add(load);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
save.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
File file = new File("data.dat");
try {
try (FileWriter writer = new FileWriter(file, true)) {
String data0 = input0.getText();
String data1 = input1.getText();
writer.write(data0+":"+data1+"\n");
}
System.out.println("Data Saved");
} catch (IOException | HeadlessException z) {
JOptionPane.showMessageDialog(null, e);
}
}
});
load.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int lines = Integer.parseInt(line.getText());
try {
FileInputStream fs= new FileInputStream("data.dat");
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
for(int i = 0; i < lines; ++i) {
br.readLine();
}
out.setText(br.readLine());
JOptionPane.showMessageDialog(null, "Loaded");
} catch ( IOException | HeadlessException es) {
JOptionPane.showMessageDialog(null, e);
}
}
});
}
}
例如: John blahblahblahblah Keith blahblahblahblah Joe blahblahblahblah Kenneth blahblahblahblah Christian blahblahblahblah 第一个单词“Names”将添加到 JList 或 JComboBox 如何使名称成为 Array。我知道如何使用 .split(); 但我不知道如何在文件的每一行中做到这一点