- [Java 기본]Swing

Posted by 겨울에
2011. 5. 14. 16:32 scrap/ Java/JSP
출처 : http://cafe.naver.com/litave/404


//===========================================================================//
  본 내용은 2002년 제가 Java 강의를 수강하며 정리 했던 내용을
    기본으로 하여 정리하였습니다.
  - 마침 java 기초를 전파할 기회가 생겨 핑계김에 정리해 가려 합니다.
  작성자 : litwave
//---------------------------------------------------------------------------//

<목차>
1. awt 와 Swing 의 비교
2. 예제 소스
  - 수업시간에 진행했던 소스만 올립니다.

//---------------------------------------------------------------------------//

1. awt 와 Swing 의 비교
                          awt                       swing
    사용시작버젼         1.1미만                   1.2이상
    import               java.awt                  java.awt(Layout Manager 때문에 필요)
                         java.awt.event            java.awt.event
                                                   javax.swing
                                                   javax.swing.border
                                                   javax.swing.event
                                                   javax.swing.tree     //탐색기의 트리형식을 이용할 수 있다
                                                   javax.swing.table    //엑셀같은 형태를 이용할 수 있다

    특징                 platform 종속적           platform 독립적
                         중량 Component            경량 Component      //시스템이 바뀔 경우 이동이 쉽다.
                         단일 Frame                다중 Frame 사용

//---------------------------------------------------------------------------//
2. 예제 소스

// Ex0205_01.java : 파일 선택하기
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Ex0205_01_Sub extends JFrame {
    //private FileDialog fd = new FileDialog(this, "열기", FileDialog.LOAD);
    private JFileChooser jfc = new JFileChooser("c:");
    public Ex0205_01_Sub() {
        super("Test");
        this.init();
        this.start();
        this.setSize(300200);
        this.setVisible(true);
        jfc.showOpenDialog(this);
        System.out.println("선택된 파일 : " + jfc.getSelectedFile());
        //jfc.showSaveDialog(this);
    }
    public void init(){}
    public void start(){}
}
public class Ex0205_01 {
    public static void main(String[] ar) {
        Ex0205_01_Sub es = new Ex0205_01_Sub();
    }
}

//---------------------------------------------------------------------------//
// Ex0205_02.java : Popup 메시지 출력
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Ex0205_02_Sub extends JFrame {
    public Ex0205_02_Sub() {
        super("Test");
        this.init();
        this.start();
        this.setSize(300200);
        this.setVisible(true);
        /*JOptionPane.showMessageDialog(this, 
            "시스템오류\n치명적인 오류입니다.", "경고", 
                                        JOptionPane.ERROR_MESSAGE);*/
        JOptionPane.showInputDialog(this"좋아하는 연예인?");
    }
    public void init() { }
    public void start() { }
}
public class Ex0205_02 {
    public static void main(String[] ar) {
        Ex0205_02_Sub es = new Ex0205_02_Sub();
    }
}


//---------------------------------------------------------------------------//
// Ex0205_03.java : JButton 테스트
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Ex0205_03_Sub extends JFrame {
    private JToolBar jtb = new JToolBar();
    private JButton jbt = new JButton(new ImageIcon("image/new.gif"));
    private JButton jbt1 = new JButton(new ImageIcon("aaa1.gif"));
    private JButton jbt2 = new JButton(new ImageIcon("aaa2.gif"));
    private JButton jbt3 = new JButton(new ImageIcon("aaa3.gif"));
    private JRootPane jrp;
    private Container con;
    private JSplitPane jsp = new JSplitPane();
    public Ex0205_03_Sub() {
        super("Test");
        this.init();
        this.start();
        this.setSize(300200);
        this.setVisible(true);
    }
    public void init() {
        jrp = this.getRootPane();
        con = jrp.getContentPane();
        con.setLayout(new BorderLayout());
        jtb.add(jbt);
        jtb.add(jbt1);
        jtb.add(jbt2);
        jtb.add(jbt3);
        con.add("North", jtb);
        con.add("Center", jsp);
    }
    public void start() { }
}
public class Ex0205_03 {
    public static void main(String[] ar) {
        Ex0205_03_Sub es = new Ex0205_03_Sub();
    }
}


