Person FileIO & JTable

PersonTableFrame

Person ArrayList & FileIO & JTable & CustomDialog & Menu

1. Gender

package PersonLib;

public enum Gender {
FEMALE, MALE;

public static Gender valueOf(int value) {
switch (value) { // switch
case 0:
return FEMALE;
case 1:
return MALE;
}
return null;
}

public static Gender nameOf(String name) {
switch (name) { // switch
case “FEMALE”:
return FEMALE;
case “MALE”:
return MALE;
}
return null;
}

public static String[] names() {
String[] names = new String[Gender.values().length];
for (Gender t : Gender.values())
names[t.ordinal()] = t.toString();
return names;
}
}

2. Activity
package PersonLib;

public enum Activity {
LOW, MEDIUM, HIGH;

public static Activity valueOf(int value)
{
switch(value) {
case 0:
return LOW;
case 1:
return MEDIUM;
case 2:
return HIGH;
default:
return null;
}
}

public static Activity nameOf(String name) {
switch (name) { // switch
case “LOW”:
return LOW;
case “MEDIUM”:
return MEDIUM;
case “HIGH”:
return HIGH;
}
return null;
}

public static String[] names() {
String[] names = new String[Activity.values().length];
for (Activity t : Activity.values())
names[t.ordinal()] = t.toString();
return names;
}
}

3. Person 클래스

package PersonLib;

import java.util.*;

