- RGB
- R(red) : 0~256
- G(green) : 0~256
- B(blue) : 0~256
- 숫자의 해석
- 0,0,0 (검정색)
- 256,256,256 (흰색)
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.TextArea;
import javax.swing.JTextArea;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class TextAreaEx extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextArea textArea;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TextAreaEx frame = new TextAreaEx();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TextAreaEx() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 520, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField();
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textArea.append(textField.getText()+"\n");
}
});
textField.setBounds(12, 10, 340, 21);
contentPane.add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("New button");
btnNewButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
//textArea.setText(textField.getText()+"\n"); //setText 기존의 것을 지우고 입력
textArea.append(textField.getText()+"\n"); //append 이어서 입력
//this.sayHello(); //this는 어뎁터라는 익명클래스를 의미함 그래서 this를 쓸경우 에러남
TextAreaEx.this.sayHello();
sayHello();
}
});
btnNewButton.setBounds(383, 9, 97, 23);
contentPane.add(btnNewButton);
textArea = new JTextArea();
textArea.setEditable(false);
textArea.setBounds(12, 41, 468, 195);
contentPane.add(textArea);
}
public void sayHello(){
System.out.println("sayHello() 호출");
}
}
2
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JCheckBox;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class CheckBoxEx01 extends JFrame {
private JPanel contentPane;
private JCheckBox CheckBox1;
private JCheckBox CheckBox2;
private JCheckBox CheckBox3;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CheckBoxEx01 frame = new CheckBoxEx01();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public CheckBoxEx01() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
CheckBox1 = new JCheckBox("딸기");
CheckBox1.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) { //체크박스 1개에 클릭이벤트설정
if(CheckBox1.isSelected()){
System.out.println("선택 됨");
}else{
System.out.println("선택 안됨");
}
}
});
CheckBox1.setSelected(true);
CheckBox1.setBounds(8, 18, 127, 23);
contentPane.add(CheckBox1);
CheckBox2 = new JCheckBox("수박");
CheckBox2.setBounds(8, 54, 127, 23);
contentPane.add(CheckBox2);
CheckBox3 = new JCheckBox("사과");
CheckBox3.setBounds(8, 91, 127, 23);
contentPane.add(CheckBox3);
JButton btnNewButton = new JButton("New button");
btnNewButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) { //버튼을 클릭했을때 체크박스 3개의 상태를 출력
String result = "";
if(CheckBox1.isSelected()){
result += CheckBox1.getText() + " ";
}
if(CheckBox2.isSelected()){
result += CheckBox2.getText() + " ";
}
if(CheckBox3.isSelected()){
result += CheckBox3.getText() + " ";
}
System.out.println(result);
}
});
btnNewButton.setBounds(325, 18, 97, 23);
contentPane.add(btnNewButton);
}
}
3
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class RadioButtonEx01 extends JFrame {
private JPanel contentPane;
private final ButtonGroup buttonGroup = new ButtonGroup(); //단일선택을 위해서 버튼 그룹 객체를 생성함
private JRadioButton rbtn2;
private JRadioButton rbtn3;
private JRadioButton rbtn1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
RadioButtonEx01 frame = new RadioButtonEx01();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public RadioButtonEx01() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
rbtn1 = new JRadioButton("딸기");
rbtn1.setSelected(true); //디폴트 값으로 선택됨
buttonGroup.add(rbtn1);
rbtn1.setBounds(8, 21, 121, 23);
contentPane.add(rbtn1); //버튼 그룹에 각각의 버튼을 추가함으로 단일선택 그룹을 생성
rbtn2 = new JRadioButton("수박");
buttonGroup.add(rbtn2);
rbtn2.setBounds(8, 56, 121, 23);
contentPane.add(rbtn2);
rbtn3 = new JRadioButton("사과");
buttonGroup.add(rbtn3);
rbtn3.setBounds(8, 94, 121, 23);
contentPane.add(rbtn3);
JButton btnNewButton = new JButton("New button");
btnNewButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
//버튼으로 단일선택된 값을 가져오기 위해서는 if ~ else if ~ 구문
String result = "";
if(rbtn1.isSelected()){
result += rbtn1.getText();
}else if(rbtn2.isSelected()){
result += rbtn2.getText();
}else if(rbtn3.isSelected()){
result += rbtn3.getText();
}
System.out.println(result);
}
});
btnNewButton.setBounds(325, 21, 97, 23);
contentPane.add(btnNewButton);
}
}
4
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JSlider;
import javax.swing.SwingConstants;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
public class SliderEx01 extends JFrame {
private JPanel contentPane;
private JSlider slider1;
private JSlider slider2;
private JSlider slider3;
private JPanel panel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SliderEx01 frame = new SliderEx01();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public SliderEx01() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 666, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
slider1 = new JSlider();
slider1.setMaximum(256);
slider1.setSnapToTicks(true); //슬라이드를 마우스 있는 곳으로 끊어서 가져옴
slider1.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
//System.out.println(slider1.getValue()); //상태전환시 getValue 슬라이더 값을 가져옴 //연속값을 가져옴
if(panel != null){
panel.setBackground(new Color(slider1.getValue(),slider2.getValue(),slider3.getValue())); //Color 객체를 생성함
}
}
});
/*slider1.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println(slider1.getValue()); //클릭시 getValue 슬라이더 값을 가져옴
}
@Override
public void mouseReleased(MouseEvent e) {
System.out.println(slider.getValue()); //마우스를 땔 때 getValue 슬라이더 값을 가져옴
}
});*/
slider1.setMinorTickSpacing(10);
slider1.setPaintTicks(true);
slider1.setPaintLabels(true);
slider1.setMajorTickSpacing(20);
slider1.setValue(10);
slider1.setBounds(12, 20, 348, 46);
contentPane.add(slider1);
slider2 = new JSlider();
slider2.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if(panel != null){ //stateChange는 가동이 바로되기때문에 panel이 null이면 setBackground실행 못함 (panel은 밑에서 정의되고있음)
panel.setBackground(new Color(slider1.getValue(),slider2.getValue(),slider3.getValue())); //Color 객체를 생성함
}
}
});
slider2.setValue(10);
slider2.setSnapToTicks(true);
slider2.setPaintTicks(true);
slider2.setPaintLabels(true);
slider2.setMinorTickSpacing(10);
slider2.setMaximum(256);
slider2.setMajorTickSpacing(20);
slider2.setBounds(12, 93, 348, 46);
contentPane.add(slider2);
slider3 = new JSlider();
slider3.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
if(panel != null){
panel.setBackground(new Color(slider1.getValue(),slider2.getValue(),slider3.getValue())); //Color 객체를 생성함
}
}
});
slider3.setValue(10);
slider3.setSnapToTicks(true);
slider3.setPaintTicks(true);
slider3.setPaintLabels(true);
slider3.setMinorTickSpacing(10);
slider3.setMaximum(256);
slider3.setMajorTickSpacing(20);
slider3.setBounds(12, 170, 348, 46);
contentPane.add(slider3);
panel = new JPanel(); //패널 초기화 밑에 있음
panel.setBounds(372, 20, 266, 215);
contentPane.add(panel);
}
}
5
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JProgressBar;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class ProgressBarEx01 extends JFrame {
private JPanel contentPane;
private JProgressBar progressBar;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ProgressBarEx01 frame = new ProgressBarEx01();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ProgressBarEx01() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
progressBar = new JProgressBar(); //프로그래스바 초기화
progressBar.setStringPainted(true);
progressBar.setValue(50); //초기값 지정
progressBar.setBounds(12, 10, 394, 14);
contentPane.add(progressBar);
JButton btnNewButton = new JButton("New button");
btnNewButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) { //프로그래스바를 위에서 초기화 했기 때문에 if구문으로 null을 검사할 필요 없음
progressBar.setValue(progressBar.getValue()-10); //프로그래스바를 10% 씩 증가
}
});
btnNewButton.setBounds(12, 34, 97, 23);
contentPane.add(btnNewButton);
JButton button = new JButton("New button");
button.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
progressBar.setValue(progressBar.getValue()+10); //프로그래스바를 10% 씩 감소
}
});
button.setBounds(309, 34, 97, 23);
contentPane.add(button);
}
}
6
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
public class ComboEx01 extends JFrame {
private JPanel contentPane;
private JComboBox comboBox;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ComboEx01 frame = new ComboEx01();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ComboEx01() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
comboBox = new JComboBox();
comboBox.setSelectedIndex(-1);
comboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED){
System.out.println(comboBox.getSelectedItem());
}
}
});
// MVC 모델
// 일을 분업화(클래스 분리)
// 디자인(View) + 데이터(Model) + 제어(Controller) 분리
//comboBox.setModel(new DefaultComboBoxModel(new String[] {"사과", "수박", "딸기"})); //DefaultComboBoxModel 데이터
//comboBox.setModel(new CustomComboBoxModel1()); //클래스 내부 getSize와 getElementAt 메소드를 통해서 데이터를 읽어드림
String[] datas = new String[]{"이순신", "강감찬", "이몽룡"};
comboBox.setModel(new CustomComboBoxModel1(datas)); //매개변수를 통한 초기화
comboBox.setBounds(12, 10, 194, 21);
contentPane.add(comboBox);
JButton btnNewButton = new JButton("New button");
btnNewButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println(comboBox.getSelectedIndex());
//System.out.println((String)comboBox.getSelectedItem());
//System.out.println(datas[comboBox.getSelectedIndex()]); //저장된 데이터에서 가져오는 방식을 추천함
}
});
btnNewButton.setBounds(257, 9, 97, 23);
contentPane.add(btnNewButton);
}
}
import javax.swing.DefaultComboBoxModel;
public class CustomComboBoxModel1 extends DefaultComboBoxModel { //디자인과 데이터를 구분하기 위해 데이터 클래스를 따로 만듦
private String[] datas = null;
public CustomComboBoxModel1() {
this.datas = new String[] { "수박" , "딸기", "키위"};
}
public CustomComboBoxModel1(String[] datas) {
this.datas = datas;
}
@Override
public int getSize() {
// TODO Auto-generated method stub
return datas.length;
}
@Override
public String getElementAt(int index) {
// TODO Auto-generated method stub
return datas[index];
}
}
7
import java.util.ArrayList;
import javax.swing.AbstractListModel;
public class CustomListModel1 extends AbstractListModel<String> {
//String[] datas = new String[]{"사과","딸기","수박"};
//배열말고 ArrayList로 만들어도 됨
ArrayList<String> datas = null;
public CustomListModel1(){
datas = new ArrayList<>();
datas.add("사과");
datas.add("딸기");
datas.add("수박");
}
@Override
public String getElementAt(int index) {
// TODO Auto-generated method stub
//return datas[index];
return datas.get(index);
}
@Override
public int getSize() {
// TODO Auto-generated method stub
//return datas.getsize;
return datas.size();
}
}
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JList;
import javax.swing.AbstractListModel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class ListEx01 extends JFrame {
private JPanel contentPane;
private JList list;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ListEx01 frame = new ListEx01();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ListEx01() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(12, 10, 153, 118);
contentPane.add(scrollPane);
list = new JList();
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
scrollPane.setViewportView(list);
//데이터를 따로 클래스로 만드는 것이 좋음
/*list.setModel(new AbstractListModel() { //익명클래스와 데이터를 읽어드릴 getSize, getElementAt 메소드를 생성함
String[] values = new String[] {"사과", "수박", "키위", "딸기", "사과", "수박", "키위", "딸기"};
public int getSize() {
return values.length;
}
public Object getElementAt(int index) {
return values[index];
}
});*/
list.setModel(new CustomListModel1());
JButton btnNewButton = new JButton("New button");
btnNewButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println(list.getSelectedIndex());
System.out.println((String)list.getSelectedValue());
}
});
btnNewButton.setBounds(278, 8, 97, 23);
contentPane.add(btnNewButton);
}
}
8
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.AbstractListModel;
public class CustomZipcode extends AbstractListModel<String>{
ArrayList<String> datas = null;
public CustomZipcode(String dong) throws IOException {
// TODO Auto-generated constructor stub
datas = new ArrayList<>();
BufferedReader br = null;
br = new BufferedReader(new FileReader("C:/java/workspace/ZipSearch/src/zipcode_seoul_utf8.csv"));
String line = "";
while((line = br.readLine()) != null){
String[] address = line.split(",");
if(address[3].startsWith(dong)){
String data = String.format("[%s] %s %s %s %s %s",address[0], address[1], address[2], address[3], address[4], address[5]);
datas.add(data);
}
}
br.close();
}
@Override
public String getElementAt(int index) {
// TODO Auto-generated method stub
return datas.get(index);
}
@Override
public int getSize() {
// TODO Auto-generated method stub
return datas.size();
}
}
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.AbstractListModel;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
public class ListSearch extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JList list;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ListSearch frame = new ListSearch();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ListSearch() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(12, 52, 410, 200);
contentPane.add(scrollPane);
list = new JList();
scrollPane.setViewportView(list);
textField = new JTextField();
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String strDong = textField.getText();
try {
list.setModel(new CustomZipcode(strDong));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
textField.setBounds(12, 10, 293, 21);
contentPane.add(textField);
textField.setColumns(10);
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(325, 9, 97, 23);
contentPane.add(btnNewButton);
}
}
9
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.SpinnerListModel;
import javax.swing.SpinnerDateModel;
import java.util.Date;
import java.util.Calendar;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
public class SpinnerEx01 extends JFrame {
private JPanel contentPane;
private JSpinner spinner_1;
private JSpinner spinner;
private JSpinner spinner_2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SpinnerEx01 frame = new SpinnerEx01();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public SpinnerEx01() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
spinner = new JSpinner();
spinner.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
System.out.println((Integer)spinner.getValue()); //spinner getvalue 타입이 object이므로 Integer로 형변환함
}
});
spinner.setModel(new SpinnerNumberModel(0, 0, 10, 2));
spinner.setBounds(12, 10, 238, 22);
contentPane.add(spinner);
spinner_1 = new JSpinner();
spinner_1.setModel(new SpinnerListModel(new String[] {"\uC0AC\uACFC", "\uC218\uBC15", "\uB538\uAE30", "\uD0A4\uC704"}));
spinner_1.setBounds(12, 55, 238, 22);
contentPane.add(spinner_1);
spinner_2 = new JSpinner();
spinner_2.setModel(new SpinnerDateModel(new Date(1466521200000L), new Date(1466521200000L), new Date(1498057200000L), Calendar.DAY_OF_MONTH));
spinner_2.setBounds(12, 105, 238, 22);
contentPane.add(spinner_2);
}
}
10
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class tableEx01 extends JFrame {
private JPanel contentPane;
private JTable table;
private JButton btnNewButton;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
tableEx01 frame = new tableEx01();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public tableEx01() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 644, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(12, 10, 484, 217);
contentPane.add(scrollPane);
table = new JTable();
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println(table.getSelectedRow()); //선택한 행인덱스 출력
System.out.println(table.getSelectedColumn()); //선택한 열인덱스 출력
System.out.println(table.getValueAt(table.getSelectedRow(), table.getSelectedColumn())); //선택한 값 출력
}
});
scrollPane.setViewportView(table);
/*table.setModel(new DefaultTableModel(
new Object[][] {
{"d", "d", "d", "d", "d"},
{"d", "d", "d", "d", "d"},
{"d", "d", "d", "d", "d"},
{"d", "d", "d", "d", "d"},
{"d", "d", "d", "d", "d"},
{"d", "d", "d", "d", "d"},
{"d", "d", "d", "d", "d"},
{"d", "d", "d", "d", "d"},
{"d", "d", "d", "d", "d"},
{"d", "d", "d", "d", null},
},
new String[] {
"1\uAC00", "2\uB098", "3\uB2E4", "4\uB77C", "5\uB9C8"
}
) {
boolean[] columnEditables = new boolean[] { //수정가능 컬럼 정하기
true, false, false, false, false
};
public boolean isCellEditable(int row, int column) {
return columnEditables[column];
}
});*/
table.setModel(new CustomTableModel1());
btnNewButton = new JButton("New button");
btnNewButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println(table.getSelectedRow()); //선택한 행인덱스 출력
System.out.println(table.getSelectedColumn()); //선택한 열인덱스 출력
System.out.println(table.getValueAt(table.getSelectedRow(), table.getSelectedColumn())); //선택한 값 출력
}
});
btnNewButton.setBounds(508, 13, 97, 23);
contentPane.add(btnNewButton);
}
}
import javax.swing.table.AbstractTableModel;
public class CustomTableModel1 extends AbstractTableModel {
String[][] datas = new String[][]{ //데이터
{"d", "d", "d", "d", "d"},
{"d", "d", "d", "d", "d"},
{"d", "d", "d", "d", "d"},
{"d", "d", "d", "d", "d"},
{"d", "d", "d", "d", "d"},
{"d", "d", "d", "d", "d"},
{"d", "d", "d", "d", "d"},
{"d", "d", "d", "d", "d"},
{"d", "d", "d", "d", "d"},
{"d", "d", "d", "d", null},
};
String[] columnNames = new String[] { //컬럼명
"1가", "2나", "3다", "4라", "5마"
};
@Override
public String getColumnName(int column) {
// TODO Auto-generated method stub
return columnNames[column];
}
@Override
public int getColumnCount() {
// TODO Auto-generated method stub
return datas[0].length;
}
@Override
public int getRowCount() {
// TODO Auto-generated method stub
return datas.length;
}
@Override
public Object getValueAt(int arg0, int arg1) {
// TODO Auto-generated method stub
return datas[arg0][arg1];
}
}
11
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class OptionPaneEx01 extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
OptionPaneEx01 frame = new OptionPaneEx01();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public OptionPaneEx01() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("New button");
btnNewButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
//JOptionPane.showMessageDialog(OptionPaneEx01.this, "메세지"); //메세지 다이얼로그를 띄움
//JOptionPane.showMessageDialog(OptionPaneEx01.this, "메세지","타이틀", JOptionPane.WARNING_MESSAGE); //메시지, 제목, 아이콘 띄움
JOptionPane.showMessageDialog(OptionPaneEx01.this, "메세지","타이틀", JOptionPane.INFORMATION_MESSAGE); //아이콘 여러가지
}
});
btnNewButton.setBounds(12, 10, 97, 23);
contentPane.add(btnNewButton);
JButton btnNewButton_1 = new JButton("New button");
btnNewButton_1.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
//JOptionPane.showConfirmDialog(OptionPaneEx01.this, "메세지"); //this쓰는 이유는 이너클래스라서 외부와 연결필요
int result = JOptionPane.showConfirmDialog(OptionPaneEx01.this, "메세지","타이틀",JOptionPane.OK_CANCEL_OPTION); //버튼 "확인, 취소"
System.out.println(result); // 확인, 취소, x표시 누르는것 마다 값이 다르게 출력됨
}
});
btnNewButton_1.setBounds(12, 43, 97, 23);
contentPane.add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("New button");
btnNewButton_2.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
String result = JOptionPane.showInputDialog("메세지"); //내용을 입력할 수 있는 다이얼로그 뜸 //내용을 String으로 받음
System.out.println(result);
}
});
btnNewButton_2.setBounds(12, 76, 97, 23);
contentPane.add(btnNewButton_2);
}
}
12
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class DialogEx01 extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DialogEx01 frame = new DialogEx01();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public DialogEx01() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //x버튼 누르면 프로그램 종료
setBounds(100, 100, 688, 399);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("New button");
btnNewButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.out.println("1");
SubDialog sb = new SubDialog();
System.out.println("2");
sb.setModal(true); //바닥창이 선택불가 하도록 만듦
System.out.println("3 : "+sb.data);
sb.setVisible(true); //subDialog 객채를 띄움 //자식창을 띄우고 메인 스레드는 여기서 멈춤
System.out.println("4 : "+sb.data); //자식창이 닫히면 메인 스레드가 4번 읽음 //OK버튼을 누른 뒤에 변경된 데이터값을 읽음
}
});
btnNewButton.setBounds(12, 10, 97, 23);
contentPane.add(btnNewButton);
}
}
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class SubDialog extends JDialog {
private final JPanel contentPanel = new JPanel();
public String data = "처음데이터";
/**
* Launch the application.
*/
/*public static void main(String[] args) {
try {
SubDialog dialog = new SubDialog();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); //메모리에서 현재 창을 지움
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}*/
/**
* Create the dialog.
*/
public SubDialog() {
//this.setDefaultCloseOperation(JDialog.EXIT_ON_CLOSE); 자식창이 프로그램 전체 종료불가함
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); //x표시 누르면 메모리에서 현재 창을 지움
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setLayout(new FlowLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
data = "OK 버튼 누른 데이터"; //OK 누르면 데이터 입력함
SubDialog.this.dispose(); //OK 누르면 현재창 닫기
}
});
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
SubDialog.this.dispose(); //Cencel 누르면 현재창 닫기
}
});
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
}
}
}
13
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFileChooser;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class DialogEx02 extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DialogEx02 frame = new DialogEx02();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public DialogEx02() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnNewButton = new JButton("New button");
btnNewButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
//파일선택기
JFileChooser fileChooser = new JFileChooser("c:\\"); //디폴트 위치를 c드라이브로 정함
int result = fileChooser.showOpenDialog(DialogEx02.this); //파일선택버튼과 취소값을 읽음
if(result == JFileChooser.APPROVE_OPTION){
System.out.println("YES");
//파일에대한 경로
System.out.println(fileChooser.getSelectedFile().getAbsolutePath()); //절대경로 출력
System.out.println(fileChooser.getSelectedFile().getName()); //이름 출력
}else if(result == JFileChooser.CANCEL_OPTION){
System.out.println("NO");
}else{
System.out.println("X");
}
}
});
btnNewButton.setBounds(12, 10, 97, 23);
contentPane.add(btnNewButton);
JButton btnNewButton_1 = new JButton("New button");
btnNewButton_1.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
Color color = JColorChooser.showDialog(DialogEx02.this, "팔레트", Color.RED); //컬러선택 다이얼로그 띄움
System.out.println(color.toString()); //RGB 컬러값 출력
System.out.println(color.getRed());
System.out.println(color.getGreen());
System.out.println(color.getBlue());
}
});
btnNewButton_1.setBounds(12, 54, 97, 23);
contentPane.add(btnNewButton_1);
}
}
14
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;
public class CustomZipTable extends AbstractTableModel {
//데이터
ArrayList<String[]> datas2 = new ArrayList<String[]>();
//컬럼명
String[] columnNames = new String[] {
"우편번호", "시", "구", "동", "상세주소1", "상세주소2"
};
public CustomZipTable(String dong) throws IOException {
// TODO Auto-generated constructor stub
BufferedReader br = null;
br = new BufferedReader(new FileReader("C:/java/workspace/ZipSearch/src/zipcode_seoul_utf8.csv"));
String line = "";
while((line = br.readLine()) != null){
String[] address = line.split(",");
if(address[3].startsWith(dong)){
String[] data = {address[0], address[1], address[2], address[3], address[4], address[5]};
datas2.add(data);
}
}
br.close();
}
@Override
public String getColumnName(int column) {
// TODO Auto-generated method stub
return columnNames[column];
}
@Override
public int getColumnCount() {
// TODO Auto-generated method stub
return datas2.get(0).length;
}
@Override
public int getRowCount() {
// TODO Auto-generated method stub
return datas2.size();
}
@Override
public Object getValueAt(int arg0, int arg1) {
// TODO Auto-generated method stub
return datas2.get(arg0)[arg1];
}
}
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JTable;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JScrollPane;
public class TableSearch extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTable table;
private JButton button;
private JScrollPane scrollPane;
private CustomZipTable newdata;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TableSearch frame = new TableSearch();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TableSearch() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 635, 332);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textField = new JTextField();
textField.setBounds(12, 10, 377, 23);
contentPane.add(textField);
textField.setColumns(10);
scrollPane = new JScrollPane();
scrollPane.setBounds(12, 43, 603, 241);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
JButton btnNewButton = new JButton("검색");
btnNewButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
String strDong = textField.getText();
//한글입력
if(!strDong.matches(".*[ㄱ-하-ㅣ가-힣]+.*") || strDong.matches(".*[a-zA-Z]+.*")){
JOptionPane.showMessageDialog(TableSearch.this, "한글만 입력이 가능합니다","입력오류", JOptionPane.WARNING_MESSAGE);
}else
//두글자 이상 입력
if(strDong.length()<2){
JOptionPane.showMessageDialog(TableSearch.this, "두글자 이상 입력하셔야합니다","입력오류", JOptionPane.WARNING_MESSAGE);
}else{
try {
newdata = new CustomZipTable(strDong);
table.setModel(newdata);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
btnNewButton.setBounds(401, 10, 97, 23);
contentPane.add(btnNewButton);
button = new JButton("저장");
button.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
// 파일선택기 부름
JFileChooser fileChooser = new JFileChooser("c:\\"); //디폴트경로 지정
int result = fileChooser.showSaveDialog(TableSearch.this);
if (result == JFileChooser.APPROVE_OPTION) {
BufferedWriter bw = null;
try {
//파일선택기에 입력한 파일이름과 경로값을 받음 → 그리고 파일 생성
bw = new BufferedWriter(new FileWriter(fileChooser.getSelectedFile().getAbsolutePath() + ".txt"));
//파일내용 쓰기
if(newdata != null){
//제목먼저 쓰기
bw.write(newdata.columnNames[0]);
for(int i=1;i<newdata.columnNames.length;i++){
bw.write(","+newdata.columnNames[i]); //쉽표로 구분
}
bw.write("\r\n"); //한줄씩 띄움
//데이터 쓰기
for (int j = 0; j < newdata.datas2.size(); j++) {
bw.write(newdata.datas2.get(j)[0]);
for (int k = 1; k < newdata.datas2.get(0).length; k++) {
bw.write("," + newdata.datas2.get(j)[k]);
}
bw.write("\r\n");
}
}
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} finally {
if(bw != null) try{ bw.close();} catch(IOException e3){}
}
}
}
});
button.setBounds(510, 10, 97, 23);
contentPane.add(button);
}
}
댓글 없음:
댓글 쓰기