SW 중심대학 사업단 교육과정설명회

11.27 (월) 15시 부터 17:40까지 사업참여 3개학과 1-3학년을 대상으로 교육과정설명회

– 행사명 : ‘SW중심대학 교육과정 설명회 및 SW자격시험 특강’

– 일시 및 장소 : 2017.11.27.(월) 15:00∼17:50 / 학생극장

– 대상 : 소프트웨어학과, 응용컴퓨터공학과, 모바일시스템공학과(전공) 1∼3학년 재학생 (502명)

– 주관 : 단국대학교 SW융합대학사업단

– 후원 : 과학기술정보통신부, 정보통신기술진흥센터(IITP)

Lab7

PersonTableFrame를 참고한다.

Lab7 프로젝트 디렉토리 안에 모든 파일(src/*.java & bin/*.class)와 보고서 (장수 제한 없음)를 넣고 Lab7_학번_이름.zip 압축한 후 e-learning (http://lms.dankook.ac.kr/index.jsp)으로 제출

Lab7 – SwingTable(FileIO & GUI & Collection & sort)
본인이 작성한 Lab6에 Lab7_template에 ConverterImporter, ConverterComparator, ConverterManager, ConverterTableFrame을 작성한다.
-ConverterImporter는 CSV 파일 I/O
-ConverterComparator는 sort를 위한 compare 메소드를 구현한다.
-ConverterManager는 List<Converter> 관리자
-ConverterTableFrame은 JTable에 List<Converter>를 보여주며 colume header을 누르면 sort된다.

ConverterFrame에서는 (textfield1/2에서 엔터키를 눌러서) Converter 계산을 하며, 그 결과가 ConverterTableFrame (즉 테이블과 매니져)에 추가된다.
ConverterTableFrame에서는 테이블뷰에 List<Converter>를 보여주고, column header를 마우스 클릭하면 해당 방식으로 데이터가 sort된다.
ConverterTableFrame에서는 테이블뷰에 row를 마우스 클릭하면 해당 데이터가 remove 된다.
ConverterFrame에서 close button을 누르면, 테스트한(또는 정렬된) List<Converter>가 콘솔창에 테이블로 출력된다.
보고서의 내용은 기존 코드 분석과 이해한 내용 그리고 본인이 추가한 코드내용을 적는다.

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
}

}

Point Collections

1. create PointLib package

– Point 클래스를 넣는다.
package PointLib;

import java.util.*;

public class Point implements Comparable<Point> {
protected double x;
protected double y;

public Point()
{
this(0.0, 0.0);
}

public Point(double x, double y)
{
this.x = x;
this.y = y;
}

public double getX()
{
return x;
}

public double getY()
{
return y;
}

public int compareTo(Point other)
{
return Double.compare(this.getX(), other.getX()); //ascending order by X
}

public static Comparator<Point> YComparator = new Comparator<Point>() {
public int compare(Point p1, Point p2) {
return Double.compare(p1.getY(), p2.getY()); //ascending order by Y
}
};

@Override
public int hashCode() // hashCode method override
{
return Double.valueOf(this.x).hashCode() * Double.valueOf(this.y).hashCode();
}

@Override
public boolean equals(Object obj) // equals method override
{
if (obj instanceof Point)
return equals((Point)obj);
return false;
}

public boolean equals(Point other) // equals method override
{
if (this.x == other.x && this.y == other.y)
return true;
return false;
}

@Override
public String toString() // toString method override
{
return “(” + this.x + “,” + this.y + “)”;
}

}

 

2. create PointCollectionLab package
– PointTest 클래스를 넣는다.
package PointTestApp;

import java.util.*;
import java.util.function.*;
import java.util.stream.Collectors;

import PointLib.Point;

class PointTest  {

public static void main(String[] args) {
new PointTest();
}

public PointTest()
{
Point[] pList = new Point[10];
for (int i=0; i<10; i++) {
pList[i] = new Point(i, i+1);
}
System.out.println(“Point!!!”);
Arrays.stream(pList).forEach((s) -> System.out.println(s));

System.out.println(“Point SORT BY X (DEFAULT)!!!”);
Arrays.sort(pList);
Arrays.stream(pList).forEach((s) -> System.out.println(s));

System.out.println(“Person SORT by Y!!!”);
Arrays.sort(pList, Point.YComparator);
Arrays.stream(pList).forEach((s) -> System.out.println(s));

///////////////////////////////////////////////////////////////////////
System.out.println(“Point SORT BY X (anonymous method)!!!”);
Arrays.sort(pList, new Comparator<Point>() {
public int compare(Point p1, Point p2) {
return Double.compare(p1.getX(), p2.getX()); //ascending order by X
}
});
Arrays.stream(pList).forEach((s) -> System.out.println(s));

System.out.println(“Point SORT by Y (anonymous method)!!!”);
Arrays.sort(pList, new Comparator<Point>() {
public int compare(Point p1, Point p2) {
return Double.compare(p1.getY(), p2.getY()); //ascending order by Y
}
});
Arrays.stream(pList).forEach((s) -> System.out.println(s));

///////////////////////////////////////////////////////////////////////
System.out.println(“Point SORT BY X (lambda)!!!”);
Arrays.sort(pList, (Point p1, Point p2)
-> Double.compare(p1.getX(), p2.getX())  );
Arrays.stream(pList).forEach((s) -> System.out.println(s));

System.out.println(“Point SORT by Y (lambda)!!!”);
Arrays.sort(pList, (Point p1, Point p2)
-> Double.compare(p1.getY(), p2.getY()) );
Arrays.stream(pList).forEach((s) -> System.out.println(s));

///////////////////////////////////////////////////////////////////////
ArrayList pointList = new ArrayList();
for (int i=0; i<10; i++) {
pointList.add(new Point(i*10, i*10+1));
}
pointList.forEach((s) -> System.out.println(s));
/*
System.out.println(“Point SORT BY X (lambda)!!!”);
pointList.sort((Point pp1, Point pp2)
-> Double.compare(pp1.getX(), pp2.getX())
);
pointList.forEach((s) -> System.out.println(s));

System.out.println(“Point SORT by Y (lambda)!!!”);
pointList.sort((Point p1, Point p2) ->
Double.compare(p1.getY(), p2.getY())
);
pointList.forEach((s) -> System.out.println(s));
*/
System.out.println(“pointList[2]=” + pointList.get(2));

Iterator it = pointList.iterator(); // Iterator 객체 얻기
while(it.hasNext()) {
Object p = it.next();
System.out.println(p);
}

///////////////////////////////////////////////////////////////////////

Vector vList= new Vector();
for (int i=0; i<10; i++) {
vList.add(new Point(i*100, i*100+1));
}
vList.forEach((s) -> System.out.println(s));

vList.removeElementAt(vList.size() – 1); // delete the last element in vList
for (int i=0; i<vList.size(); i++) {
Object p = vList.get(i);
System.out.println(p);
}

///////////////////////////////////////////////////////////////////////

Hashtable<Integer, Point> hList = new Hashtable<Integer, Point>();
for (int i=0; i<10; i++) {
hList.put(i, new Point(i*1000, i*1000+1));
}
hList.forEach((i, s) -> System.out.println(s));

System.out.println(“hList contains point (1000, 1001) is ” + hList.contains(new Point(1000, 1001)));
hList.put(10, new Point(10, 10));
hList.forEach((i, s) -> System.out.println(s));
hList.remove(9); // remove item by key
hList.forEach((i, s) -> System.out.println(s));

System.out.println(“Key,Value print”);
Set keys = hList.keySet();
Iterator itr = keys.iterator();
while(itr.hasNext()) {
Integer key = (Integer) itr.next();
Point value = hList.get(key);
System.out.println(“(” + key + “,” + value + “)”);
}

///////////////////////////////////////////////////////////////////////
System.out.println(“/////////////”);
}
}