public class Person implements Comparable<Person> {
private String name;
private int age;
private double weight;
private double height;
private Gender gender;
private Activity activity;

public Person()
{
this(“”, 0, 0.0, 0.0, Gender.FEMALE, Activity.LOW);
}

public Person(String name, int age, double weight, double height, Gender gender, Activity activity)
{
this.name = name;
this.age = age;
this.weight = weight;
this.height = height;
this.gender = gender;
this.activity = activity;
}

public Person(Person other)
{
this(other.name, other.age, other.weight, other.height, other.gender, other.activity);
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public int getAge()
{
return age;
}

public void setAge(int age)
{
this.age = age;
}

public double getWeight()
{
return weight;
}

public void setWeight(double weight)
{
this.weight = weight;
}

public double getHeight()
{
return height;
}

public void setHeight(double height)
{
this.height = height;
}

public Gender getGender()
{
return gender;
}

public void setGender(Gender gender)
{
this.gender = gender;
}

public Activity getActivity()
{
return activity;
}

public void setActivity(Activity activity)
{
this.activity = activity;
}

@Override
public String toString() // Object.toString() overriding
{
return String.format(“%s,%d,%.2f,%.2f,%s,%s”, name, age, weight, height, gender.toString(), activity.toString());
}

@Override
public boolean equals(Object other) // Object.equals overriding
{
if (other instanceof Person) {
Person that = (Person) other;
return that.canEqual(this)
&& this.getName().equals(that.getName())
&& this.getAge() == that.getAge()
&& this.getWeight() == that.getWeight()
&& this.getHeight() == that.getHeight()
&& this.getGender() == that.getGender()
&& this.getActivity() == that.getActivity();
}
return false;
}

@Override
public int hashCode()
{
return (41 * getName().hashCode() + getAge() + Double.valueOf(getWeight()).hashCode() + Double.valueOf(getHeight()).hashCode() + (int)(getGender()).hashCode() + (int)(getActivity()).hashCode());
}

public boolean canEqual(Object other)
{
return (other instanceof Person);
}

public int compareTo(Person other)
{
return this.getName().compareTo(other.getName()); //ascending order
}

public static Comparator AgeComparator
= new Comparator() {
public int compare(Person p1, Person p2) {
return p1.getAge() – p2.getAge(); //ascending order
}
};

public static Comparator WeightComparator
= new Comparator() {
public int compare(Person p1, Person p2) {
return Double.compare(p1.getWeight(), p2.getWeight()); //ascending order
}
};

public static Comparator HeightComparator
= new Comparator() {
public int compare(Person p1, Person p2) {
return Double.compare(p1.getHeight(), p2.getHeight()); //ascending order
}
};

public static Comparator GenderComparator
= new Comparator() {
public int compare(Person p1, Person p2) {
return p1.getGender().compareTo(p2.getGender());
}
};

public static Comparator ActivityComparator
= new Comparator() {
public int compare(Person p1, Person p2) {
return p1.getActivity().compareTo(p2.getActivity());
}
};

public static String[] columnNames() {
return new String[] {“Name”, “Age”, “Weight”, “Height”, “Gender”, “Activity”};
}

}

4. PersonComparator 클래스

package PersonLib;

import java.util.Comparator;

public class PersonComparator implements Comparator<Person> {
private int column;

public PersonComparator(int column) {
this.column = column;
}

@Override
public int compare(Person p1, Person p2) {
if (!(p1 instanceof Person) || !(p2 instanceof Person))
return 0;
switch (this.column) {
case 0:
return p1.getName().compareTo(p2.getName());
case 1:
return Integer.compare(p1.getAge(), p2.getAge());
case 2:
return Double.compare(p1.getWeight(), p2.getWeight());
case 3:
return Double.compare(p1.getHeight(), p2.getHeight());
case 4:
return p1.getGender().compareTo(p2.getGender());
case 5:
return p1.getActivity().compareTo(p2.getActivity());
default:
return 0;
}
}
}

5. PersonImporter 클래스

package PersonLib;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PersonImporter {
// load CSV
public static List<Person> loadCSV(String filename)
{
List<Person> personList = new ArrayList<Person>();
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
System.out.println(“file import: ” + filename);

String line = “”;
String delimiter = “,”;

while ((line = br.readLine()) != null) {
// use comma as separator
String[] items = line.split(delimiter);

Person p = new Person();
p.setName(items[0]);
p.setAge(Integer.parseInt(items[1]));
p.setWeight(Double.parseDouble(items[2]));
p.setHeight(Double.parseDouble(items[3]));
p.setGender(Gender.nameOf(items[4]));
p.setActivity(Activity.nameOf(items[5]));
System.out.println(“Person: ” + p);

personList.add(p);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(“load successfully”);
return personList;
}

// save CSV
public static void writeCSV(String path, List<Person> personList)
{
FileWriter fw;
try {
System.out.println(“file save: ” + path);

fw = new FileWriter(path);
for (Person c : personList) {
System.out.println(c);
fw.append(c.toString() + “\n”);
}
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

6. PersonManager 클래스

package PersonLib;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class PersonManager {
private List<Person> personList = null;

public PersonManager() {
personList = new ArrayList();
}

public PersonManager(List<Person> personList) {
this.personList = personList;
}

public void loadCSV(String filename) {
this.personList = PersonImporter.loadCSV(filename);
}

public void writeCSV(String filename) {
PersonImporter.writeCSV(filename, this.personList);
}

public List<Person> getList() {
return this.personList;
}

public Person get(int index) {
return this.personList.get(index);
}

public void set(int index, Person p) {
this.personList.set(index, p);
}

public int size() {
return this.personList.size();
}

public boolean isEmpty() {
return this.personList.isEmpty();
}

// add
public void add(Person p) {
this.personList.add(p);
}

// add all
public void addAll(List<Person> personList) {
this.personList.addAll(personList);
}

// print all
public void print() {
this.personList.forEach(p -> System.out.println(p));
}

// sort by
public void sort(int index) {
//this.personList.sort(new PersonComparator(index));
switch (index) {
case 0:
System.out.println(“sort by default (name)”);
this.personList.sort(null); // default – using Comparable
break;
case 1:
System.out.println(“sort by age”); // using lambda
this.personList.sort((p1, p2) -> Integer.compare(p1.getAge(), p2.getAge()));
break;
case 2:
System.out.println(“sort by weight”); // using lambda
this.personList.sort((p1, p2) -> Double.compare(p1.getWeight(), p2.getWeight()));
break;
case 3:
System.out.println(“sort by height”); // using lambda
this.personList.sort((p1, p2) -> Double.compare(p1.getHeight(), p2.getHeight()));
break;
case 4:
System.out.println(“sort by gender”); // using PersonComparator
this.personList.sort(new PersonComparator(4));
break;
case 6:
System.out.println(“sort by activity”);
this.personList.sort(Person.ActivityComparator); // using Person.ActivityComparator
break;
default:
System.out.println(“unsupported sort mode”);
break;
}
}

// remove at
public void removeAt(int index) {
if (index >= 0 && index < size()) {
this.personList.remove(index);
}
}

// remove must be done with Iterator or lambda removeIf
public void removeAllIf(Predicate<Person> func) {
this.personList.removeIf(func);
}

// find if matches
public List<Person> findAllIf(Predicate<Person> func) {
return this.personList.stream().filter(func).collect(Collectors.toList());
}
}

6. PersonDialog 클래스

package PersonTableFrame;

import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

import PersonLib.Activity;
import PersonLib.Gender;
import PersonLib.Person;

public class PersonDialog extends JDialog implements ActionListener, ItemListener, KeyListener {

public final static int OK = 1;
public final static int CANCEL = 2;
int returnValue = 0;

JLabel label1 = new JLabel(“이름”);
JLabel label2 = new JLabel(“나이”);
JLabel label3 = new JLabel(“몸무게”);
JLabel label4 = new JLabel(“키”);
JLabel label5 = new JLabel(“성별”);
JLabel label6 = new JLabel(“활동량”);

JTextField textfield1 = new JTextField(20);
JTextField textfield2 = new JTextField(20);
JTextField textfield3 = new JTextField(20);
JTextField textfield4 = new JTextField(20);

JRadioButton rbutton1 = new JRadioButton(“FEMALE”, true);
JRadioButton rbutton2 = new JRadioButton(“MALE”);
ButtonGroup rgroup1 = new ButtonGroup();
JPanel panel1 = new JPanel();

JComboBox combobox1 = new JComboBox(Activity.names());

JButton button1 = new JButton(“확인”);

Activity selectedActivity;

Person person = new Person();

public PersonDialog() {
setTitle(“Person Dialog”);
setLayout(null); // no layout – absolute positioning

label1.setBounds(20, 30, 100, 20);
label2.setBounds(20, 60, 100, 20);
label3.setBounds(20, 90, 100, 20);
label4.setBounds(20, 120, 100, 20);
label5.setBounds(20, 150, 100, 20);
label6.setBounds(20, 180, 100, 20);
this.add(label1);
this.add(label2);
this.add(label3);
this.add(label4);
this.add(label5);
this.add(label6);

textfield1.setBounds(120, 30, 150, 20);
textfield2.setBounds(120, 60, 150, 20);
textfield3.setBounds(120, 90, 150, 20);
textfield4.setBounds(120, 120, 150, 20);
this.add(textfield1);
this.add(textfield2);
this.add(textfield3);
this.add(textfield4);
textfield1.addKeyListener(this);

panel1.add(rbutton1);
panel1.add(rbutton2);
rgroup1.add(rbutton1);
rgroup1.add(rbutton2);
panel1.setBounds(120, 150, 150, 30);
this.add(panel1);

combobox1.setBounds(120, 180, 150, 20);
combobox1.addItemListener(this);
this.add(combobox1);

button1.setBounds(60, 220, 160, 20);
button1.addActionListener(this);
this.add(button1);

setSize(300, 300);
setModal(true); // set Modal (dialog)
}

public Gender selectGender() {
if (rbutton1.isSelected())
return Gender.FEMALE;
else
return Gender.MALE;
}

public Activity selectActivity() {
return Activity.valueOf(combobox1.getSelectedIndex());
}

public void addPerson() {
person.setName(textfield1.getText());
person.setAge(Integer.parseInt(textfield2.getText()));
person.setWeight(Double.parseDouble(textfield3.getText()));
person.setHeight(Double.parseDouble(textfield4.getText()));
person.setGender(selectGender());
person.setActivity(selectActivity());
System.out.println(“Person: ” + person);
}

@Override
public void actionPerformed(ActionEvent e) {
if ((JButton)e.getSource() == button1) {
addPerson();
returnValue = OK;
dispose();
}
}

@Override
public void itemStateChanged(ItemEvent e) {
JComboBox cb = (JComboBox)e.getSource();
int selectedIndex = cb.getSelectedIndex();
switch(selectedIndex) {
case 0:
selectedActivity = Activity.LOW;
break;
case 1:
selectedActivity = Activity.MEDIUM;
break;
case 2:
selectedActivity = Activity.HIGH;
break;
default:
break;
}
}

@Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_ENTER) {
Toolkit.getDefaultToolkit().beep();
System.out.println(“Enter pressed”);

addPerson();
returnValue = OK;
dispose();
}
}

@Override
public void keyReleased(KeyEvent e) {

}

@Override
public void keyTyped(KeyEvent e) {

}

public int getReturnValue()
{
return returnValue;
}

public Person getPerson()
{
return person;
}

}

7. PersonTableModel 클래스

package PersonTableFrame;

import java.util.List;
import java.util.ArrayList;
import javax.swing.table.*;

import PersonLib.Activity;
import PersonLib.Gender;
import PersonLib.Person;

public class PersonTableModel extends AbstractTableModel {

private List<Person> personList;
private String[] columnNames = Person.columnNames();

public PersonTableModel(List<Person> pList) {
this.personList = new ArrayList(pList);
}

@Override
public int getRowCount() {
return this.personList.size();
}

@Override
public int getColumnCount() {
return columnNames.length;
}

@Override
public String getColumnName(int column) {
return columnNames[column];
/*String name = “??”;
switch (column) {
case 0:
name = “Name”;
break;
case 1:
name = “Age”;
break;
case 2:
name = “Weight”;
break;
case 3:
name = “Height”;
break;
case 4:
name = “Gender”;
break;
case 5:
name = “Activity”;
break;
}
return name;*/
}

@Override
public Class<?> getColumnClass(int columnIndex) {
Class<?> type = String.class;
switch (columnIndex) {
case 0:
type = String.class;
break;
case 1:
type = Integer.class;
break;
case 2:
case 3:
type = Double.class;
break;
case 4:
type = Gender.class;
break;
case 5:
type = Activity.class;
break;
}
return type;
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Person p = this.personList.get(rowIndex);
Object value = null;
switch (columnIndex) {
case 0:
value = p.getName();
break;
case 1:
value = p.getAge();
break;
case 2:
value = p.getWeight();
break;
case 3:
value = p.getHeight();
break;
case 4:
value = p.getGender();
break;
case 5:
value = p.getActivity();
break;
}
return value;
}

@Override
public void setValueAt(Object value, int rowIndex, int columnIndex) {
Person p = this.personList.get(rowIndex);
switch (columnIndex) {
case 0:
p.setName((String)value);
break;
case 1:
p.setAge((Integer)value);
break;
case 2:
p.setWeight((Double)value);
break;
case 3:
p.setHeight((Double)value);
break;
case 4:
p.setGender((Gender)value);
break;
case 5:
p.setActivity((Activity)value);
break;
default:
throw new IllegalArgumentException(“Invalid column index”);
}
fireTableDataChanged();
}

public void addRow(Person p) {
System.out.println(“addRow: ” + p + ” RowCount=” + getRowCount());
this.personList.add(p);
fireTableRowsInserted(this.personList.size() – 1, this.personList.size() – 1);
}

public void removeRow(int rowIndex) {
if (rowIndex >=0 && rowIndex < getRowCount()) {
System.out.println(“PERSONTABLEMODEL REMOVEROW rowIndex=” + rowIndex);
fireTableRowsDeleted(rowIndex, rowIndex);
this.personList.remove(rowIndex);
}
}

class ColumnListener extends MouseAdapter {
private JTable table;
public ColumnListener(JTable table) {
this.table = table;
}

public void mouseClicked(MouseEvent e) {
TableColumnModel colModel = table.getColumnModel();
int columnModelIndex = colModel.getColumnIndexAtX(e.getX());
int modelIndex = colModel.getColumn(columnModelIndex).getModelIndex();

if (modelIndex < 0)
return;

for (int i = 0; i < getColumnCount(); i++) {
TableColumn column = colModel.getColumn(i);
column.setHeaderValue(getColumnName(column.getModelIndex()));
}
table.getTableHeader().repaint();

personList.sort(new PersonComparator(columnModelIndex));

table.tableChanged(new TableModelEvent(PersonTableModel.this));
table.repaint();
}
}
}

 

8. PersonTableFrame 클래스

package PersonTableFrame;

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.List;
import java.util.ArrayList;
import javax.swing.table.*;

import PersonLib.Person;
import PersonLib.PersonImporter;

import java.io.*;

public class PersonTableFrame extends JFrame {

List personList = new ArrayList();
PersonTableModel model;

public PersonTableFrame()
{
super(“PersonTableFrame”);

model = new PersonTableModel(personList);
JTable table = new JTable(model);

table.setAutoCreateRowSorter(true); // enable sorting
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setIntercellSpacing(new Dimension(10, 5));
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
int index = table.getSelectedRow();
if (index >= 0 && index < personList.size()) { personList.remove(index); model.removeRow(index); //personList.forEach((s) -> System.out.println(s));
}
}
});
/*personList.add(new Person(“Dooly”, 1000, 40, 126.4, Gender.MALE));
personList.add(new Person(“Douner”, 1986, 30, 110, Gender.MALE));
personList.add(new Person(“Ddochi”, 30, 50, 150.5, Gender.MALE));
personList.add(new Person(“Heedong”, 3, 36, 100.6, Gender.MALE));
personList.add(new Person(“Michol”, 25, 39.8, 126.4, Gender.MALE));
personList.add(new Person(“Gildong”, 40, 38.2, 129.4, Gender.MALE));
personList.add(new Person(“Younghi”, 10, 47.2, 152.4, Gender.FEMALE));
personList.add(new Person(“Cheolsoo”, 10, 48.2, 155.4, Gender.MALE));
personList.forEach((s) -> System.out.println(s));
personList.forEach((s) -> model.addRow(s));*/

personList = PersonImporter.loadCSV(“PersonList.csv”);
personList.forEach((s) -> model.addRow(s));
//personList.forEach((s) -> System.out.println(s));
//saveCSV(“TestList.csv”, personList);

JScrollPane scrollPane = new JScrollPane(table);
this.add(scrollPane, BorderLayout.CENTER);

// menu
JMenuBar menuBar = new JMenuBar();

// File Menu, F – Mnemonic
JMenu fileMenu = new JMenu(“File”);
fileMenu.setMnemonic(KeyEvent.VK_F);
menuBar.add(fileMenu);

// File->Open, O – Mnemonic
JMenuItem openMenuItem = new JMenuItem(“Open”, KeyEvent.VK_O);
fileMenu.add(openMenuItem);
this.setJMenuBar(menuBar);
openMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent event) {
System.out.println(“OPEN”);
String selectedFilename = openFileDialog();
if (selectedFilename != null) {
personList = PersonImporter.loadCSV(selectedFilename);
personList.forEach((q) -> model.addRow(q));
}
}
});