//---------------------------------------------------------------------------//
// Ex0205_04.java : Event 테스트
import java.awt.*;
import java.awt.event.*;
class Ex0205_04_Sub extends Frame implements ActionListener {
    private Button bt = new Button("1번");
    private Button bt1 = new Button("2번");
    private Button bt2 = new Button("3번");
    private Panel p = new Panel();
    private Panel p1 = new Panel();
    private Panel p2 = new Panel();
    private Panel pp, pp1;
    private CardLayout cl = new CardLayout();
    public Ex0205_04_Sub() {
        super("Test");
        this.init();
        this.start();
        this.setSize(300200);
        this.setVisible(true);
    }
    public void init() {
        this.setLayout(new BorderLayout());
        pp = new Panel(new FlowLayout());
        pp.add(bt);
        pp.add(bt1);
        pp.add(bt2);
        pp1 = new Panel(cl);
        p.setBackground(Color.red);
        p1.setBackground(Color.green);
        p2.setBackground(Color.blue);
        pp1.add(p, "first");
        pp1.add(p1, "second");
        pp1.add(p2, "third");
        this.add("North", pp);
        this.add("Center", pp1);
    }
    public void start() {
        bt.addActionListener(this);
        bt1.addActionListener(this);
        bt2.addActionListener(this);
    }
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == bt) {
            cl.show(pp1, "first");

        } else if(e.getSource() == bt1) {
            cl.show(pp1, "second");

        } else if(e.getSource() == bt2) {
            cl.show(pp1, "third");
        }
    }
}
public class Ex0205_04 {
    public static void main(String[] ar) {
        Ex0205_04_Sub es = new Ex0205_04_Sub();
    }
}

//---------------------------------------------------------------------------//
// Ex0205_05.java : JTabbedPane 테스트
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Ex0205_05_Sub extends JFrame {
    private JRootPane jrp;
    private Container con;
    private JTabbedPane jtp = new JTabbedPane();
    private JPanel jp = new JPanel();
    private JPanel jp1 = new JPanel();
    private JPanel jp2 = new JPanel();
    public Ex0205_05_Sub() {
        super("Test");
        this.init();
        this.start();
        this.setSize(300200);
        this.setVisible(true);
    }
    public void init() {
        jrp = this.getRootPane();
        con = jrp.getContentPane();
        con.setLayout(new BorderLayout());
        jp.setBackground(Color.red);
        jp1.setBackground(Color.green);
        jp2.setBackground(Color.blue);
        jtp.addTab("1번", jp);
        jtp.addTab("2번", jp1);
        jtp.addTab("3번", jp2);
        con.add("Center", jtp);
    }
    public void start() { }
}
public class Ex0205_05 {
    public static void main(String[] ar) {
        Ex0205_05_Sub es = new Ex0205_05_Sub();
    }
}


//---------------------------------------------------------------------------//
// Ex0205_06.java : JTree 테스트
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
class Ex0205_06_Sub extends JFrame{
    private JRootPane jrp;
    private Container con;
    private JLabel jlb = new JLabel("JTree !!"JLabel.CENTER);
    private JButton jbt = new JButton("확인");
    private DefaultMutableTreeNode root = new DefaultMutableTreeNode("전세계");
    private JTree jt = new JTree(root);
    private JScrollPane jsp = new JScrollPane(jt);

    private DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("대한민국");
    private DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("미국");
    private DefaultMutableTreeNode child3 = new DefaultMutableTreeNode("일본");

    public Ex0205_06_Sub() {
        super("Test");
        this.init();
        this.setSize(300200);
        this.setVisible(true);
    }
    public void init() {
        jrp = this.getRootPane();
        con = jrp.getContentPane();
        con.setLayout(new BorderLayout());
        jlb.setFont(new Font("휴먼옛체"Font.BOLD20));
        con.add("North", jlb);
        con.add("South", jbt);
        root.add(child1);
        root.add(child2);
        root.add(child3);
        con.add("Center", jsp);
    }
}
public class Ex0205_06 {
    public static void main(String[] ar) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch(Exception ee) { }
        Ex0205_06_Sub es = new Ex0205_06_Sub();
    }
}

