/*계산버튼을 누르거나 결과 텍스트필드에 마우스클릭하면 계산결과가 나오게 하는 과제*/
import java.awt.Button;
import java.awt.Choice;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
class MyFrame extends Frame implements ActionListener,ItemListener,FocusListener{
Button b,b1;
TextField tf, tf1, tf2;
Choice c;
Panel p1, p2;
String aa;
String[] s=new String[]{"","+","-","×","÷"};
MyFrame(String t) {
setTitle(t);
p1 = new Panel(new FlowLayout());
p2 = new Panel(new FlowLayout());
b = new Button("계산");
b1 = new Button("초기화");
tf = new TextField(10);
tf1 = new TextField(10);
tf2 = new TextField(10);
c = new Choice();
tf.setText("");
p1.add(tf);
p1.add(c);
p1.add(tf1);
p2.add(b);
p2.add(tf2);
p2.add(b1);
c.add("선택");
c.add("+");
c.add("-");
c.add("×");
c.add("÷");
}
void addComponent() {
add(p1, "North");
add(p2, "Center");
}
void registerEvent() {
b.addActionListener(this);
c.addItemListener(this);
b1.addActionListener(this);
tf2.addFocusListener(this);
}
public void actionPerformed(ActionEvent e){
if(e.getActionCommand()=="계산"){
int i=c.getSelectedIndex();
int x=Integer.parseInt(tf.getText());
int y=Integer.parseInt(tf1.getText());
int[] ys={0,x+y,x-y,x*y,x/y};
tf2.setText(x+aa+y+"="+ys[i]);
}else{
tf.setText("");
tf1.setText("");
tf2.setText("");
c.select(0);
}
}
public void itemStateChanged(ItemEvent e){
int i=c.getSelectedIndex();
aa=s[i];
}
public void focusGained(FocusEvent f){
int i=c.getSelectedIndex();
int x=Integer.parseInt(tf.getText());
int y=Integer.parseInt(tf1.getText());
int[] ys={0,x+y,x-y,x*y,x/y};
tf2.setText(x+aa+y+"="+ys[i]);
}
public void focusLost(FocusEvent f){
}
}
class A {
public static void main(String args[]) {
MyFrame f = new MyFrame("사칙연산");
f.setVisible(true);
f.setBounds(800, 200, 300, 300);
f.registerEvent();
f.addComponent();
}
}
'개발하자 > JAVA문제풀이' 카테고리의 다른 글
15.01.20 달력과제 1차(콘솔창출력) (0) | 2015.01.20 |
---|---|
2015.01.10 awt와 DB연동 과제 (0) | 2015.01.11 |
묻지마정렬(학생의 반과 번호) (0) | 2015.01.06 |
2진수 IP주소를 10진수로 바꾸기 (0) | 2015.01.06 |
그릇높이계산 (0) | 2015.01.06 |