1. More on GUI
- JButton example 1
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class FirstGUI extends JFrame {
private JButton button1;
private JButton button2;
private JButton button3;
private JButton button4;
private JButton button5;
// constructor
public FirstGUI() {
// Jframe을 상속받았기 때문에 set.., add 등의 메소드를 객체 선언 없이 사용 가능
super.setSize(300, 300);
super.setTitle("First GUI");
super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Jbutton 객체 만드는 일반적인 방식
button1 = new JButton();
button2 = new JButton();
// JButton('title') 버튼 객체 선언
button3 = new JButton("Explore");
button4 = new JButton("Cancel");
button5 = new JButton("Send");
// 버튼 setting
button1.setText("Back");
button1.setBackground(Color.CYAN);
button2.setText("Next");
button2.setBackground(Color.RED);
super.setLayout(new BorderLayout());
super.add(button1, BorderLayout.EAST);
super.add(button2, BorderLayout.WEST);
super.add(button3, BorderLayout.CENTER);
super.add(button4, BorderLayout.NORTH);
super.add(button5, BorderLayout.SOUTH);
// 액션리스너
button1.addActionListener(new changeColor());
button2.addActionListener(new anotherAction());
button3.addActionListener(new changeColor());
button4.addActionListener(new anotherAction());
button5.addActionListener(new anotherAction());
super.setVisible(true);
}
public static void main(String[] args) {
// 호출시 위 constructor에 있는 모든 객체 생성
FirstGUI gui = new FirstGUI();
}
private class changeColor implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
// code to do when you click a button
// change();
System.out.println("Red Color");
}
}
private class anotherAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
// code to do when you click a button
// change();
System.out.println("KNock!!");
}
}
}
- JButton example2
// Creating JButtons.
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.AbstractButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.JToggleButton;
public class ButtonFrame extends JFrame implements ActionListener {
private AbstractButton plainJButton; // button with just text
private JButton fancyJButton; // button with icons
// ButtonFrame adds JButtons to JFrame
public ButtonFrame() {
super("Testing Buttons");
setLayout(new FlowLayout()); // set frame layout
plainJButton = new JRadioButton("Plain Button"); // button with text
add(plainJButton); // add plainJButton to JFrame
// 이미지 접근을 위해 getResource('자원이 위치한 경로');
Icon bug1 = new ImageIcon(getClass().getResource("bug1.gif"));
Icon bug2 = new ImageIcon(getClass().getResource("bug2.gif"));
fancyJButton = new JButton("RollOver Button", bug1); // set image
fancyJButton.setRolloverIcon(bug2); // set rollover image
add(fancyJButton); // add fancyJButton to JFrame
// 액션 추가
fancyJButton.addActionListener(this);
plainJButton.addActionListener(this);
} // end ButtonFrame constructor
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == fancyJButton) {
// 팝업 메시지 보여줌
// showMessageDialog(); : 첫번째 인자로 부모 컴포넌트 전달하는 것 중요!
JOptionPane.showMessageDialog(ButtonFrame.this, "fancyJButton", "fancyJButton action",
JOptionPane.INFORMATION_MESSAGE);
}
else if (e.getSource() == plainJButton) {
JOptionPane.showMessageDialog(ButtonFrame.this, "Plain button", "Plain button action",
JOptionPane.INFORMATION_MESSAGE);
}
}
} // end class ButtonFrame
- 위 example2를 실행시키기 위한 main method
import javax.swing.JFrame;
public class ButtonTest
{
public static void main( String[] args )
{
ButtonFrame buttonFrame = new ButtonFrame(); // create ButtonFrame
buttonFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
buttonFrame.setSize( 300, 200 ); // set frame size
buttonFrame.setVisible( true ); // display frame
} // end main
} // end class ButtonTest
2. MVC model
3. Converter Apllication
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class ConverterFrame extends JFrame implements ActionListener {
JLabel distanceLabel;// = new JLabel("Distance in Km");
JTextField inputKm;
JButton calculateButton;
JLabel displayLabel;
// constructor start
public ConverterFrame() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setSize(300, 100);
setLayout(new GridLayout(2, 2));
setTitle("Converter");
distanceLabel = new JLabel("Distance in Km");
inputKm = new JTextField();
calculateButton = new JButton("Calculate");
displayLabel = new JLabel();
// JFrame에 요소 추가
add(distanceLabel);
add(inputKm);
add(calculateButton);
add(displayLabel);
// view 완성
// controller = actionlistener
calculateButton.addActionListener(this);
setVisible(true);
}
// controller
@Override
public void actionPerformed(ActionEvent e) {
// inputKm = textField 니까 getText -> inputValue 저장
String inputValue = inputKm.getText();
//convert string into Double
double inputkm = Double.parseDouble(inputValue);
double result = inputkm *0.621;
// set displayLabel to result value.
displayLabel.setText(String.format("%f miles(s)", result));
}
}
// convertor 실행을 위한 메인 메소드 클래스
public class TestConverter {
public static void main(String[] args) {
ConverterFrame frame = new ConverterFrame();
}
}
4. WINDOWBUILDER
tool to create Java GUI application
- help -> eclipse marketplace에서 windowbuilder 플러그인 설치 후 이클립스 재시작
(설치하는데 시간이 몇 분 정도 소요되고, 설치가 다 되면 restart 여부를 묻는 팝업창이 뜸) - java project 생성 -> src에 new -> other -> windowbuilder -> Swing Designer -> JFrame -> finish
- GUI로 프레임에 컴포넌트를 드래그하고 속성을 변경하기만 하면 코드 자동 생성!!
- window -> references -> window builder -> swing -> code generation -> field 선택 (no local!!!) 설정
- example - score board
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.JRadioButton;
import javax.swing.JList;
import javax.swing.JFormattedTextField;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
public class application extends JFrame implements ActionListener {
private JPanel contentPane;
private JButton ResetButton;
private JPanel panel;
private JLabel lblNewLabel;
private JLabel lblNewLabel_1;
private JLabel RedScoreLabel;
private JLabel BlueScoreLabel;
private JButton RedScoreButton;
private JButton BlueScoreButton;
private int redCounter = 0;
private int blueCounter = 0;
/**
* Create the frame.
*/
public application() {
setTitle("This is the title");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 305, 205);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
ResetButton = new JButton("Reset Score");
contentPane.add(ResetButton, BorderLayout.SOUTH);
panel = new JPanel();
contentPane.add(panel, BorderLayout.CENTER);
panel.setLayout(new GridLayout(3, 2, 0, 0));
lblNewLabel = new JLabel("Red Team");
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setForeground(Color.RED);
panel.add(lblNewLabel);
lblNewLabel_1 = new JLabel("Bluee Team");
lblNewLabel_1.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel_1.setForeground(Color.BLUE);
panel.add(lblNewLabel_1);
RedScoreLabel = new JLabel("0");
RedScoreLabel.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(RedScoreLabel);
BlueScoreLabel = new JLabel("0");
BlueScoreLabel.setHorizontalAlignment(SwingConstants.CENTER);
panel.add(BlueScoreLabel);
RedScoreButton = new JButton("Red Score");
panel.add(RedScoreButton);
BlueScoreButton = new JButton("Blue Score");
panel.add(BlueScoreButton);
// 액션 리스터 연결 필요
RedScoreButton.addActionListener(this);
BlueScoreButton.addActionListener(this);
ResetButton.addActionListener(this);
}
// gui 생성후 직접 구현한 액션리스너
@Override
public void actionPerformed(ActionEvent e) {
// 레드 스코어 버튼 클릭하면 레드 스코어 1 증가 후 display
if (e.getSource() == RedScoreButton ) {
redCounter++;
RedScoreLabel.setText(redCounter+"");
}
else if(e.getSource() == BlueScoreButton) {
blueCounter++;
BlueScoreLabel.setText(blueCounter+"");
}
// reset 버튼을 클릭하면 모든 스코어 값 0 으로 초기화
else if(e.getSource() == ResetButton) {
blueCounter = 0;
redCounter = 0;
BlueScoreLabel.setText("0");
RedScoreLabel.setText("0");
}
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
application frame = new application();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
References
- 성균관대학교 소프트웨어학과 타메르 교수님 2021-1 <자바 프로그래밍 실습> 수업
'프로그래밍 언어 > Java' 카테고리의 다른 글
Week10) Java Programming Lab : Multithreading (0) | 2021.04.30 |
---|---|
Week9) Java Programming Lab : Exception Handling (0) | 2021.04.19 |
Week7) Java Programming Lab : Grapical User Interface (GUI) AWT and Swing APIs (0) | 2021.04.05 |
Java programming 자바 프로그래밍 실습 : 다형성 polymorphism 추상 클래스 interface을 활용한 예제 (0) | 2021.04.05 |
Week6) Java Programming Lab : Polymorphism (0) | 2021.03.29 |