Swing ( Ⅲ )
1. JMenu
ex> Test01_JMenu.java
메뉴생성 및 메뉴의 책상을 누르면 해당 색상으로 바탕화면 변경.
package test02;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
class MyFrame01 extends JFrame implements ActionListener{
JMenuBar bar=new JMenuBar();
JMenu menu1=new JMenu("파일");
JMenu menu2=new JMenu("편집");
JMenuItem item1=new JMenuItem("빨강");
JMenuItem item2=new JMenuItem("파랑");
JMenuItem item3=new JMenuItem("노랑");
JMenuItem item4=new JMenuItem("종료");
Container con;
public MyFrame01(){
con=getContentPane();
//프레임에 메뉴바 붙이기
setJMenuBar(bar);
//메뉴바에 메뉴붙이기
bar.add(menu1);
bar.add(menu2);
//메뉴에 하위메뉴(메뉴아이템)붙이기
menu1.add(item1);
menu1.add(item2);
menu1.add(item3);
menu1.add(item4);
//메뉴아이템에 이벤트리스너 등록하기
item1.addActionListener(this);
item2.addActionListener(this);
item3.addActionListener(this);
item4.addActionListener(this);
setSize(400,400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e){
if(e.getSource()==item1){
con.setBackground(Color.RED);
}else if(e.getSource()==item2){
con.setBackground(Color.BLUE);
}else if(e.getSource()==item3){
con.setBackground(Color.YELLOW);
}else if(e.getSource()==item4){
System.exit(0);
}
}
}
public class Test01_JMenu{
public static void main(String[] args) {
new MyFrame01();
}
}
2. JList
ex> Test02_JList.java
package test02;
import java.awt.BorderLayout;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
class MyFrame02 extends JFrame{
JList<String> list;
JComboBox<String> combo;
public MyFrame02() {
setLayout(new BorderLayout());
String[] slist={"홍길동","김철수","이영희"};
list=new JList<String>(slist);
String[] part={"영업부","생산부"};
combo=new JComboBox<String>(part);
add(combo,BorderLayout.NORTH);
add(list,BorderLayout.CENTER);
setSize(400,400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
public class Test02_JList{
public static void main(String[] args) {
new MyFrame02();
}
}
ex> Test03_JList.java
추가 버튼으로 입력한 내용을 추가한다. (삭제)
package test02;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
class MyFrame03 extends JFrame implements ActionListener{
JTextField txt=new JTextField(15);
JButton btnAdd=new JButton("추가");
JButton btnDel=new JButton("삭제");
JPanel pan=new JPanel();
JList<String> list;
//JList와 연결될 모델객체 생성하기
DefaultListModel<String> model=new DefaultListModel<>();
public MyFrame03() {
setLayout(new BorderLayout());
pan.add(txt);
pan.add(btnAdd);
pan.add(btnDel);
model.addElement("홍길동");
model.addElement("홍길서");
model.addElement("홍길남");
model.addElement("홍길북");
//모델객체와 연결된 JList생성하기
list=new JList<String>(model);
add(pan,BorderLayout.NORTH);
add(new JScrollPane(list),BorderLayout.CENTER);
btnAdd.addActionListener(this);
btnDel.addActionListener(this);
//텍스트필드에 키보드로 키값을 누를때마다 이를 감지하는 이벤트 리스너 등록
txt.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
//누른 키값 얻어오기
int keyCode=e.getKeyCode();
//누른 키가 엔터키인경우
if(keyCode==KeyEvent.VK_ENTER){
addData();//입력된 문자열을 Model객체에 추가하기
}
}
});
setSize(400,400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
//추가버튼을 누른경우
if(e.getSource()==btnAdd){
addData();
}else if(e.getSource()==btnDel){
//삭제버튼을 누른 경우
//선택된 인덱스번호 얻어오기
int index=list.getSelectedIndex();
//선택한 항목이 없는 경우
if(index==-1){
JOptionPane.showMessageDialog(this,"삭제할 항목을 선택하세요!");
return;//메소드 끝내기
}else{
//선택한 항목 얻어오기
String value=list.getSelectedValue();
//부모컴포넌트, 보여줄메시지, 타이틀, 버튼형태
int btn=JOptionPane.showConfirmDialog(this,
value+"님을 정말로 삭제할까요?",
"삭제",
JOptionPane.YES_NO_OPTION
);
//아니오 버튼을 누른 경우
if(btn==JOptionPane.NO_OPTION){
return;
}
}
//해당 인덱스데이터를 Model에서 삭제하기
model.remove(index);
}
}
private void addData(){
//입력된 문자열 얻어오기
String str=txt.getText();
//데이터 추가는 Model객체에 해야 함
model.addElement(str);
txt.setText("");
txt.requestFocus();
}
}
public class Test03_JList{
public static void main(String[] args) {
new MyFrame03();
}
}
3. JTable
ex> Test04_JTable.java
package test02;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
class MyFrame04 extends JFrame{
JTable tb;
public MyFrame04() {
setLayout(new BorderLayout());
//JTable(Object[][] rowData, Object[] columnNames)
String[][] rowData={
{"홍길동","010-111-1234","경기도"},
{"홍길서","010-222-3333","서울"},
{"홍길남","010-333-4567","노원구"},
{"홍길북","010-444-9876","경기도"}};
String colNames[]={"이름","전화번호","주소"};
//JTable생성
tb=new JTable(rowData,colNames);
//JTable을 Center영역에 붙이기
add(new JScrollPane(tb),BorderLayout.CENTER);
setSize(500,500);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
public class Test04_JTable{
public static void main(String[] args) {
new MyFrame04();
}
}
ex> Test05_JTable.java
package test02;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
class MyFrame05 extends JFrame implements ActionListener{
JTextField txtName=new JTextField(5);
JTextField txtPhone=new JTextField(5);
JTextField txtAddr=new JTextField(10);
JPanel pan=new JPanel();
JButton btnAdd=new JButton("추가");
JButton btnDel=new JButton("삭제");
JTable tb;
DefaultTableModel model;
public MyFrame05() {
setLayout(new BorderLayout());
pan.add(new JLabel("이름"));
pan.add(txtName);
pan.add(new JLabel("전화"));
pan.add(txtPhone);
pan.add(new JLabel("주소"));
pan.add(txtAddr);
pan.add(btnAdd);
pan.add(btnDel);
//public DefaultTableModel(Vector columnNames, int rowCount)
//컬럼명을 Vector에 저장하기
Vector<String> cols=new Vector<String>();
cols.add("이름");
cols.add("전화");
cols.add("주소");
//JTable과 연결될 모델객체 생성
model=new DefaultTableModel(cols,0);
//model객체와 연결되는 JTable생성
tb=new JTable(model);
add(pan,BorderLayout.NORTH);
add(new JScrollPane(tb),BorderLayout.CENTER);
//버튼에 이벤트리스너등록하기
btnAdd.addActionListener(this);
btnDel.addActionListener(this);
setSize(500,500);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
// 추가버튼을 누른경우
if(e.getSource()==btnAdd){
//입력된 데이터 얻어오기
String name=txtName.getText();
String phone=txtPhone.getText();
String addr=txtAddr.getText();
//모델객체에 데이터 추가하기
String []rows={name,phone,addr};
model.addRow(rows);
}else if(e.getSource()==btnDel){
//선택한 행번호 얻어오기
int index=tb.getSelectedRow();
//선택한 행이 없는 경우
if(index==-1){
JOptionPane.showMessageDialog(this,"삭제할 회원 선택!");
return;
}
//삭제는 Model객체에서 해야 함!
model.removeRow(index);
}
}
}
public class Test05_JTable{
public static void main(String[] args) {
new MyFrame05();
}
}
4. JDialog
ex> Test06_Dlg.java
로그인 버튼 - 로그인 팝업 창 오픈 - 아이디/비번 입력 체크
package test02;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
class MyFrame06 extends JFrame implements ActionListener{
JButton btn1=new JButton("로그인");
JLabel lbl=new JLabel();
public MyFrame06() {
setLayout(new FlowLayout());
add(btn1);
add(lbl);
btn1.addActionListener(this);
setSize(500,500);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
@Override
public void actionPerformed(ActionEvent e) {
LoginDlg dlg=new LoginDlg(this);
dlg.txtId.setText("admin");
}
}
class LoginDlg extends JDialog implements ActionListener{
MyFrame06 frm;
JTextField txtId=new JTextField();
JTextField txtPwd=new JTextField();
JButton btnOk=new JButton("확인");
JButton btnCancel=new JButton("취소");
public LoginDlg(MyFrame06 frm){
this.frm=frm;
setLayout(new GridLayout(3,2));
add(new JLabel("아이디"));
add(txtId);
add(new JLabel("비밀번호"));
add(txtPwd);
add(btnOk);
add(btnCancel);
btnOk.addActionListener(this);
setSize(200,120);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(txtId.getText().equals("song") && txtPwd.getText().equals("1234")){
frm.lbl.setText(txtId.getText()+"님 환영합니다.");
//다이얼로그 닫기
dispose();
}else{
JOptionPane.showMessageDialog(this,"아이디 또는 비밀번호가 틀려요!");
}
}
}
public class Test06_Dlg{
public static void main(String[] args) {
new MyFrame06();
}
}