gpt4 book ai didi

java - 从外部文件获取并显示在 JTable 中

转载 作者:太空宇宙 更新时间:2023-11-04 13:56:31 26 4
gpt4 key购买 nike

有人可以告诉我如何修改下面的程序吗?程序的数据通过 object[][] 传递 - 而不是仅给出应在表中打印数据的文件名。

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class SimpleTableDemo extends JPanel {
private boolean DEBUG = false;

public SimpleTableDemo() {
super(new GridLayout(1,0));

String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};

Object[][] data = {
{"Kathy", "Smith",
"Snowboarding", new Integer(5), new Boolean(false)},
{"John", "Doe",
"Rowing", new Integer(3), new Boolean(true)},
{"Sue", "Black",
"Knitting", new Integer(2), new Boolean(false)},
{"Jane", "White",
"Speed reading", new Integer(20), new Boolean(true)},
{"Joe", "Brown",
"Pool", new Integer(10), new Boolean(false)}
};

final JTable table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);

if (DEBUG) {
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
printDebugData(table);
}
});
}

//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);

//Add the scroll pane to this panel.
add(scrollPane);
}

private void printDebugData(JTable table) {
int numRows = table.getRowCount();
int numCols = table.getColumnCount();
javax.swing.table.TableModel model = table.getModel();

System.out.println("Value of data: ");
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + model.getValueAt(i, j));
}
System.out.println();
}
System.out.println("--------------------------");
}

/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("SimpleTableDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Create and set up the content pane.
SimpleTableDemo newContentPane = new SimpleTableDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);

//Display the window.
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

最佳答案

如果我理解问题正确,您可以将 Object[][] 数据替换为如下内容:

    String line;
ArrayList<String[]> toData = new ArrayList<String[]>();
File file = new File("\\file path");
try{
BufferedReader reader = new BufferedReader(new FileReader(file));
while ((line = reader.readLine()) != null) {
String[] lineElements = line.split(",");
toData.add(lineElements);
}
}catch (Exception ex){
ex.printStackTrace();
System.out.println("File not found");
}
String[][] data = new String[toData.size()][];
int index = 0;
for(String[] a: toData){
data[index]=a;
index++;
}

在此示例中,如果文件中的数据格式为:名字,姓氏,运动,是素食主义者。不过,您可以轻松更改它,但请记住还要更改 line.split() 中括号中的符号。

编辑:我不完全明白你想要实现什么,但我会这样做:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;

public class Project {
private JScrollPane scrollPane;
private JFrame frame;
private JTable table;

public static void main (String[] args){
Project project = new Project();
project.createGUI();
}

public void createGUI(){
frame = new JFrame();

scrollPane = new JScrollPane();
JPanel panel = new JPanel();
JButton open = new JButton("Open");
open.addActionListener(new OpenListener());
JButton submit = new JButton("Submit");
submit.addActionListener(new SubmitListener());
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new CancelListener());
panel.add(open);
panel.add(submit);
panel.add(cancel);

frame.getContentPane().add(BorderLayout.CENTER,scrollPane);
frame.getContentPane().add(BorderLayout.SOUTH,panel);


frame.setSize(500,500);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void createAndDisplayList(String[][] data){
String[] columnNames = {"First Name","Last Name","Sport","# of Years","Vegetarian"};
table = new JTable(data, columnNames);
frame.setVisible(false);
frame.remove(scrollPane);
scrollPane = new JScrollPane(table);
frame.getContentPane().add(BorderLayout.CENTER,scrollPane);
frame.revalidate();
frame.setVisible(true);
}
private class OpenListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
String line;
ArrayList<String[]> toData = new ArrayList<String[]>();
fileChooser.showOpenDialog(frame);
try{
BufferedReader reader = new BufferedReader(new FileReader(fileChooser.getSelectedFile()));
while ((line = reader.readLine()) != null) {
String[] lineElements = line.split(",");
toData.add(lineElements);
}
reader.close();
}catch (Exception ex){
ex.printStackTrace();
JOptionPane.showMessageDialog(frame, "File not found", "Error", JOptionPane.ERROR_MESSAGE);
}
String[][] data = new String[toData.size()][];
int index = 0;
for(String[] a: toData){
data[index]=a;
index++;
}
createAndDisplayList(data);
}
}

private class CancelListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
frame.remove(scrollPane);
scrollPane = new JScrollPane();
frame.getContentPane().add(BorderLayout.CENTER,scrollPane);
frame.revalidate();
frame.setVisible(true);
}
}

private class SubmitListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.showSaveDialog(frame);
try{
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fileChooser.getSelectedFile()));
for(int i = 0; i<table.getRowCount(); i++){
for(int j = 0; j<table.getColumnCount(); j++){
System.out.println(i + "," + table.getRowCount());
bufferedWriter.write(table.getValueAt(i, j).toString() + ",");
}
bufferedWriter.newLine();
}
bufferedWriter.close();
}catch (IOException ex){
ex.printStackTrace();
JOptionPane.showMessageDialog(frame,"File not found","Error",JOptionPane.ERROR_MESSAGE);
}
}
}
}

但是请注意,这是一个原始且业余编写的代码,但它在某种程度上有效。您可以打开、更改内容和保存文件(提交),但不能在表中添加行,您需要在 .txt 文件中执行此操作(但不能在文件末尾留任何空白)。不管怎样,我希望你能在这里找到有用的东西。

关于java - 从外部文件获取并显示在 JTable 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29763903/

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