.csv 파일의 JTable 열에 헤더를 추가하고 싶습니다..csv 파일에서 JTable의 열에 헤더를 추가하는 방법
그림에서 내 .csv 파일을 볼 수 있습니다.
나는이 코드 조각을 삭제해야합니다 private String[] columnNames = { "Country", "Capital", "Population" };
대신 그것의 은 .CSV 파일의 열 내 이름과 열 이름을 얻을 수 있습니다 다른 기능을 넣어.
내 주요 클래스 :
public class App extends JFrame {
private Object[][] data;
private String[] columnNames = { "Country", "Capital", "Population" };
private DefaultTableModel tableModel;
private JTable table;
private CountryList myList;
public App(String title) {
super(title);
setBounds(10, 10, 400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myList = new CountryList();
myList.readFromCSV("data/country.csv");
data = myList.convert2Data();
tableModel = new DefaultTableModel(data, columnNames);
table = new JTable(tableModel);
table.setAutoCreateRowSorter(true);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setPreferredSize(new Dimension(380, 280));
JPanel panel = new JPanel();
panel.add(scrollPane);
add(panel, BorderLayout.CENTER);
}
public static void main(String[] args) {
App myApp = new App("Basic JTable");
myApp.setVisible(true);
}
}
그리고 내 클래스 CountryList :
public class CountryList {
private ArrayList<Country> books;
public CountryList() {
books = new ArrayList<Country>();
}
public void add(Country sb) {
books.add(sb);
}
public void readFromCSV(String filename) {
File file = new File(filename);
FileReader reader = null;
try {
reader = new FileReader(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(1);
}
BufferedReader infile = new BufferedReader(reader);
String line = "";
try {
boolean done = false;
while (!done) {
line = infile.readLine();
if (line == null) {
done = true;
} else {
String[] tokens = line.trim().split(";");
String country = tokens[0].trim();
String capital = tokens[1].trim();
int population = Integer.parseInt(tokens[2].trim());
Country sb = new Country(country, capital, population);
books.add(sb);
}
}
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}