'프로그래밍'에 해당되는 글 79건
- 2007/11/21 Java / BufferedInputStream/BufferedOutputStream - ConfigurationReader
- 2007/11/21 Java / InputStreamReader/OutputStreamWriter, PrintStream/PrintWriter
- 2007/11/21 Java / FileReader/FileWriter - ReadFileData
- 2007/11/21 Java / FileInputStream/FileOutputStream - FileCopy
- 2007/11/21 Java / FileInputStream/FileOutputStream - More
- 2007/11/21 Java / FileInputStream/FileOutputStream - ConsoleCopy
- 2007/11/21 Java / InputStream/OutputStream - Copier
- 2007/11/21 Java / InputStream/OutputStream - ConsoleReader, ConsoleReaderTest
- 2007/11/21 Java / InputStream/OutputStream - ScannerTest
- 2007/11/21 Java / 자바 입출력 클래스 (InputStream/OutputStream) - SimpleRead
- 2007/11/21 Java / 애플릿(Applet)
- 2007/11/07 Java / AWT - 카드 레이아웃
- 2007/11/07 Java / AWT 맛보기
- 2007/10/17 Java / MVC 스윙 모델, 스피너
- 2007/10/17 Java / MVC 스윙 모델, 셀 편집기와 렌더러
- 2007/10/17 Java / MVC 스윙 모델, 콤보 박스
- 2007/10/17 Java / MVC 스윙 모델, 버튼 모델
- 2007/10/14 Java / (Report) p380,p390 실습1,2,3 - 메뉴작성 / 계산기 모양 GUI 작성
- 2007/10/10 Java / 마우스 커서
- 2007/10/10 Java / 체크박스, 라디오 버튼, 토글 버튼, 패널
- 2007/10/10 Java / 라벨과 이미지 아이콘, 버튼, 툴팁, 보더
- 2007/09/19 Java / 프레임과 메뉴(2)
- 2007/09/19 Java / 이벤트 프로그램 작성
- 2007/09/12 Java / GUI 프로그래밍 - 스윙(Swing)
- 2007/09/08 Java / (Report) - p.274 실습 1번. 예외처리 & UML 작성(1)
- 2007/09/05 Java / 예외(Exception) 처리
- 2007/06/14 C언어 - 070614 / 동적 배열
- 2007/06/11 C언어 - 070607 / 파일 입출력 응용문제
- 2007/06/11 C언어 - 070531 / 구조체 실습 예제
- 2007/06/04 Java / 5.3 내부 클래스(Inner Class)
# 다음은 포트 번호입니다. # port 7690 # # 다음은 서버 이름입니다. # server it.mokpo.ac.kr # # 다음은 관리자 메일입니다. # admin admin@it.mokpo.ac.kr #
import java.io.*;
import java.util.*;
public class ConfigurationReader
{
String file;
char comment;
Hashtable ht;
String delm;
public ConfigurationReader(String file)
{
this(file, '#', " \t");
}
public ConfigurationReader(String file, char comment)
{
this(file, comment, " \t");
}
public ConfigurationReader(String file, char comment, String delm)
{
this.file = file;
this.comment = comment;
this.delm = delm;
ht = new Hashtable();
}
public void parse() throws IOException
{
String rl;
BufferedReader br = new BufferedReader(new FileReader(file));
while ((rl=br.readLine()) != null)
{
rl = rl.trim();
if (rl.charAt(0) == comment)
{
continue;
}else{
StringTokenizer st = new StringTokenizer(rl,delm,false);
String key = st.nextToken();
String value = st.nextToken();
ht.put(key, value);
}
}
br.close();
}
public String getValue(String name)
{
return (String)ht.get(name);
}
public static void main(String args[])
{
ConfigurationReader cr = new ConfigurationReader("server.conf");
try
{
cr.parse();
System.out.println(cr.getValue("port"));
System.out.println(cr.getValue("server"));
System.out.println(cr.getValue("admin"));
}
catch (Exception e) { }
}
}
/*
---------- JAVAC ----------
Note: ConfigurationReader.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
출력 완료 (1초 경과) - 정상 종료
권장되지 않은 명령어를 사용해서 나오는 오류
Sun 에서는 1.5이상에서 컬렉션프레임워크 사용시
제네릭 프로그래밍을 권장하기 때문
※ 프레임워크
생성된 객체들을 보관하고 있는 클래스
※ 제네릭 프로그래밍
효율적인 알고리즘의 추상적인
형태를 표현하기 위한 프로그래밍 방법
*/
import java.io.*;
import java.text.*;
public class ConsoleWriter extends PrintWriter
{
public ConsoleWriter(OutputStream out)
{
super(out, true);
}
public ConsoleWriter(Writer out)
{
super(out, true);
}
public void printWon(long value)
{
String format = "W#,###";
DecimalFormat df = new DecimalFormat(format);
print(df.format(value));
}
public void printlnWon(long value)
{
printWon(value);
println();
}
public void printDollar(float value)
{
String format = "$#,###.00";
DecimalFormat df = new DecimalFormat(format);
print(df.format(value));
}
public void printlnDollar(float value)
{
printDollar(value);
println();
}
public void print(double value, int digit)
{
String format = "#.";
for (int i=0; i < digit; i++)
{
format += "#";
}
DecimalFormat df = new DecimalFormat(format);
print(df.format(value));
flush();
}
public void println(double value, int digit)
{
print(value, digit);
println();
}
}
public class ConsoleWriterTest
{
public static void main(String args[])
{
try
{
ConsoleWriter out = new ConsoleWriter(System.out);
double d = 123.456789;
int money = 1234567;
out.println(d);
out.println(d, 2);
out.printlnWon(money);
out.printlnDollar(money);
}
catch (Exception e)
{
System.out.println(e);
}
}
}
123 123.456 한 한글입니다.
import java.io.*;
public class ReadFileData
{
public static void main(String args[])
{
int ivalue;
double dvalue;
char cvalue;
String svalue;
try
{
ConsoleReader in = new ConsoleReader(new FileReader("data.txt"));
ivalue = in.readInt();
System.out.println("value = " + ivalue);
dvalue = in.readDouble();
System.out.println("value = " + dvalue);
cvalue = in.readChar();
System.out.println("value = " + cvalue);
svalue = in.readString();
System.out.println("value = " + svalue);
}
catch (Exception e)
{
System.out.println("타입에 맞지 않은 입력입니다.");
}
}
}
import java.io.*;
public class FileCopy
{
public static void main(String args[])
{
if (args.length != 2)
{
System.out.println("usage: java FileCopy");
System.out.println("<filename> <filename>");
System.exit(1);
}
try
{
Copier cp = new Copier(new FileInputStream(args[0]),new FileOutputStream(args[1]));
cp.copy();
System.out.println("파일 복사가 완료되었습니다.");
}
catch (Exception e)
{
System.out.println(e);
}
}
}
import java.io.*;
public class More
{
public static void main(String args[])
{
if (args.length != 1)
{
System.out.println("usage: java More <filename>");
System.exit(1);
}
try
{
Copier cp = new Copier(new FileInputStream(args[0]),System.out);
cp.copy();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
import java.io.*;
public class ConsoleCopy
{
public static void main(String args[])
{
if (args.length != 1)
{
System.out.println("usage:java Consolecopy <filename>");
System.exit(1);
}
try
{
Copier cp = new Copier(System.in, new FileOutputStream(args[0]));
cp.copy();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
import java.io.*;
public class Copier
{
protected InputStream in;
protected OutputStream out;
protected byte data[];
public Copier(InputStream in, OutputStream out, int sz)
{
this.in = in;
this.out = out;
data = new byte[sz];
}
public Copier(InputStream in, OutputStream out)
{
this(in, out, 1024);
}
public void copy() throws IOException
{
int n=0;
while ((n = in.read(data)) != -1)
{
out.write(data, 0, n);
}
in.close();
out.close();
}
}
import java.io.*;
public class ConsoleReader extends BufferedReader
{
public ConsoleReader(Reader in) throws IOException
{
super(in);
}
public ConsoleReader(InputStream in) throws IOException
{
super(new InputStreamReader(in));
}
public int readInt() throws IOException
{
return Integer.parseInt(readLine().trim());
}
public String readString() throws IOException
{
return readLine().trim();
}
public char readChar() throws IOException
{
String line = readLine().trim();
return line.charAt(0);
}
public double readDouble() throws IOException
{
Double d = new Double(readLine().trim());
return d.doubleValue();
}
}
import java.io.*;
public class ConsoleReaderTest
{
public static void main(String args[])
{
int ivalue;
double dvalue;
char cvalue;
String svalue;
try
{
ConsoleReader in = new ConsoleReader(System.in);
System.out.print("정수를 입력해주세요:");
ivalue = in.readInt();
System.out.println("value = " + ivalue);
System.out.print("\n실수를 입력해주세요:");
dvalue = in.readDouble();
System.out.println("value = " + dvalue);
System.out.print("\n문자를 입력해주세요:");
cvalue = in.readChar();
System.out.println("value = " + cvalue);
System.out.print("\n문자열을 입력해주세요:");
svalue = in.readString();
System.out.println("value = " + svalue);
}
catch (Exception e)
{
System.out.println("타입에 맞지 않은 입력입니다.");
}
}
}
import java.util.*;
public class ScannerTest
{
public static void main(String args[])
{
System.out.print("->");
Scanner sc = new Scanner(System.in);
while (sc.hasNextInt())
{
int i = sc.nextInt();
System.out.println(i);
}
System.out.println("-----------------------");
while (sc.hasNext())
{
String s = sc.next();
System.out.println(s);
}
}
}
import java.io.IOException;
public class SimpleRead
{
public static void main(String args[])
{
int b=0, count =0;
try
{
b = System.in.read();
while (b != -1)
{
System.out.print((char)b);
count++;
b = System.in.read();
}
}
catch (IOException e)
{
System.out.println(e);
}
System.out.println();
System.out.println("total byte:" + count);
}
}
import java.awt.*;
import java.applet.Applet;
public class ImgTest extends Applet
{
Image duke;
public void init()
{
duke = getImage(getDocumentBase(),"duke.gif");
}
public void paint(Graphics g)
{
g.drawImage(duke, 25, 25, this);
}
}
<html> <head> <title>애플릿 테스트</title> </head> <body> <applet code=ImgTest width=300 height=300></applet> </body> </html>
import java.awt.*;
import java.awt.event.*;
public class SimpleCard extends Frame implements ItemListener
{
private Panel body, ps[];
private Choice choice;
private CardLayout card;
private int selected; //현재 선택된 패널 번호
public SimpleCard()
{
super("카드 레이아웃");
body = new Panel();
body.setLayout(card = new CardLayout());
MouseHandler handler = new MouseHandler();
String data[] = {"First", "Second", "Third", "Fourth", "Fifth"};
Color colors[] = {Color.YELLOW, Color.GREEN,
Color.MAGENTA, Color.WHITE, Color.CYAN};
ps = new Panel[data.length];
for (int i=0; i < ps.length; i++)
{
ps[i] = new Panel();
ps[i].setBackground(colors[i]);
ps[i].add(new Label(data[i] + " Panel"));
ps[i].addMouseListener(handler);
body.add(String.valueOf(i), ps[i]);
}
card.show(body, "0");
selected = 0;
choice = new Choice();
choice.addItemListener(this);
for (int i=0; i < ps.length; i++)
{
choice.add(String.valueOf(i+1));
}
add(choice, "East");
add(body, "Center");
addWindowListener(new WindowHandler());
setSize(300, 200);
setVisible(true);
}
public void itemStateChanged(ItemEvent e)
{
Object o = e.getSource();
if (o == choice)
{
int index = choice.getSelectedIndex();
card.show(body, String.valueOf(index));
selected = index;
}
}
public class MouseHandler extends MouseAdapter
{
public void mouseClicked(MouseEvent e)
{
card.next(body);
selected = (selected + 1) % ps.length;
choice.select(selected);
}
}
public class WindowHandler extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
setVisible(false);
dispose();
System.exit(0);
}
}
public static void main(String args[])
{
new SimpleCard();
}
}
import java.awt.*;
import java.awt.event.*;
public class AWT extends Frame implements ActionListener, ItemListener
{
protected MenuItem exit;
protected TextField field;
protected TextArea text;
protected Choice choice;
public AWT()
{
super("AWT테스트");
makeMenu();
makeBody();
setSize(400, 500);
setVisible(true);
}
protected void makeMenu()
{
MenuBar bar = new MenuBar();
Menu file = new Menu("File");
exit = new MenuItem("Exit");
exit.addActionListener(this);
file.add(exit);
bar.add(file);
setMenuBar(bar);
}
protected void makeBody()
{
Panel top = new Panel(new BorderLayout());
top.add(new Label("데이터"), BorderLayout.WEST);
field = new TextField();
field.addActionListener(this);
top.add(field, BorderLayout.CENTER);
add(top, BorderLayout.NORTH);
text = new TextArea();
add(text, BorderLayout.CENTER);
choice = new Choice();
choice.addItemListener(this);
choice.add("사과");
choice.add("배");
choice.add("귤");
add(choice, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e)
{
Object o = e.getSource();
if (o == exit)
{
setVisible(false);
System.exit(0);
}else if(o == field){
text.append(field.getText());
text.append("\n");
field.setText("");
}
}
public void itemStateChanged(ItemEvent e)
{
Object o = e.getSource();
if (o == choice)
{
if (e.getStateChange() == ItemEvent.SELECTED)
{
String item = choice.getSelectedItem();
text.append(item);
text.append("\n");
}
}
}
public static void main(String args[])
{
new AWT();
}
}
import java.awt.*;
import javax.swing.*;
public class SpinnerTest extends JFrame
{
protected JSpinner score, color, date;
public SpinnerTest()
{
super("Spinner 테스트");
JPanel panel = new JPanel(new GridLayout(3,2));
SpinnerNumberModel scoreModel = new SpinnerNumberModel(0,0,100,5);
score = new JSpinner(scoreModel);
panel.add(new JLabel("점수"));
panel.add(score);
String colors[] = {"빨강", "노랑", "파랑"};
SpinnerListModel colorModel = new SpinnerListModel(colors);
color = new JSpinner(colorModel);
panel.add(new JLabel("좋아하는 색"));
panel.add(color);
SpinnerDateModel dateModel = new SpinnerDateModel();
date = new JSpinner(dateModel);
panel.add(new JLabel("생일"));
panel.add(date);
getContentPane().add("North", panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,300);
setVisible(true);
}
public static void main(String args[])
{
new SpinnerTest();
}
}
import java.util.*;
import java.awt.*;
import javax.swing.*;
public class IconCellRenderer extends DefaultListCellRenderer
{
protected Hashtable icons;
public IconCellRenderer()
{
icons = new Hashtable();
}
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus)
{
String text = value.toString();
setText(text);
if (!icons.containsKey(text))
{
ImageIcon img = new ImageIcon(text + ".gif");
icons.put(text, img);
setIcon(img);
} else {
setIcon((ImageIcon)icons.get(text));
}
if (isSelected = true)
{
setBackground(Color.white);
setForeground(Color.blue);
} else {
setBackground(Color.lightGray);
setForeground(Color.black);
}
return this;
}
}
import java.awt.Color;
import javax.swing.*;
public class DeviceListCombo extends JFrame
{
protected JList list;
protected JComboBox combo;
public DeviceListCombo()
{
super("아이콘을 갖는 리스트와 콤보");
String[] data = {"Keyboard", "mouse", "joystick"};
list = new JList(data);
list.setBackground(Color.lightGray);
list.setCellRenderer(new IconCellRenderer());
getContentPane().add(new JScrollPane(list), "Center");
combo = new JComboBox(data);
combo.setRenderer(new IconCellRenderer());
getContentPane().add(combo, "South");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400,300);
setVisible(true);
}
public static void main(String args[])
{
new DeviceListCombo();
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JListComboBox extends JFrame implements ItemListener
{
protected JList fruits;
protected JComboBox colors;
protected String items[] = {"apple", "orange", "banana", "pear"};
public JListComboBox()
{
super("스윙 리스트와 콤보 박스");
getContentPane().setLayout(new FlowLayout());
fruits = new JList(items);
fruits.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
int index = fruits.locationToIndex(e.getPoint());
if (e.getClickCount() == 1)
{
System.out.println(items[index]);
} else if (e.getClickCount() == 2)
{
System.out.println("[" + items[index] + "]");
}
}
});
fruits.setVisibleRowCount(3);
JScrollPane sp = new JScrollPane(fruits);
colors = new JComboBox();
colors.addItem("white");
colors.addItem("blue");
colors.addItem("green");
colors.addItemListener(this);
getContentPane().add(sp);
getContentPane().add(colors);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300,200);
setVisible(true);
}
public void itemStateChanged(ItemEvent e)
{
Object o = e.getSource();
if (o == colors)
{
if (e.getStateChange() == ItemEvent.SELECTED)
{
Object data = colors.getSelectedItem();
System.out.println(data.toString());
}
}
}
public static void main(String args[])
{
JListComboBox jlc = new JListComboBox();
}
}
import java.awt.*;
import javax.swing.*;
public class CountButtonModel extends DefaultButtonModel
{
private int count;
private JButton btn;
public CountButtonModel(JButton btn)
{
this.btn = btn;
btn.setModel(this);
}
public void setPressed(boolean b)
{
if(b) {
count = ++count % 4;
switch(count) {
case 0:
btn.setBackground(Color.lightGray);
break;
case 1:
btn.setBackground(Color.green);
break;
case 2:
btn.setBackground(Color.red);
break;
case 3:
btn.setBackground(Color.yellow);
}
}
}
}
import javax.swing.*;
public class ButtonModelTest extends JFrame
{
JButton ok;
public ButtonModelTest()
{
super("ButtonModel 테스트");
ImageIcon rai = new ImageIcon("rai.gif");
ok = new JButton("OK", rai);
ok.setRolloverIcon(rai);
ok.setPressedIcon(rai);
CountButtonModel model = new CountButtonModel(ok);
getContentPane().add("South",ok);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,300);
setVisible(true);
}
public static void main(String args[])
{
new ButtonModelTest();
}
}
/*
1. 다음과 같은 형태의 GUI 화면을 작성하라.
메뉴 아이템과 버튼을 클릭하는 경우에 메시지가
출력된다. 예를들어, New 버튼을 클릭하는 경우에
"New"라는 메시지가 출력되어야 한다.
두 개의 버튼은 JToolBar에 붙인다.
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MenuTest extends JFrame implements ActionListener {
JMenuBar bar;
JMenu file, style, edit, help;
JMenuItem fileNew, fileOpen, fileExit;
JToolBar toolBar;
JButton btNew, btOpen;
public MenuTest() {
super("실습 테스트");
makeMenu();
makeBody();
getContentPane().setLayout(null);
toolBar.setSize(100,40);
toolBar.setLocation(0,0);
getContentPane().add(toolBar);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400, 300);
setVisible(true);
}
protected void makeMenu() {
bar = new JMenuBar();
file = new JMenu("File");
file.setMnemonic('F');
edit = new JMenu("Edit");
edit.setMnemonic('E');
help = new JMenu("Help");
help.setMnemonic('H');
fileNew = new JMenuItem("New");
fileNew.addActionListener(this);
file.add(fileNew);
fileOpen = new JMenuItem("Open");
fileOpen.addActionListener(this);
file.add(fileOpen);
file.addSeparator();
fileExit = new JMenuItem("Exit");
fileExit.addActionListener(this);
file.add(fileExit);
bar.add(file);
bar.add(edit);
bar.add(help);
setJMenuBar(bar);
}
protected void makeBody() {
setLayout(new FlowLayout());
toolBar = new JToolBar();
btNew = new JButton("New");
btNew.addActionListener(this);
btOpen = new JButton("Open");
btOpen.addActionListener(this);
toolBar.add(btNew);
toolBar.add(btOpen);
}
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if(o == fileNew) {
System.out.println("New");
} else if(o == fileOpen) {
System.out.println("Open");
} else if(o == fileExit) {
System.out.println("Exit");
} else if(o == btNew) {
System.out.println("New");
} else if(o == btOpen) {
System.out.println("Open");
}
}
public static void main(String args[]) {
new MenuTest();
}
}
/*
2. 계산기 모양의 GUI 프로그램을 작성하라.
*/
import java.awt.*;
import javax.swing.*;
public class cal extends JFrame {
JButton bt_num0,bt_num1,bt_num2,bt_num3,bt_num4,bt_num5,bt_num6,bt_num7,bt_num8,bt_num9;
JButton bt_op0,bt_op1,bt_op2,bt_op3,bt_op4,bt_op5,bt_op6;
JButton bt_backspace,bt_ce,bt_c;
TextField text;
Panel p1,p2,p3,p4,p5;
public cal()
{
super("계산기 모양의 GUI");
getContentPane().setLayout(new GridLayout(6,1));
text = new TextField();
bt_num1 = new JButton("1");
bt_num2 = new JButton("2");
bt_num3 = new JButton("3");
bt_num4 = new JButton("4");
bt_num5 = new JButton("5");
bt_num6 = new JButton("6");
bt_num7 = new JButton("7");
bt_num8 = new JButton("8");
bt_num9 = new JButton("9");
bt_num0 = new JButton("0");
bt_op1 = new JButton("/");
bt_op2 = new JButton("*");
bt_op3 = new JButton("-");
bt_op4 = new JButton("+");
bt_op5 = new JButton(".");
bt_op6 = new JButton("=");
bt_backspace = new JButton("Backspace");
bt_ce = new JButton("Ce");
bt_c = new JButton("C");
p1 = new Panel(new FlowLayout());
p2 = new Panel(new FlowLayout());
p3 = new Panel(new FlowLayout());
p4 = new Panel(new FlowLayout());
p5 = new Panel(new FlowLayout());
p1.add(bt_num0);
p1.add(bt_op4);
p1.add(bt_op5);
p1.add(bt_op6);
p2.add(bt_num1);
p2.add(bt_num2);
p2.add(bt_num3);
p2.add(bt_op3);
p3.add(bt_num4);
p3.add(bt_num5);
p3.add(bt_num6);
p3.add(bt_op2);
p4.add(bt_num7);
p4.add(bt_num8);
p4.add(bt_num9);
p4.add(bt_op1);
p5.add(bt_backspace);
p5.add(bt_ce);
p5.add(bt_c);
getContentPane().add(text);
getContentPane().add(p5);
getContentPane().add(p4);
getContentPane().add(p3);
getContentPane().add(p2);
getContentPane().add(p1);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(225, 250);
setVisible(true);
}
public static void main(String args[]) {
cal ct = new cal();
}
}
/*
3. 2번에서 작성한 계산기에서 버튼을 클릭하면
클릭한 숫자가 화면에 출력되도록 기능을 추가하라.
*/
import java.awt.*;
import java.awt.event.*; // evnet
import javax.swing.*;
public class calPlus extends JFrame implements ActionListener { // 아이템 리스너 인터페이스
JButton bt_num0,bt_num1,bt_num2,bt_num3,bt_num4,bt_num5,bt_num6,bt_num7,bt_num8,bt_num9;
JButton bt_op0,bt_op1,bt_op2,bt_op3,bt_op4,bt_op5,bt_op6;
JButton bt_backspace,bt_ce,bt_c;
TextField text;
Panel p1,p2,p3,p4,p5;
public calPlus()
{
super("계산기 모양의 GUI");
getContentPane().setLayout(new GridLayout(6,1)); //그리드 레이아웃
text = new TextField();
bt_num1 = new JButton("1");
bt_num1.addActionListener(this); // 이벤트 리스너 등록
bt_num2 = new JButton("2");
bt_num2.addActionListener(this);
bt_num3 = new JButton("3");
bt_num3.addActionListener(this);
bt_num4 = new JButton("4");
bt_num4.addActionListener(this);
bt_num5 = new JButton("5");
bt_num5.addActionListener(this);
bt_num6 = new JButton("6");
bt_num6.addActionListener(this);
bt_num7 = new JButton("7");
bt_num7.addActionListener(this);
bt_num8 = new JButton("8");
bt_num8.addActionListener(this);
bt_num9 = new JButton("9");
bt_num9.addActionListener(this);
bt_num0 = new JButton("0");
bt_num0.addActionListener(this);
bt_op1 = new JButton("/");
bt_op2 = new JButton("*");
bt_op3 = new JButton("-");
bt_op4 = new JButton("+");
bt_op5 = new JButton(".");
bt_op6 = new JButton("=");
bt_backspace = new JButton("Backspace");
bt_ce = new JButton("Ce");
bt_c = new JButton("C");
p1 = new Panel(new FlowLayout()); //플로우레이아웃 형태로 패널 묶음
p2 = new Panel(new FlowLayout());
p3 = new Panel(new FlowLayout());
p4 = new Panel(new FlowLayout());
p5 = new Panel(new FlowLayout());
p1.add(bt_num0);
p1.add(bt_op4);
p1.add(bt_op5);
p1.add(bt_op6);
p2.add(bt_num1);
p2.add(bt_num2);
p2.add(bt_num3);
p2.add(bt_op3);
p3.add(bt_num4);
p3.add(bt_num5);
p3.add(bt_num6);
p3.add(bt_op2);
p4.add(bt_num7);
p4.add(bt_num8);
p4.add(bt_num9);
p4.add(bt_op1);
p5.add(bt_backspace);
p5.add(bt_ce);
p5.add(bt_c);
getContentPane().add(text);
getContentPane().add(p5);
getContentPane().add(p4);
getContentPane().add(p3);
getContentPane().add(p2);
getContentPane().add(p1);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(225, 250);
setVisible(true);
}
// ActionEvent 추가
public void actionPerformed(ActionEvent e) {
String st = e.getActionCommand();
if (st == "1") text.setText("1");
if (st == "2") text.setText("2");
if (st == "3") text.setText("3");
if (st == "4") text.setText("4");
if (st == "5") text.setText("5");
if (st == "6") text.setText("6");
if (st == "7") text.setText("7");
if (st == "8") text.setText("8");
if (st == "9") text.setText("9");
if (st == "0") text.setText("0");
}
public static void main(String args[]) {
calPlus ct = new calPlus();
}
}
import java.awt.*;
import javax.swing.*;
public class DefinedCursor extends JFrame
{
Cursor cursor;
Image img;
public DefinedCursor()
{
super("사용자가 정의하는 커서");
Toolkit tk = Toolkit.getDefaultToolkit();
img = tk.getImage("horse.gif");
Point point = new Point(0,0);
cursor = tk.createCustomCursor(img, point, "horse");
setCursor(cursor);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400, 300);
setVisible(true);
}
public static void main(String args[])
{
new DefinedCursor();
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CheckTest extends JFrame implements ItemListener
{
protected JCheckBox java,cpp;
protected JRadioButton single, married;
public CheckTest()
{
super("체크 테스트");
getContentPane().setLayout(new GridLayout(4,1));
getContentPane().add(new JLabel("좋아하는 언어는"));
JPanel top = new JPanel();
java = new JCheckBox("Java");
java.addItemListener(this);
cpp = new JCheckBox("C++");
cpp.addItemListener(this);
top.add(java);
top.add(cpp);
getContentPane().add(top);
getContentPane().add(new JLabel("결혼 여부"));
JPanel bottom = new JPanel();
ButtonGroup bg = new ButtonGroup();
single = new JRadioButton("미혼");
single.addItemListener(this);
bottom.add(single);
bg.add(single);
married = new JRadioButton("기혼");
married.addItemListener(this);
bottom.add(married);
bg.add(married);
getContentPane().add(bottom);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400, 300);
setVisible(true);
}
public void itemStateChanged(ItemEvent e)
{
Object o = e.getSource();
int type = e.getStateChange();
if (o == java)
{
if (type == ItemEvent.SELECTED)
{
System.out.println("JAVA 선택");
}else {
System.out.println("JAVA 선택 해제");
}
} else if (o == cpp) {
if (type == ItemEvent.SELECTED)
{
System.out.println("C++ 선택");
}else {
System.out.println("C++ 선택 해제");
}
} else if (o == single) {
if (type == ItemEvent.SELECTED)
{
System.out.println("미혼 선택");
}
} else if (o == married) {
if (type == ItemEvent.SELECTED)
{
System.out.println("기혼 선택");
}
}
}
public static void main(String args[])
{
new CheckTest();
}
}
import java.awt.*;
import javax.swing.*;
public class JLabelButton extends JFrame
{
protected JButton textB, iconB;
protected JLabel label;
public JLabelButton() {
super("스윙 버튼과 라벨");
getContentPane().setLayout(new FlowLayout());
ImageIcon logo = new ImageIcon("logo.gif");
label = new JLabel("자바 듀크", logo, JLabel.RIGHT);
label.setBorder(BorderFactory.createTitledBorder("label"));
getContentPane().add(label);
textB = new JButton("버튼");
getContentPane().add(textB);
ImageIcon surf = new ImageIcon("surf.gif");
iconB = new JButton("", surf);
iconB.setPressedIcon(new ImageIcon("surf2.gif"));
iconB.setBorder(BorderFactory.createEtchedBorder());
iconB.setToolTipText("서핑 듀크");
getContentPane().add(iconB);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(270, 180);
setVisible(true);
}
public static void main(String args[])
{
JLabelButton jlb = new JLabelButton();
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonEvent extends JFrame implements ActionListener
{
protected JButton ok;
public ButtonEvent()
{
super("버튼 이벤트");
ok = new JButton("ok");
ok.addActionListener(this);
getContentPane().add(ok, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,200);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
Object o = e.getSource();
if (o == ok)
{
System.out.println("OK");
}
}
public static void main(String args[])
{
ButtonEvent be = new ButtonEvent();
}
}
import java.awt.event.*;
import javax.swing.*;
public class MenuTest extends JFrame implements ActionListener {
JMenuBar bar;
JMenu file,style;
JMenuItem fileNew;
JCheckBoxMenuItem num;
JRadioButtonMenuItem dos, unix;
public MenuTest() {
super("메뉴 테스트");
makeMenu();
makeBody();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400,300);
setVisible(true);
}
protected void makeMenu() {
bar = new JMenuBar();
file = new JMenu("File");
file.setMnemonic('F');
fileNew = new JMenuItem("New");
fileNew.addActionListener(this);
file.add(fileNew);
file.addSeparator();
num = new JCheckBoxMenuItem("Line Number");
num.addActionListener(this);
style = new JMenu("Style");
file.add(num);
file.add(style);
dos = new JRadioButtonMenuItem("DOS Style", true);
dos.addActionListener(this);
unix = new JRadioButtonMenuItem("UNIX Style");
unix.addActionListener(this);
ButtonGroup bg = new ButtonGroup();
bg.add(dos);
bg.add(unix);
style.add(dos);
style.add(unix);
bar.add(file);
setJMenuBar(bar);
}
protected void makeBody() {
//GUI 몸체 부분을 정의한다.
}
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if (o == fileNew){
System.out.println("New");
}else if (o == num){
if (num.isSelected())
System.out.println("Line Number");
}else if (o == dos){
System.out.println("DOS");
}else if (o == unix){
System.out.println("UNIX");
}
}
public static void main(String args[]){
new MenuTest();
}
}
import java.awt.*;
import javax.swing.*;
public class IconTest extends JFrame
{
Image logo;
public IconTest()
{
super("학교 로고");
Toolkit tk = Toolkit.getDefaultToolkit();
logo = tk.getImage("logo.gif");
setIconImage(logo);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(200,150);
setVisible(true);
}
public static void main(String args[])
{
IconTest it = new IconTest();
}
}
import javax.swing.*;
public class JFrameTest extends JFrame
{
public JFrameTest()
{
super("스윙 JFrame 테스트");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300,200);
setVisible(true);
}
public static void main(String args[])
{
JFrameTest jf = new JFrameTest();
}
}
import java.awt.*;
import javax.swing.*;
public class SixButtons extends JFrame
{
protected JButton one, two, three, four, five, six;
public SixButtons()
{
super("플로우 레이아웃");
getContentPane().setLayout(new FlowLayout());
one = new JButton("One");
two = new JButton("Two");
three = new JButton("Three");
four = new JButton("Four");
five = new JButton("Five");
six = new JButton("Six");
getContentPane().add(one);
getContentPane().add(two);
getContentPane().add(three);
getContentPane().add(four);
getContentPane().add(five);
getContentPane().add(six);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 200);
setVisible(true);
}
public static void main(String args[])
{
SixButtons sb = new SixButtons();
}
}
import java.awt.*;
import javax.swing.*;
public class FiveButtons extends JFrame
{
protected JButton b1, b2, b3, b4, b5;
public FiveButtons()
{
super("보더 레이아웃");
b1 = new JButton("Center");
b2 = new JButton("South");
b3 = new JButton("North");
b4 = new JButton("West");
b5 = new JButton("East");
getContentPane().add(b1, BorderLayout.CENTER);
getContentPane().add(b2, BorderLayout.SOUTH);
getContentPane().add(b3, BorderLayout.NORTH);
getContentPane().add(b4, BorderLayout.WEST);
getContentPane().add(b5, BorderLayout.EAST);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,200);
setVisible(true);
}
public static void main(String args[])
{
FiveButtons fb = new FiveButtons();
}
}
import java.awt.*;
import javax.swing.*;
public class FourButtons extends JFrame
{
protected JButton b1, b2, b3, b4;
public FourButtons()
{
super("그리드 레이아웃");
getContentPane().setLayout(new GridLayout(2,2));
b1 = new JButton("One");
b2 = new JButton("Two");
b3 = new JButton("Three");
b4 = new JButton("Four");
getContentPane().add(b1);
getContentPane().add(b2);
getContentPane().add(b3);
getContentPane().add(b4);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,200);
setVisible(true);
}
public static void main(String args[])
{
FourButtons fb = new FourButtons();
}
}
import java.awt.*;
import javax.swing.*;
public class SimpleGridBag extends JFrame {
JButton b1,b2,b3,b4,b5,b6;
public SimpleGridBag() {
super("SimpleGridBag");
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints constraint = new GridBagConstraints();
getContentPane().setLayout(gridbag);
constraint.fill = GridBagConstraints.BOTH;
constraint.weightx = 1.0;
constraint.weighty = 1.0;
b1 = new JButton("Button1");
gridbag.setConstraints(b1, constraint);
getContentPane().add(b1);
b2 = new JButton("Button2");
gridbag.setConstraints(b2, constraint);
getContentPane().add(b2);
constraint.gridwidth = GridBagConstraints.REMAINDER;
b3 = new JButton("Button3");
gridbag.setConstraints(b3, constraint);
getContentPane().add(b3);
constraint.gridwidth = 1;
constraint.gridheight = 2;
b4 = new JButton("Button4");
gridbag.setConstraints(b3, constraint);
getContentPane().add(b4);
constraint.gridwidth = GridBagConstraints.REMAINDER;
constraint.gridheight = 1;
constraint.weighty = 1.0;
b5 = new JButton("Button5");
gridbag.setConstraints(b5, constraint);
getContentPane().add(b5);
b6 = new JButton("Button6");
gridbag.setConstraints(b6, constraint);
getContentPane().add(b6);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400,200);
setVisible(true);
}
public static void main(String args[])
{
new SimpleGridBag();
}
}
/* 0으로 나누었을 때 발생할 수 있는 DivideByZeroException라는 예외 클래스를 작성하라.
이 예외는 Exception으로부터 상속받는 체크 예외 클래스이다. */
import java.util.Scanner;
public class ZeroExcute
{
public static void main(String args[])
{
int inNum; // 숫자를 입력받을 변수
Scanner scan = new Scanner (System.in);
System.out.println("숫자를 입력하세요.");
inNum = scan.nextInt();
Zero z = new Zero(); // Zero 객체 생성
try
{
z.check(inNum); // Zero.java check(int num)로 값 전달
}
catch (DivideByZeroException e)
{
e.printStackTrace();
// DivideByZeroException 예외발생시
// 현재 throwable과 트레이스 정보를 표준 에러로 출력
}
}
}
// throw를 이용한 예외 발생 클래스 작성
public class Zero
{
private long result; //결과값이 저장될 변수
public void check(int num) throws DivideByZeroException
{
if (num == 0)
{
throw new DivideByZeroException(); //입력받은 숫자가 0이면 예외 발생
}else{
result = 10000 / num;
System.out.println("결과 : " + result);
}
}
}
// Exception으로부터 상속받는 체크 예외 클래스 DivideByZeroException 작성
public class DivideByZeroException extends Exception
{
public DivideByZeroException()
{
super("0으로 나눌 수 없습니다.");
}
}
UML - Class diagram
public class BalanceOutOfBoundsException extends Exception
{
public BalanceOutOfBoundsException()
{
super("잔액을 초과하였습니다.");
}
}
public class MalformedData extends RuntimeException
{
public MalformedData()
{
super("데이터 포맷이 잘못되었습니다.");
}
}
public class Account
{
private long balance;
private String name;
public Account(String name)
{
this.name = name;
}
public void deposit(int amount) throws MalformedData
{
if (amount <= 0)
{
throw new MalformedData();
}
balance = balance + amount;
}
public void withdraw(int amount) throws BalanceOutOfBoundsException, MalformedData
{
if (amount <=0)
{
throw new MalformedData();
}
if (balance < amount)
{
throw new BalanceOutOfBoundsException();
}
balance = balance - amount;
}
public void check()
{
System.out.println(name + " : " + balance);
}
}
public class Bank
{
public static void main(String args[])
{
Account hong = new Account("홍길동");
hong.deposit(10000);
//hong.deposit(-100); //MalformedData 예외 발생
try
{
hong.withdraw(5000);
//hong.withdraw(-50); //MalformedData 예외 발생
}
catch (BalanceOutOfBoundsException be)
{
be.printStackTrace();
}
catch (MalformedData me)
{
me.printStackTrace();
}
hong.check();
//try
//{
// hong.withdraw(10000); // BalanceOutOfBoundsException 예외 발생
//}
//catch (BalanceOutOfBoundsException be)
//{
// be.printStackTrace();
//}
}
}
#include <stdio.h>
#include <stdlib.h>
//동적 배열
typedef unsigned int UNINT;
void sum(UNINT n);
void main()
{
UNINT max;
puts("배열 사이즈 입력 :");
scanf("%d",&max);
sum(max);
}
void sum(UNINT n)
{
UNINT i;
UNINT *ptd;
ptd = (UNINT *) malloc(n * sizeof (UNINT));
if (ptd == NULL)
{
puts("메모리 확보 실패");
exit(0);
}
puts("\n출력 :");
for (i=0; i < n; i++)
{
*ptd=i+1;
printf("값=%d\n", *ptd++);
}
free(ptd);
}
#include <stdio.h>
#include <process.h>
FILE *ifp, *ofp;
void main()
{
int i;
float n[4];
float sum,ave,max,min;
ifp = fopen("ex_in.txt","r");
ofp = fopen("ex_out.txt","w");
if (ifp==NULL)
{
printf("파일 열기 실패 입니다.\n");
exit(0);
}
fprintf(ofp,"합계\t평균\t최고값\t최소값\n");
while (!feof(ifp))
{
fscanf(ifp,"%f %f %f %f",&n[0],&n[1],&n[2],&n[3]);
sum = n[0] + n[1] + n[2] + n[3];
ave = sum / 4.0;
max = n[0];
min = n[0];
for (i=0;i<4;i++)
{
if (max < n[i])
{
max = n[i];
}
if (min > n[i])
{
min = n[i];
}
}
fprintf(ofp,"%.1f\t%.1f\t%.1f\t%.1f\n",sum,ave,max,min);
}
fclose(ifp), fclose(ofp);
}
/*
구조체 실습 예제 2번
*/
#include <stdio.h>
struct student{
char name[10];
int c,cpp,vc,rank;
int tot;
};
void sum(struct student *pst, int n);
void sort(struct student *pst, int n);
void show(struct student *pst, int n);
void main()
{
struct student st[4]={
{"홍길동",90,90,90,1,0},
{"지흔이",80,89,70,1,0},
{"김진수",70,73,80,1,0},
{"박순이",60,87,80,1,0},
};
sum(st,4);
sort(st,4);
show(st,4);
}
void sum(struct student *pst, int n)
{
for(int i=0;i<n;i++)
{
pst[i].tot = pst[i].c + pst[i].cpp + pst[i].vc;
}
}
void sort(struct student *pst, int n)
{
struct student temp;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(pst[i].tot < pst[j].tot)
{
pst[i].rank++;
}
if(pst[i].rank < pst[j].rank)
{
temp=pst[i];
pst[i]=pst[j];
pst[j]=temp;
}
}
}
}
void show(struct student *pst, int n)
{
printf("이 름 | C | C++| VC | 총점| 석차\n");
printf("---------------------------------\n");
for(int i=0;i<n;i++)
{
printf("%s | %d | %d | %d | %d | %d\n",pst[i].name,pst[i].c,pst[i].cpp,pst[i].vc,pst[i].tot,pst[i].rank);
}
}
5.3.1 내지된 톱 레벨 클래스 / 인터페이스 (Nested top-level classes / interfaces)
5.3.2 멤버 클래스 (Member classes)
5.3.3 지역 클래스 (Local classes)
5.3.4 무명 클래스 (Anonymous classes)
5.3.2 멤버 클래스 (Member classes)
5.3.3 지역 클래스 (Local classes)
5.3.4 무명 클래스 (Anonymous classes)






DivideByZeroException.java
ex_in.txt


Recent Comment