//---------------------------------------------------------------------------//
// Ex0205_07.java : JTable 테스트
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;
class Ex0205_07_Sub extends JFrame {
    private JRootPane jrp;
    private Container con;
    private JLabel jlb = new JLabel("JTable !!"JLabel.CENTER);
    private JButton jbt = new JButton("확인");
    private DefaultTableModel dtm = new DefaultTableModel(310);
    private DefaultTableColumnModel dtcm = new DefaultTableColumnModel();
    private TableColumn[] tc = new TableColumn[3];
    private DefaultTableCellRenderer[] dtcr = new DefaultTableCellRenderer[3];
    private DefaultCellEditor[] dce = new DefaultCellEditor[3];
    private DefaultListSelectionModel dlsm = new DefaultListSelectionModel();
    private JTableHeader jth = new JTableHeader(dtcm);
    private JTable jt = new JTable(dtm, dtcm, dlsm);
    private JScrollPane jsp = new JScrollPane(jt);
    public Ex0205_07_Sub() {
        super("Test");
        this.init();
        this.setSize(300200);
        this.setVisible(true);
    }
    public void init() {
        jrp = this.getRootPane();
        con = jrp.getContentPane();
        con.setLayout(new BorderLayout());
        jlb.setFont(new Font("휴먼옛체"Font.BOLD20));
        con.add("North", jlb);
        con.add("South", jbt);
        jsp.setBorder(new BevelBorder(BevelBorder.RAISED));

        dtcr[0] = new DefaultTableCellRenderer();
        dce[0] = new DefaultCellEditor(new JCheckBox());
        tc[0] = new TableColumn(075, dtcr[0], dce[0]);
        tc[0].setHeaderValue("순서");
        dtcm.addColumn(tc[0]);
        dtcr[1] = new DefaultTableCellRenderer();
        dce[1] = new DefaultCellEditor(new JComboBox());
        tc[1] = new TableColumn(175, dtcr[1], dce[1]);
        tc[1].setHeaderValue("이름");
        dtcm.addColumn(tc[1]);
        dtcr[2] = new DefaultTableCellRenderer();
        dce[2] = new DefaultCellEditor(new JTextField());
        tc[2] = new TableColumn(275, dtcr[2], dce[2]);
        tc[2].setHeaderValue("주민번호");
        dtcm.addColumn(tc[2]);
        jt.setTableHeader(jth);
        con.add("Center", jsp);
    }
}
public class Ex0205_07 {
    public static void main(String[] ar) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch(Exception ee) { }
        Ex0205_07_Sub es = new Ex0205_07_Sub();
    }
}


//---------------------------------------------------------------------------//
// Ex0205_08.java : JTable 테스트
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;

class Ex0205_08_Sub extends JFrame {
    private JRootPane jrp;
    private Container con;
    private JLabel jlb = new JLabel("JTable !!"JLabel.CENTER);
    private JButton jbt = new JButton("확인");
    private String[][] str = {{"AAA""BBB""CCC"}, {"DDD""EEE""FFF"}, {"GGG""HHH""III"}};
    private String[] str1 = {"1""2""3"};
    private JTable jt = new JTable(str, str1);
    private JScrollPane jsp = new JScrollPane(jt);
    public Ex0205_08_Sub() {
        super("Test");
        this.init();
        this.setSize(300200);
        this.setVisible(true);
    }
    public void init() {
        jrp = this.getRootPane();
        con = jrp.getContentPane();
        con.setLayout(new BorderLayout());
        jlb.setFont(new Font("휴먼옛체"Font.BOLD20));
        con.add("North", jlb);
        con.add("South", jbt);
        jsp.setBorder(new BevelBorder(BevelBorder.RAISED));
        con.add("Center", jsp);
    }
}
public class Ex0205_08 {
    public static void main(String[] ar) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch(Exception ee) { }
        Ex0205_08_Sub es = new Ex0205_08_Sub();
    }
}



