티스토리 뷰

반응형

⊙ 문제

 

14장 프로그래밍 문제(https://tooo1.tistory.com/184)에서 작성한 카드 돌리기 프로그램의 외형에서 각 버튼을 클릭하면 최초 카드, 이전 카드, 다음 카드, 마지막 카드로 넘기도록 프로그램을 완성하시오.

 

 

[쉽게 배우는 자바 프로그래밍] 14장 : 8번 - JAVA[자바]

⊙ 문제 5개의 카드 돌리기 프로그램의 외형을 구성하시오. 버튼을 사용해 카드를 넘기는 이벤트 처리는 다음 장에서 살펴보고, 여기서는 화면만 구성한다. 카드번호가 나오는 부분은 CardLayout

tooo1.tistory.com


 

⊙ 문제 접근 과정

 

총 4개의 색에 대해 만들었다.


 

⊙ 문제 풀이

 

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

public class Main extends JFrame implements ActionListener{

    JPanel panel;
    Cards cards;

    public Main(){
        setTitle("카드 레이아웃");
        setSize(400, 200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        panel = new JPanel(new GridLayout(0, 4, 10, 0));
        addButton("<<", panel);
        addButton("<", panel);
        addButton(">", panel);
        addButton(">>", panel);
        add(panel, BorderLayout.NORTH);
        cards = new Cards();
        add(cards, BorderLayout.CENTER);
        setVisible(true);
    }

    public void addButton(String str, Container target){
        JButton bt = new JButton(str);
        bt.addActionListener((ActionListener) this);
        target.add(bt);
    }

    class Cards extends JPanel{
        CardLayout layout;

        public Cards(){
            layout = new CardLayout();
            setLayout(layout);
            for(int i=0 ; i<=3 ; i++){
                JButton bt = new JButton();
                bt.setText("카드 번호" + (i+1) + "!");
                Color[] color = {Color.YELLOW, Color.BLUE, Color.PINK, Color.RED};
                bt.setBackground(color[i]);
                add(bt, BorderLayout.CENTER);
            }
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getActionCommand().equals("<<")){
            cards.layout.first(cards);
        }
        if(e.getActionCommand().equals("<")){
            cards.layout.previous(cards);
        }
        if(e.getActionCommand().equals(">")){
            cards.layout.next(cards);
        }
        if(e.getActionCommand().equals(">>")){
            cards.layout.last(cards);
        }
    }
    public static void main(String[] args){
        new Main();
    }
}

 


⊙ 결과

 


⊙ 마무리

 

 

NONE

 

좋아요 로그인하지 않아도 누를 수 있습니다!

 

728x90
반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함