프레임을 생성하는 방법 1
(main 에서 띄우기)
package GUI;
import javax.swing.*;
public class FraneTest {
public static void main(String[] args) {
JFrame j = new JFrame("yasuo"); // j프레임을 동적할당 (프레임을 생성)
j.setTitle("MyFrame"); // 프레임의 타이틀을 설정
j.setSize(500, 400); // 프레임의 크기를 설정
j.setVisible(true); // 트루로 바꿔줘서 화면에 출력
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 닫힘버튼(x) 를 누르면 프로그램 종료시킴
}
}
프레임을 생성하는 법 2
(상속받아 띄우기)
package GUI;
import javax.swing.*;
// JFrame를 상속받아 사용
public class MyFrame extends JFrame {
public MyFrame() {
setSize(300, 200);
setTitle("MyFrame");
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
MyFrame j = new MyFrame(); // My프레임 생성자가 호출되면서 작업이 시작된다.
}
}
프레임에 버튼 추가하기
package GUI;
import javax.swing.*;
import java.awt.*;
// JFrame를 상속받아 사용
public class MyFrame extends JFrame {
public MyFrame() {
setSize(300, 200);
setTitle("MyFrame");
setLayout(new FlowLayout()); // 배치 관리자를 FlowLayout으로 지정(안하면 화면 전체를 버튼이 차지함)
JButton but = new JButton("튼버"); // 버튼을 동적할당하여 추가
add(but); // add 문장을 실행하여서 버튼을 프레임에 추가
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
MyFrame j = new MyFrame(); // My프레임 생성자가 호출되면서 작업이 시작된다.
}
}
<aside> 💡 setVisible(true)는 자신의 위에 있는 문장만 실행함
</aside>
package ex07.example;
import javax.swing.*;
import java.awt.*;
public class MyFrameEx01 {
static int num = 1;
public static void main(String[] args) {
JFrame jf = new JFrame();
//jf.setLayout(new FlowLayout());
jf.setSize(300, 500);
JButton btn1 = new JButton("더하기");
JButton btn2 = new JButton("빼기");
JLabel la1 = new JLabel(num + "");
jf.add("North", btn1);
jf.add("South", btn2);
jf.add("Center", la1);
btn1.addActionListener(e -> {
num++;
la1.setText(num + "");
});
btn2.addActionListener(e -> {
num--;
if (num < 0) {
num = 0;
}
la1.setText(num + "");
});
jf.setVisible(true);
}
}