// File->Save, O – Mnemonic
JMenuItem saveMenuItem = new JMenuItem(“Save”, KeyEvent.VK_S);
fileMenu.add(saveMenuItem);
this.setJMenuBar(menuBar);
saveMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent event) {
System.out.println(“SAVE”);
String selectedFilename = saveFileDialog();
if (selectedFilename != null) {
PersonImporter.writeCSV(selectedFilename, personList);
}
}
});

// File->Exit, E – Mnemonic
JMenuItem exitMenuItem = new JMenuItem(“Exit”, KeyEvent.VK_E);
fileMenu.add(exitMenuItem);
this.setJMenuBar(menuBar);
exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent event) {
System.exit(0);
}
});

// Person Menu, P – Mnemonic
JMenu personMenu = new JMenu(“Person”);
personMenu.setMnemonic(KeyEvent.VK_P);
menuBar.add(personMenu);

// Person->Add, A – Mnemonic
JMenuItem addMenuItem = new JMenuItem(“Add”, KeyEvent.VK_A);
personMenu.add(addMenuItem);
this.setJMenuBar(menuBar);
addMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent event) {
PersonDialog personDialog = new PersonDialog();
personDialog.setVisible(true);
if (personDialog.getReturnValue() == PersonDialog.OK) {
Person p = personDialog.getPerson();
//System.out.println(p);
model.addRow(p);
personList.add(p);
System.out.println(“After add:”);
personList.forEach((s) -> System.out.println(s));
System.out.println(“———————added”);
}
}
});

this.setSize(600, 450);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public String openFileDialog() {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
System.out.println(“openFile”);
String selectedFilename = fileChooser.getSelectedFile().getAbsolutePath().toString();
System.out.println(selectedFilename);
return selectedFilename;
}
else {
System.out.println(“file not opened”);
return null;
}
}

public String saveFileDialog() {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showSaveDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
System.out.println(“saveFile”);
String selectedFilename = fileChooser.getSelectedFile().getAbsolutePath().toString();
System.out.println(selectedFilename);
return selectedFilename;
}
else {
System.out.println(“file not selected”);
return null;
}
}

public static void main(String args[])
{
new PersonTableFrame(); // data table
}

}