Person ArrayList & FileIO & JTable & CustomDialog & Menu
1. Person 클래스
import java.util.*;
enum Gender
{
FEMALE, MALE
}
public class Person implements Comparable<Person>
{
private String name;
private int age;
private double weight;
private double height;
private Gender gender;
public Person()
{
this(“”, 0, 0.0, 0.0, Gender.FEMALE);
}
public Person(String name, int age, double weight, double height, Gender gender)
{
this.name = name;
this.age = age;
this.weight = weight;
this.height = height;
this.gender = gender;
}
public Person(Person other)
{
this(other.name, other.age, other.weight, other.height, other.gender);
}
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;
}
@Override
public String toString() // Object.toString() overriding
{
return String.format(“%s,%d,%.2f,%.2f,%s”, name, age, weight, height, gender.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();
}
return false;
}
@Override
public int hashCode()
{
return (41 * getName().hashCode() + getAge() + Double.valueOf(getWeight()).hashCode() + Double.valueOf(getHeight()).hashCode() + (int)(getGender()).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<Person> AgeComparator
= new Comparator<Person>() {
public int compare(Person p1, Person p2) {
return p1.getAge() – p2.getAge(); //ascending order
}
};
public static Comparator<Person> WeightComparator
= new Comparator<Person>() {
public int compare(Person p1, Person p2) {
return Double.compare(p1.getWeight(), p2.getWeight()); //ascending order
}
};
public static Comparator<Person> HeightComparator
= new Comparator<Person>() {
public int compare(Person p1, Person p2) {
return Double.compare(p1.getHeight(), p2.getHeight()); //ascending order
}
};
public static Comparator<Person> GenderComparator
= new Comparator<Person>() {
public int compare(Person p1, Person p2) {
return p1.getGender().compareTo(p2.getGender());
}
};
}
2. PersonDialog 클래스
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
//Kyoung Shin Park (2016 Fall)
public class PersonDialog extends JDialog implements ActionListener {
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(“성별”); // 레이블 초기화
JTextField textfield1 = new JTextField(20); // 텍스트필드 초기화
JTextField textfield2 = new JTextField(20); // 텍스트필드 초기화
JTextField textfield3 = new JTextField(20); // 텍스트필드 초기화
JTextField textfield4 = new JTextField(20); // 텍스트필드 초기화
JRadioButton rbutton1 = new JRadioButton(“여자”, true); // gender 라디오버튼
JRadioButton rbutton2 = new JRadioButton(“남자”); // gender 라디오버튼
ButtonGroup rgroup = new ButtonGroup();
JPanel panel = new JPanel(); // 패널 초기화
JButton button1 = new JButton(“확인”); // 버튼 초기화
Person person = new Person();
public PersonDialog() {
setTitle(“Person Dialog”);
setLayout(null);
// frame
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);
add(label1);
add(label2);
add(label3);
add(label4);
add(label5);
textfield1.setBounds(120, 30, 150, 20);
textfield2.setBounds(120, 60, 150, 20);
textfield3.setBounds(120, 90, 150, 20);
textfield4.setBounds(120, 120, 150, 20);
add(textfield1);
add(textfield2);
add(textfield3);
add(textfield4);
panel.add(rbutton1);
panel.add(rbutton2);
rgroup.add(rbutton1);
rgroup.add(rbutton2);
panel.setBounds(20, 150, 300, 40);
add(panel);
button1.setBounds(60, 200, 160, 20);
add(button1);
// event
button1.addActionListener(this);
setSize(300, 270); // size the frame
setResizable(false);
setModal(true);
}
private Gender selectGender()
{
if (rbutton2.isSelected()) {
return Gender.MALE;
}
return Gender.FEMALE;
}
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button == button1) {
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());
returnValue = OK;
dispose();
}
}
public int getReturnValue()
{
return returnValue;
}
public Person getPerson()
{
return person;
}
/*public static void main(String[] args) {
new PersonDialog();
}*/
}
3. PersonTableModel 클래스
import java.util.*;
import javax.swing.table.*;
public class PersonTableModel extends AbstractTableModel {
private ArrayList<Person> personList;
public PersonTableModel(ArrayList<Person> pList) {
this.personList = new ArrayList<Person>(pList);
}
@Override
public int getRowCount() {
return this.personList.size();
}
@Override
public int getColumnCount() {
return 5;
}
@Override
public String getColumnName(int 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;
}
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;
}
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;
}
return value;
}
public void setValueAt(Person value, int rowIndex) {
this.personList.set(rowIndex, value);
fireTableDataChanged();
}
public void addRow(Person p) {
this.personList.add(p);
fireTableRowsInserted(this.personList.size() – 1, this.personList.size() – 1);
}
public void removeRow(int rowIndex) {
if (rowIndex >=0 && rowIndex < getRowCount()) {
this.personList.remove(rowIndex);
fireTableRowsDeleted(rowIndex, rowIndex);
}
}
}
4. PersonTableFrame 클래스
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.table.*;
import java.io.*;
//Kyoung Shin Park (2016 Fall)
public class PersonTableFrame extends JFrame {
ArrayList<Person> personList = new ArrayList<Person>();
PersonTableModel model;
public PersonTableFrame()
{
super(“PersonTableFrame”);
model = new PersonTableModel(personList);
JTable table = new JTable(model);
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));
}
}
});
/*.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 = loadCSV(“data/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 = 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) {
saveCSV(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;
}
}
// load CSV
public ArrayList<Person> loadCSV(String filename)
{
ArrayList<Person> pList = 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);
String name = items[0];
int age = Integer.parseInt(items[1]);
double weight = Double.parseDouble(items[2]);
double height = Double.parseDouble(items[3]);
Gender gender = items[4].equals(“FEMALE”) ? Gender.FEMALE : Gender.MALE;
// add Person into List
Person p = new Person(name, age, weight, height, gender);
//System.out.println(p);
pList.add(p);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(“load successfully”);
return pList;
}
// save CSV
public void saveCSV(String path, ArrayList<Person> pList)
{
FileWriter fw;
try {
System.out.println(“file save: ” + path);
fw = new FileWriter(path);
for (Person p : pList) {
System.out.println(p);
fw.append(p.toString() + “\n”);
}
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String args[])
{
new PersonTableFrame(); // data table
}
}