//---------------------------------------------------------------------------//
// Ho0205_01.java : JComboBox 테스트
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Ho0205_01_Sub extends JFrame {
    private JRootPane jrp;
    private Container con;
    private String[] items = {"자전거""자동차""오토바이""스키""보드""신발""지하철""기차""맨발""개발""닭발"};
    private JComboBox jcb = new JComboBox(items);
    private JScrollPane jp = new JScrollPane(jcb);
    public Ho0205_01_Sub() {
        super("콤보박스에 내용 적기");
        init();
        start();
        setSize(300,50);
        setLocation(300,200);
        setVisible(true);
    }
    public void init() {
        jrp = this.getRootPane();
        con = jrp.getContentPane();
        con.setLayout(new BorderLayout());
        jcb.setEditable(true);
        con.add("Center", jcb);
    
    }
    public void start() { 
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

public class Ho0205_01 {
    public static void main(String [] ar) {
        Ho0205_01_Sub h1s = new Ho0205_01_Sub();
    }
}


//---------------------------------------------------------------------------//
// Ho0205_02.java : JPasswordField 테스트
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

class Ho0205_02_Sub extends JFrame {
    private JRootPane jrp;
    private Container con;
    private JPasswordField jpf = new JPasswordField();
    
    public Ho0205_02_Sub() {
        super("JPasswordField 연습");
        init();
        start();
        setSize(300,70);
        setLocation(300,300);   
        setVisible(true); 
    }
    public void init() { 
        jrp = this.getRootPane();
        con = jrp.getContentPane();
        con.setLayout(new BorderLayout());
        jpf.setEchoChar('●');
        jpf.setBorder(new TitledBorder("암호"));
        con.add("Center", jpf);
    }
    public void start() { 
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
public class Ho0205_02 {
    public static void main(String [] ar) {
        Ho0205_02_Sub h2s = new Ho0205_02_Sub();
    }
}

//---------------------------------------------------------------------------//
// Ho0205_03.java : JProgressBar 테스트
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

class WorkPanel extends JPanel {
    private int nValue;
    private int xy, w, h;
    public void paint(Graphics g) {
        for(int i=0; i < nValue; i++) {
            x = (int)(getSize().width * i / 200.0f);
            w = getSize().width - 2 * x;
            y = (int)(getSize().height * i / 200.0f);
            h = getSize().height - 2 * y;
            g.setColor(new Color(00, i*2 + 50));
            g.fillRect(xy, w, h);   
        }
        g.setColor(Color.black);
        g.drawRect(xy, w, h);
    }
    public void setNValue(int i) {
        nValue = i;
    }
    public int getNValue() {
        return nValue;
    }
}

class Ho0205_03_Sub extends JFrame implements Runnable {
    private JProgressBar jpb = new JProgressBar(0100);
    private JRootPane jrp;
    private Container con;
    private WorkPanel wp = new WorkPanel();
//    private Ho0205_03_Sub h3s = new Ho0205_03_Sub();
    public Ho0205_03_Sub() {
        super("JProgressBar Test");
        init();
        start();
        setSize(300,200);
        setLocation(300,300);   
        setVisible(true);
    }
    public void init() {
        jrp = this.getRootPane();
        con = jrp.getContentPane();
        con.setLayout(new BorderLayout());
        JPanel jp1 = new JPanel(new BorderLayout());
        jp1.setBorder(new TitledBorder("진행상태"));
        jpb.setStringPainted(true);
        jpb.setIndeterminate(true);
        jp1.add("Center", jpb);
        con.add("South", jp1);
        con.add("Center", wp);
    }
    public void start() { 
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    
    public void run() {
        for(int i=1; i <= 100; i++) {
            wp.setNValue(i);
            wp.repaint();
            try {
                Thread.sleep(100);
            } catch(Exception ee) { }
            jpb.setValue(i);
            jpb.setString("현재 : " + (int)(jpb.getPercentComplete() * 100+ "%");   
        } 
    }
}

public class Ho0205_03 {
    public static void main(String [] ar) {
        Ho0205_03_Sub h3s = new Ho0205_03_Sub();
        Thread thd = new Thread(h3s);
        try {
            thd.start();
        } catch (Exception ee) { }  
    }
}


//---------------------------------------------------------------------------//
// Ho0205_05.java : 색상 선택하기 프로그램
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Ho0205_05_Sub extends JFrame implements ActionListener{
    //west
    private JLabel jlb1 = new JLabel("Red"JLabel.RIGHT);
    private JLabel jlb2 = new JLabel("Green"JLabel.RIGHT);
    private JLabel jlb3 = new JLabel("Blue"JLabel.RIGHT);
    //cen   //선택 색상 초기값으로 버튼에 표시
    private JTextField redjtf1 = new JTextField("140"5);
    private JTextField greenjtf2 = new JTextField("84");
    private JTextField bluejtf3 = new JTextField("44");
    //ease  //색상 선택 버튼
    private JButton jbt1 = new JButton("색상 선택");
    //south  //Button 선택값 보여주기
    //sou-west
    private JLabel jlb4 = new JLabel("선택 색상 - ");
    //Sou-Cen
    private JTextField jtf4 = new JTextField();
    
    private JRootPane jrp;
    private Container con;
    
    private JColorChooser jcc;
    
    public Ho0205_05_Sub() {
        super("색상 얻어오기");
        init();
        start();
        this.pack();
        Toolkit tk = Toolkit.getDefaultToolkit();
        Dimension di1 = tk.getScreenSize();
        Dimension di2 = this.getSize();
        setLocation((int)(di1.getWidth()/2 - di2.getWidth()/2),
                    (int)(di1.getHeight()/2 - di2.getHeight()/2));
        setVisible(true);
    }
    public void init() {
        jrp = this.getRootPane();
        con = jrp.getContentPane();
        con.setLayout(new BorderLayout());
        //wst
        JPanel jp1 = new JPanel(new GridLayout(3,1));
        jp1.add(jlb1);
        jp1.add(jlb2);
        jp1.add(jlb3);
        con.add("West", jp1);
        //cen
        JPanel jp2 = new JPanel(new GridLayout(3,1));
        jp2.add(redjtf1);
        jp2.add(greenjtf2);
        jp2.add(bluejtf3);
        con.add("Center", jp2);
        con.add("East", jbt1);
        //sou
//        JPanel jp3 = new JPanel(new BorderLayout());
//        jp3.add("West", jlb4);
//        jp3.add("Center", jtf4);
        con.add("South", jlb4);
    }
    public void start() {
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jbt1.addActionListenerthis );
    }
    public void actionPerformed(ActionEvent e) {
        int redgreenblue;
        red = green = blue = 0;
        if(e.getSource() == jbt1) {
            if(redjtf1.getText().length() == 0 || greenjtf2.getText().length() == 0 || bluejtf3.getText().length() == 0) {
                return;
            }
            red = Integer.parseInt(redjtf1.getText().trim()) % 256;
            green = Integer.parseInt(greenjtf2.getText().trim()) % 256;
            blue = Integer.parseInt(bluejtf3.getText().trim()) % 256;     
            Color cc = new Color(redgreenblue);
            jbt1.setBackground(cc);
            jcc = new JColorChooser();
            try { 
                cc = jcc.showDialog(this"색상선택", cc);
                jbt1.setBackground(cc);
                jlb4.setText("선택색상 - R: " + cc.getRed() + ", G: " + cc.getGreen() + ", B: " + cc.getBlue());
            } catch (NullPointerException ee) { 
                cc = new Color(redgreenblue);
                jbt1.setBackground(cc);
                jlb4.setText("선택색상 - R: " + cc.getRed() + ", G: " + cc.getGreen() + ", B: " + cc.getBlue());      
            }
        }
    }
}

public class Ho0205_05 {
    public static void main(String [] ar) {
        Ho0205_05_Sub h5s = new Ho0205_05_Sub();
    }
}



//---------------------------------------------------------------------------//
// Ho0205_09.java : JTree를 이용한 디렉토리 구조 보여주기
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
import java.io.*;

class Ho0205_09_Sub extends JFrame {
    private JRootPane jrp;
    private Container con;
    private File f = new File("c:\\Documents and Settings\\All Users\\");        //여기에 절대 경로 표시
    private DefaultMutableTreeNode root = new DefaultMutableTreeNode(f.getAbsolutePath());
    private JTree jt = new JTree(root);
    private JScrollPane jsp = new JScrollPane(jt);
    
    public Ho0205_09_Sub() {
        super("경로보여주기");
        setSize(300,200);
        Toolkit tk = Toolkit.getDefaultToolkit();
        Dimension di1 = tk.getScreenSize();
        Dimension di2 = this.getSize();
        setLocation((int)(di1.getWidth()/2 - di2.getWidth()/2),
                    (int)(di1.getHeight()/2 - di2.getHeight()/2));
        init();
        start();
        setVisible(true);
    }
    public void init() {
        jrp = this.getRootPane();
        con = jrp.getContentPane();
        con.setLayout(new BorderLayout());
        creatPath(f);
        con.add("Center", jsp);
    }
    public void start() {
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
    }

    public void creatPath(File f) {        //시작시만 실행(root에 f를 add 시킴)
        String fpath = f.getAbsolutePath();
//      System.out.println(fpath);   //현재 파일 절대 경로 포함 표시    
        
        if(f.isDirectory()) {
            String[] str = f.list();      
            for(int i=0; i < f.list().length; i++) {
                File nf = new File(fpath + "\\" + str[i]);
                creatPath(nf, root);
            }
        }
    }
    
    public void creatPath(File f, DefaultMutableTreeNode dmtn) {        //dmtn에 f를 add 시킴
        String fpath = f.getAbsolutePath();
        DefaultMutableTreeNode indmtn = new DefaultMutableTreeNode(f.getName());
        dmtn.add(indmtn);
//      System.out.println(fpath);   //현재 파일 절대 경로 포함 표시    
        
        if(f.isDirectory()) {
            String[] str = f.list();
            for(int i=0; i < f.list().length; i++) {
                File nf = new File(fpath + "\\" + str[i]);
                creatPath(nf, indmtn);
            }
        }
    }
}

public class Ho0205_09 {
    public static void main(String [] ar) {
        Ho0205_09_Sub h9s = new Ho0205_09_Sub();  
    }
}



//===========================================================================//