ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 210824_Swing+Label+Button+Arrays+Random
    Swing 2021. 8. 24. 17:38

    public class SwingLabelGridEx05 extends JFrame {

     

    Container cp;

    JLabel[] lbl=new JLabel[9];  //공간만 할당받고 초기값 받은 거 아님

    String []str={"한국","영국","프랑스","오스트리아","체코","헝가리","홍콩","미국","태국"};

    JButton btn;

     

     

    public SwingLabelGridEx05(String title) {

    super(title);

     

    cp=this.getContentPane();

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    this.setBounds(700,100,600,600); 

    cp.setBackground(new Color(151,190,200));

     

    initDesign();

    this.setVisible(true);

    }

     

     

    public void initDesign() {

     

    //패널을 프레임의 센터에 추가

    JPanel pCenter=new JPanel(new GridLayout(3, 3));  //패널 생성하고 그리드 3행3열

    this.add(pCenter,BorderLayout.CENTER);  

     

    //라벨을 패널에 추가

    for(int i=0;i<lbl.length;i++)

    {

    lbl[i]=new JLabel(str[i], JLabel.CENTER);

     

    //색상 랜덤으로 주기

    int r=(int)(Math.random()*256);  //0~256

    int g=(int)(Math.random()*256);  //0~256

    int b=(int)(Math.random()*256);  //0~256

    lbl[i].setBackground(new Color(r, g, b));

     

    //글꼴 

    lbl[i].setFont(new Font("궁서체",Font.BOLD,15));

     

    lbl[i].setOpaque(true);

     

    //패널에 라벨 추가

    pCenter.add(lbl[i]);

    }

     

    //프레임의 하단에 버튼 생성 후 추가

    btn=new JButton("라벨색상변경");

    this.add(btn,BorderLayout.SOUTH); //this는 프레임을 의미

     

    //버튼에 익명내부 클래스 이벤트

    //객체가 하나일 때는 익명내부클래스가 편함

    btn.addActionListener(new ActionListener() {

     

    @Override

    public void actionPerformed(ActionEvent e) {

     

    for(int i=0;i<lbl.length;i++)

    {

    int r=(int)(Math.random()*256);  //0~256

    int g=(int)(Math.random()*256);  //0~256

    int b=(int)(Math.random()*256);  //0~256

    lbl[i].setBackground(new Color(r, g, b));

    }

    }

    });

    }

     

     

    public static void main(String[] args) {

     

    new SwingLabelGridEx05("라벨 배열 그래드로 출력");

    }

    }

     

    하단의 라밸색상변경 버튼을 누를시 랜덤으로 색상 변경됨

     

    댓글

Designed by Tistory.