EventHandler

AbsolutePositionEventListener

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Button1Listener implements ActionListener { // (1) 독립적 이벤트 클래스

public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
button.setText(“버튼 1이 눌려졌습니다”);
}

}

class MyFrame extends JFrame implements ActionListener { // (3) 인터페이스 구현
JButton b1;
JButton b2;
JButton b3;
JButton b4;
JButton b5;

private class Button2Listener implements ActionListener { // (2) 내부 이벤트 클래스

public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button == b2) {
b1.setText(“버튼2 이 눌려졌습니다”);
b2.setText(“버튼2 이 눌려졌습니다”);
b3.setText(“버튼2 이 눌려졌습니다”);
}
}

}

public MyFrame() {
setTitle(“Absolute Position Test”);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);

JPanel p = new JPanel();
p.setLayout(null); // 절대위치크기 지정
b1 = new JButton(“Button #1”);
p.add(b1);
b2 = new JButton(“Button #2”);
p.add(b2);
b3 = new JButton(“Button #3”);
p.add(b3);
b4 = new JButton(“Button #4”);
p.add(b4);
b5 = new JButton(“Button #5”);
p.add(b5);
b1.setBounds(20, 5, 95, 30); // 절대위치크기 지정
b2.setBounds(55, 45, 105, 70); // 절대위치크기 지정
b3.setBounds(180, 15, 105, 90); // 절대위치크기 지정
b4.setBounds(80, 120, 105, 40); // 절대위치크기 지정
b5.setBounds(20, 170, 200, 30); // 절대위치크기 지정
add(p);

b1.addActionListener(new Button1Listener()); // (1) 독립적 이벤트 클래스 사용
b2.addActionListener(new Button2Listener()); // (2) 내부 이벤트 클래스 사용
b3.addActionListener(this); // (3) 인터페이스 구현
b4.addActionListener(new ActionListener() { // (4) 무명 이벤트 클래스 사용
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button == b4) {
b1.setText(“버튼4 이 눌려졌습니다”);
b2.setText(“버튼4 이 눌려졌습니다”);
b3.setText(“버튼4 이 눌려졌습니다”);
b4.setText(“버튼4 이 눌려졌습니다”);
}
}
});
b5.addActionListener(e -> { // (5) lambda 사용
b1.setText(“버튼5 이 눌려졌습니다”);
b2.setText(“버튼5 이 눌려졌습니다”);
b3.setText(“버튼5 이 눌려졌습니다”);
b4.setText(“버튼5 이 눌려졌습니다”);
b5.setText(“버튼5 이 눌려졌습니다”);
});

setVisible(true);
}

public void actionPerformed(ActionEvent e) { // (3) 인터페이스 구현

JButton button = (JButton) e.getSource();
if (button == b3) {
b1.setText(“버튼3 이 눌려졌습니다”);
b2.setText(“버튼3 이 눌려졌습니다”);
b3.setText(“버튼3 이 눌려졌습니다”);
}

}

}

public class AbsolutePositionTest {
public static void main(String args[]) {
MyFrame f = new MyFrame();
}
}

Lab6

Lab6_Swing_template (updated)

PersonFrame PersonLib BMILib를 참고한다.

Lab6 프로젝트 디렉토리 안에 모든 파일(src/*.java & bin/*.class)와 보고서 (3~4장)를 넣고 Lab6_학번_이름.zip 압축한 후 e-learning (http://lms.dankook.ac.kr/index.jsp)으로 제출

Lab6 – Swing(GUI)

본인이 작성한 Lab5에 Lab6_template에 ConverterFrame을 작성한다.
ConverterFrame에서는 GUI방식의 Converter를 테스트할 수 있다.
close button을 누르면 테스트한 Converter 데이터를 테이블로 출력한다 (ArrayList 사용).
보고서의 내용은 기존 코드 분석과 이해한 내용 그리고 본인이 추가한 코드내용을 적는다.

Lab5

Lab5_template

ValueCollectionTest ValueLib를 참고한다.

Lab5 프로젝트 디렉토리 안에 모든 파일(src/*.java & bin/*.class)와 보고서 (3~4장)를 넣고 Lab5_학번_이름.zip 압축한 후 e-learning (http://lms.dankook.ac.kr/index.jsp)으로 제출

Lab5 – Collections(ArrayList, HashMap, Comparable, Comparator, sort, equals, hashCode)

본인이 작성한 Lab4에 LengthConverter 클래스를 참고하여 다른 클래스도 바꾼다. ConverterTest에서는 ArrayList를 사용하여 각종 Converter 데이터를 추가하고 테이블로 출력한다.

https://www.unitconverters.net/length/km-to-miles.htm

그리고 sort를 사용하여 Comparable vs Comparator 차이점을 비교해본다. 또한 HashMap을 사용하여== vs equals vs hashCode 차이점을 비교해본다.

보고서는 출력해서 수업시작 전에 제출한다.

보고서의 내용은 기존 코드 분석과 이해한 내용 그리고 본인이 추가한 코드내용을 적는다.

Difference between Array and ArrayList

  • Resizable
    • Array is static in size that is fixed length data structure, One can not change the length after creating the Array object.
    • ArrayList is dynamic in size. Each ArrayList object has instance variable capacity which indicates the size of the ArrayList. Its capacity grows automatically.
  • Primitives
    • Array can contain both primitive data types (e.g. int, float, double) as well as objects.
    • ArrayList can not contains primitive data types it can only contains objects.
  • Adding elements
    • In array we insert elements using the assignment(=) operator.
    • We can insert elements into the ArrayList using the add() method
  • Length
    • Each array object has the length variable which returns the length of the array.
    • Length of the ArrayList is provided by the size() method.

// Array

int[] integerArray = new int[3];
integerArray[0] = 1;
integerArray[1] = 2;
integerArray[2] = 3;
for (int i : integerArray) System.out.println(i);
for (int j=0; j<integerArray.length; j++) System.out.println(integerArray[ j ]);
int k = 0;
while (k < integerArray.length) System.out.println(integerArray[k++]);

// ArrayList

ArrayList integerList = new ArrayList();
integerList.add(1); //cannot store primitive in ArrayList, instead autoboxing will convert int to Integer object
integerList.add(2); //cannot store primitive in ArrayList, instead autoboxing will convert int to Integer object
integerList.add(3); //cannot store primitive in ArrayList, instead autoboxing will convert int to Integer object
for (int m : integerList) System.out.println(m);
for (int n=0; n<integerList.size(); n++) System.out.println(integerList.get(n));
Iterator itr = integerList.iterator();
while (itr.hasNext()) System.out.println(itr.next());