Search

'Programming'에 해당되는 글 345건

  1. 2014.01.20 JAVA 채팅 Client 예제 #1
  2. 2014.01.19 Android GoogleMap API V2
  3. 2014.01.17 JAVA FIle 실습 #1
  4. 2014.01.17 JAVA File 실습
  5. 2014.01.16 JAVA 공던지기 게임 완성
  6. 2014.01.16 JAVA 공던지기 게임
  7. 2014.01.16 CPP 연산자 오버로딩
  8. 2014.01.16 CPP 연산자 오버로딩
  9. 2014.01.14 JAVA 가계부 #2
  10. 2014.01.14 JAVA 가계부

JAVA 채팅 Client 예제 #1

Programming/JAVA,JSP 2014. 1. 20. 17:27 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

import java.awt.BorderLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.IOException;

import java.io.PrintWriter;

import java.net.Socket;

import java.net.UnknownHostException;

import java.util.Scanner;


import javax.swing.JFrame;

import javax.swing.JTextArea;

import javax.swing.JTextField;




public class Client {

static JTextField textField;

static JTextArea textArea;

static PrintWriter out;

public static void main(String[] args) {

try {

Socket s = new Socket("115.20.247.170",5555);


out = new PrintWriter(s.getOutputStream(), true);


JFrame f = new JFrame("채팅");

f.setSize(600, 400);

f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);

textArea = new JTextArea();

textField = new JTextField(10);

textField.addActionListener(


new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

// TODO Auto-generated method stub

out.println(textField.getText());

}

}

);

f.add(textField, BorderLayout.SOUTH);

f.add(textArea , BorderLayout.CENTER);

f.setVisible(true);

} catch (UnknownHostException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}



'Programming > JAVA,JSP' 카테고리의 다른 글

JAVA 채팅 예제 #2  (0) 2014.01.20
JAVA 채팅 Server 예제 #1  (0) 2014.01.20
JAVA FIle 실습 #1  (0) 2014.01.17
JAVA File 실습  (0) 2014.01.17
JAVA 공던지기 게임 완성  (0) 2014.01.16

Android GoogleMap API V2

Programming/Android 2014. 1. 19. 11:50 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

안드로이드 맵에 검색창 띄워서 검색하기



Android Geocoding – Showing User Input Location on Google Map Android API V2



In this article, we will create an Android application which facilitates users to input street address in an EditText and on clicking the find button, application draws corresponding location marker on the Google Map Android API v2 using Google’s Geocoder API.

This application is an upgraded version of the application discussed in the article titled “Android Geocoding – Showing User Input Location on Google Map” where the location is shown in Google Map Android API v1.

This application is developed in Eclipse 4.2.1 with ADT plugin ( 21.0.0 ) and Android SDK ( 21.0.0 ) and is tested in a real Android Phone with Android 2.3.6  ( GingerBread ).


1. Download and configure Google Play Services Library in Eclipse

Please follow the given below link to setup Google Play Service library in Eclipse.

http://developer.android.com/google/play-services/setup.html


2. Create a new Android Application Project namely “LocationGeocodingV2″

Create new Android application project

Figure 1 : Create new Android application project


3. Configure Android Application Project

Configure Android Application Project

Figure 2 : Configure Android Application Project


4. Design Application Launcher Icon

Design Application Launcher Icon

Figure 3 : Design Application Launcher Icon


5. Create a blank activity

Create a blank activity

Figure 4 : Create a blank activity


6. Enter Main Activity Details

Enter Main Activity Details

Figure 5 : Enter Main Activity Details


7. Link to Google Play Service Library

Link to Google Play Services Library

Figure 6 : Link to Google Play Services Library


8. Get the API key for Google Maps Android API v2

We need to get an API key from Google to use Google Maps in Android application. Please follow the given below link to get the API key for Google Maps Android API v2.

https://developers.google.com/maps/documentation/android/start


9. Add Android Support library to this project

By default, Android support library (android-support-v4.jar ) is added to this project by Eclipse IDE to the directory libs. If it is not added, we can do it manually by doing the following steps :

  • Open Project Explorer by Clicking “Window -> Show View -> Project Explorer”
  • Right click this project
  • Then from popup window, Click “Android Tools -> Add Support Library “

10. Update the file AndroidManfiest.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?xml version="1.0" encoding="utf-8"?>
    package="in.wptrafficanalyzer.locationgeocodingv2"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />
 
    <permission
        android:name="in.wptrafficanalyzer.locationgeocodingv2.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>
 
    <uses-permission android:name="in.wptrafficanalyzer.locationgeocodingv2.permission.MAPS_RECEIVE"/>
 
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
 
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>
 
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
 
        <activity
            android:name="in.wptrafficanalyzer.locationgeocodingv2.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
 
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="YOUR_API_KEY"/>
    </application>
</manifest>

11. Update the layout file res/layout/activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >
 
    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
 
        <Button
            android:id="@+id/btn_find"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/str_btn_find"
            android:layout_alignParentRight="true" />
 
        <EditText
            android:id="@+id/et_location"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:inputType="text"
            android:hint="@string/hnt_et_location"
            android:layout_toLeftOf="@id/btn_find" />
 
    </RelativeLayout>
 
    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment" />
 
</LinearLayout>

12. Update the file res/values/strings.xml

1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">LocationGeocodingV2</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="str_btn_find">Find</string>
    <string name="hnt_et_location">Enter location</string>
</resources>

13. Update the file src/in/wptrafficanalyzer/locationgeocodingv2/MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package in.wptrafficanalyzer.locationgeocodingv2;
 
import java.io.IOException;
import java.util.List;
 
import android.location.Address;
import android.location.Geocoder;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
 
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
 
public class MainActivity extends FragmentActivity {
 
    GoogleMap googleMap;
    MarkerOptions markerOptions;
    LatLng latLng;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        SupportMapFragment supportMapFragment = (SupportMapFragment)
        getSupportFragmentManager().findFragmentById(R.id.map);
 
        // Getting a reference to the map
        googleMap = supportMapFragment.getMap();
 
        // Getting reference to btn_find of the layout activity_main
        Button btn_find = (Button) findViewById(R.id.btn_find);
 
        // Defining button click event listener for the find button
        OnClickListener findClickListener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                // Getting reference to EditText to get the user input location
                EditText etLocation = (EditText) findViewById(R.id.et_location);
 
                // Getting user input location
                String location = etLocation.getText().toString();
 
                if(location!=null && !location.equals("")){
                    new GeocoderTask().execute(location);
                }
            }
        };
 
        // Setting button click event listener for the find button
        btn_find.setOnClickListener(findClickListener);
 
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
 
    // An AsyncTask class for accessing the GeoCoding Web Service
    private class GeocoderTask extends AsyncTask<String, Void, List<Address>>{
 
        @Override
        protected List<Address> doInBackground(String... locationName) {
            // Creating an instance of Geocoder class
            Geocoder geocoder = new Geocoder(getBaseContext());
            List<Address> addresses = null;
 
            try {
                // Getting a maximum of 3 Address that matches the input text
                addresses = geocoder.getFromLocationName(locationName[0], 3);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return addresses;
        }
 
        @Override
        protected void onPostExecute(List<Address> addresses) {
 
            if(addresses==null || addresses.size()==0){
                Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
            }
 
            // Clears all the existing markers on the map
            googleMap.clear();
 
            // Adding Markers on Google Map for each matching address
            for(int i=0;i<addresses.size();i++){
 
                Address address = (Address) addresses.get(i);
 
                // Creating an instance of GeoPoint, to display in Google Map
                latLng = new LatLng(address.getLatitude(), address.getLongitude());
 
                String addressText = String.format("%s, %s",
                address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
                address.getCountryName());
 
                markerOptions = new MarkerOptions();
                markerOptions.position(latLng);
                markerOptions.title(addressText);
 
                googleMap.addMarker(markerOptions);
 
                // Locate the first location
                if(i==0)
                    googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
            }
        }
    }
}

14. Screenshot of the application in execution

Showing Street Address in Google Map Android API V2

Figure 7 : Showing Street Address in Google Map Android API V2


15. Download Source Code









출처 : http://wptrafficanalyzer.in/blog/android-geocoding-showing-user-input-location-on-google-map-android-api-v2/



'Programming > Android' 카테고리의 다른 글

Android 2014-03-01 GoogleMap V2 띄우기  (0) 2014.03.01
Android 반짝이는 화면  (0) 2014.02.22
viewpagertest  (0) 2014.01.14
Android FrameLayout 예제  (0) 2014.01.12
안드로이드 위치 기록, 위치 추적  (0) 2014.01.12

JAVA FIle 실습 #1

Programming/JAVA,JSP 2014. 1. 17. 17:36 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

package com.tistory.tansanc;


import java.awt.Color;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;


import javax.swing.JButton;

import javax.swing.JColorChooser;

import javax.swing.JFrame;

import javax.swing.JPanel;


class MyFrame extends JFrame {

private JButton button1;

private JButton button2;

private JPanel panel;


public MyFrame() {

this.setSize(300, 200);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

this.setTitle("이벤트 예제");

panel = new JPanel();

button1 = new JButton("색상선택");

button1.addActionListener(new MyListener());

panel.add(button1);

this.add(panel);

LoadFile();

this.setVisible(true);

}


private void LoadFile() {

// TODO Auto-generated method stub

ObjectInputStream oos = null;

try {

oos = new ObjectInputStream(

new FileInputStream("Color.bin"));

Color newColor = (Color)oos.readObject();

panel.setBackground(newColor);

oos.close();

} catch ( IOException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}


private class MyListener implements ActionListener {

public void actionPerformed(ActionEvent e) {

if (e.getSource() == button1) {

JColorChooser colorChooser = 

new JColorChooser();

Color newColor =

colorChooser.showDialog(MyFrame.this,

"Hello",Color.red);

System.out.println(newColor);

panel.setBackground(newColor);

ObjectOutputStream oos = null;

try {

oos = new ObjectOutputStream(

new FileOutputStream("Color.bin"));

oos.writeObject(newColor);

oos.close();

} catch ( IOException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

}

}

}


public class MyFrameTest2 {

public static void main(String[] args) {

MyFrame t = new MyFrame();

}

}



'Programming > JAVA,JSP' 카테고리의 다른 글

JAVA 채팅 Server 예제 #1  (0) 2014.01.20
JAVA 채팅 Client 예제 #1  (0) 2014.01.20
JAVA File 실습  (0) 2014.01.17
JAVA 공던지기 게임 완성  (0) 2014.01.16
JAVA 공던지기 게임  (0) 2014.01.16

JAVA File 실습

Programming/JAVA,JSP 2014. 1. 17. 16:52 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

1. ColorChooser를 활용한

Panel Background Color 변경

및 파일이용하여 변경사항 저장


2. 암호화된 파일저장 & 암호화된 파일 읽기기능


3. 파일에서 찾고자하는 문자열을 갖고 있는지 검색하는 프로그램


4. 특정 폴더 내부에서 찾고자하는 문자열을 갖고 있는 파일을 검색하는 프로그램

'Programming > JAVA,JSP' 카테고리의 다른 글

JAVA 채팅 Client 예제 #1  (0) 2014.01.20
JAVA FIle 실습 #1  (0) 2014.01.17
JAVA 공던지기 게임 완성  (0) 2014.01.16
JAVA 공던지기 게임  (0) 2014.01.16
JAVA 가계부 #2  (0) 2014.01.14

JAVA 공던지기 게임 완성

Programming/JAVA,JSP 2014. 1. 16. 17:30 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

package com.tistory.tansanc;

 

import java.awt.BorderLayout;

import java.awt.Color;

import java.awt.Font;

import java.awt.Graphics;

import java.awt.Image;

import java.awt.Toolkit;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.awt.event.MouseEvent;

import java.awt.event.MouseListener;

import java.awt.event.MouseMotionListener;

 

import javax.swing.JButton;

import javax.swing.JComponent;

import javax.swing.JFrame;

 

// 그림이 그려지는 컴포넌트를 정의

class MyComponent extends JComponent {

 

   public int x = 30;

   public int y = 420;

 

   public boolean wire = true;

 

   public void paint(Graphics g) {

       g.setColor(new Color(167, 114, 48));

       g.drawLine(100, 500, 100, 450);

       g.drawLine(100, 450, 75, 400);

       g.drawLine(100, 450, 125, 400);

 

       if (wire) {

          g.setColor(new Color(0, 255, 0));

          g.drawLine(75, 400, x + 25, y + 25);

         g.drawLine(125, 400, x + 25, y + 25);

       }

       g.setColor(new Color(255, 0, 0));

       g.fillOval(x, y, 50, 50);

 

       g.setColor(new Color(0, 0, 255));

       g.drawOval(400, 150, 100, 50);

       // x : 400 ~ 500

       // y : 150 ~ 200

       g.drawLine(500, 150, 500, 600);

 

       g.setFont(new Font("Monospaced", Font.BOLD, 20));

      g.drawString("점수 : " + point, 10, 100);

       if (x + 25 > 400 && x + 25 < 500 && y + 25 > 150 && y + 25 < 200) {

          pointBool = true;

       } else {

          if (pointBool == true) {

             point++;

 

          }

          pointBool = false;

       }

       Image image;

       try {

          //image = ImageIO.read(this.getClass().getResource("angry.png"));

          image= Toolkit.getDefaultToolkit().getImage("angry.png");

          int w = image.getWidth(null);

          int h = image.getHeight(null);

          g.drawImage(image, x, y, 50, 50, null);

       } catch (Exception e) {

          // TODO Auto-generated catch block

          e.printStackTrace();

       }

 

      

   }

 

   boolean pointBool = false;

   int point = 0;

}

 

// 프레임 컴포넌트를 상속받아서 정의

public class StarFrame extends JFrame implements ActionListener,

       MouseMotionListener, MouseListener {

   public static final int WIDTH = 800;

   public static final int HEIGHT = 600;

 

   JButton next = new JButton("Next");

   MyComponent c;

 

   public StarFrame() {

       setTitle("MyFrame");

       setSize(WIDTH, HEIGHT);

   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

       setVisible(true);

 

       // MyComponent 객체 생성하여 프레임에 추가

       c = new MyComponent();

       next.addActionListener(this);

 

       add(c, BorderLayout.CENTER);

       add(next, BorderLayout.SOUTH);

 

       addMouseMotionListener(this);

       addMouseListener(this);

   }

 

   public static void main(String[] args) {

       StarFrame frame = new StarFrame();

   }

 

   @Override

   public void actionPerformed(ActionEvent arg0) {

       // TODO Auto-generated method stub

   }

 

   @Override

   public void mouseDragged(MouseEvent arg0) {

       // TODO Auto-generated method stub

       if (arg0.getX() < 140 && arg0.getY() > 400) {

 

          c.x = arg0.getX() - 30;

          c.y = arg0.getY() - 60;

          c.repaint();

       }

 

   }

 

   @Override

   public void mouseMoved(MouseEvent arg0) {

       // TODO Auto-generated method stub

 

   }

 

   @Override

   public void mouseClicked(MouseEvent arg0) {

       // TODO Auto-generated method stub

 

   }

 

   @Override

   public void mouseEntered(MouseEvent arg0) {

       // TODO Auto-generated method stub

 

   }

 

   @Override

   public void mouseExited(MouseEvent arg0) {

       // TODO Auto-generated method stub

 

   }

 

   boolean mouse = false;

   int startX;

   int startY;

   int endX;

   int endY;

 

   @Override

   public void mousePressed(MouseEvent arg0) {

       // TODO Auto-generated method stub

       if (arg0.getX() < 140 && arg0.getY() > 400) {

          if (mouse == false) {

 

             c.wire = true;

             c.x = arg0.getX() - 30;

             c.y = arg0.getY() - 60;

             c.repaint();

             startX = arg0.getX();

             startY = arg0.getY();

             mouse = true;

 

          }

       }

   }

 

   @Override

   public void mouseReleased(MouseEvent arg0) {

       // TODO Auto-generated method stub

 

       if (mouse == true) {

          endX = arg0.getX();

          endY = arg0.getY();

          System.out.println("power X : " + (startX - endX));

          System.out.println("power Y : " + (startY - endY));

          mouse = false;

          c.wire = false;

          if (ft != null) {

             ft.stop();

          }

          ft = new FlyThread((startX - endX), (startY - endY));

          ft.start();

       }

   }

 

   FlyThread ft;

 

   class FlyThread extends Thread {

       int powerX;

       int powerY;

 

       FlyThread(int powerX, int powerY) {

          this.powerX = powerX;

          this.powerY = powerY;

       }

 

       @Override

       public void run() {

          while (true) {

             if (c.x > 800 || c.x < -50) {

                 break;

             }

             if (c.y > 600 || c.y < -50) {

                 break;

             }

             c.x += powerX / 10;

             c.y += powerY / 10;

             powerY += 1;

             try {

                 sleep(10);

             } catch (InterruptedException e) {

                 // TODO Auto-generated catch block

                 e.printStackTrace();

             }

             c.repaint();

 

          }

       }

   }

 

}

 

 

'Programming > JAVA,JSP' 카테고리의 다른 글

JAVA FIle 실습 #1  (0) 2014.01.17
JAVA File 실습  (0) 2014.01.17
JAVA 공던지기 게임  (0) 2014.01.16
JAVA 가계부 #2  (0) 2014.01.14
JAVA 가계부  (0) 2014.01.14

JAVA 공던지기 게임

Programming/JAVA,JSP 2014. 1. 16. 16:49 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

package com.tistory.tansanc;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import javax.swing.*;

// 그림이 그려지는 컴포넌트를 정의
class MyComponent extends JComponent {

 public int x = 30;
 public int y = 420;
 
 public boolean wire = true;

 public void paint(Graphics g) {
  g.setColor(new Color(167, 114, 48));
  g.drawLine(100, 500, 100, 450);
  g.drawLine(100, 450, 75, 400);
  g.drawLine(100, 450, 125, 400);

  if( wire )
  {
   g.setColor(new Color(0, 255, 0));
   g.drawLine(75, 400, x + 25, y + 25);
   g.drawLine(125, 400, x + 25, y + 25);
  }
  g.setColor(new Color(255, 0, 0));
  g.fillOval(x, y, 50, 50);
 }
}

// 프레임 컴포넌트를 상속받아서 정의
public class StarFrame extends JFrame implements ActionListener,
  MouseMotionListener, MouseListener {
 public static final int WIDTH = 800;
 public static final int HEIGHT = 600;

 JButton next = new JButton("Next");
 MyComponent c;

 public StarFrame() {
  setTitle("MyFrame");
  setSize(WIDTH, HEIGHT);
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  setVisible(true);

  // MyComponent 객체 생성하여 프레임에 추가
  c = new MyComponent();
  next.addActionListener(this);

  add(c, BorderLayout.CENTER);
  add(next, BorderLayout.SOUTH);

  addMouseMotionListener(this);
  addMouseListener(this);
 }

 public static void main(String[] args) {
  StarFrame frame = new StarFrame();
 }

 @Override
 public void actionPerformed(ActionEvent arg0) {
  // TODO Auto-generated method stub
 }

 @Override
 public void mouseDragged(MouseEvent arg0) {
  // TODO Auto-generated method stub
  if (arg0.getX() < 140 && arg0.getY() > 400) {

   c.x = arg0.getX()-30;
   c.y = arg0.getY()-60;
   c.repaint();
  }

 }

 @Override
 public void mouseMoved(MouseEvent arg0) {
  // TODO Auto-generated method stub

 }

 @Override
 public void mouseClicked(MouseEvent arg0) {
  // TODO Auto-generated method stub

 }

 @Override
 public void mouseEntered(MouseEvent arg0) {
  // TODO Auto-generated method stub

 }

 @Override
 public void mouseExited(MouseEvent arg0) {
  // TODO Auto-generated method stub

 }

 boolean mouse = false;
 int startX;
 int startY;
 int endX;
 int endY;

 @Override
 public void mousePressed(MouseEvent arg0) {
  // TODO Auto-generated method stub
  if (arg0.getX() < 140 && arg0.getY() > 400) {
   if (mouse == false) {

    c.wire = true;
    c.x = arg0.getX()-30;
    c.y = arg0.getY()-60;
    c.repaint();
    startX = arg0.getX();
    startY = arg0.getY();
    mouse = true;
    
   }
  }
 }

 @Override
 public void mouseReleased(MouseEvent arg0) {
  // TODO Auto-generated method stub

  if (mouse == true) {
   endX = arg0.getX();
   endY = arg0.getY();
   System.out.println("power X : " + (startX - endX));
   System.out.println("power Y : " + (startY - endY));
   mouse = false;
   c.wire = false;
   if( ft != null)
   {
    ft.stop();
   }
   ft = new FlyThread((startX - endX), (startY - endY));
   ft.start();
  }
 }
 FlyThread ft;
 class FlyThread extends Thread
 {
  int powerX;
  int powerY;
  FlyThread(int powerX, int powerY)
  {
   this.powerX = powerX;
   this.powerY = powerY;
  }
  @Override
  public void run() {
   while(true)
   {
    if( c.x > 800)
    {
     break;
    }
    if( c.y > 600)
    {
     break;
    }
    c.x += powerX/10;
    c.y += powerY/10;
    powerY += 1;
    try {
     sleep(10);
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    c.repaint();
    
   }
  }
 }

}

'Programming > JAVA,JSP' 카테고리의 다른 글

JAVA File 실습  (0) 2014.01.17
JAVA 공던지기 게임 완성  (0) 2014.01.16
JAVA 가계부 #2  (0) 2014.01.14
JAVA 가계부  (0) 2014.01.14
JAVA 쿵쿵따 게임 #2 중복 탐지  (0) 2014.01.09

CPP 연산자 오버로딩

Programming/C,CPP,CS 2014. 1. 16. 12:42 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

#include <iostream>

#include <string>

using namespace std;


class ImaginaryNumber

{

public:

ImaginaryNumber();

ImaginaryNumber(double a, double b);

void SetA(double a);

void SetB(double b);

double GetA();

double GetB();

char* GetImaginaryNumber();

ImaginaryNumber addImaginaryNumber(ImaginaryNumber in2);

ImaginaryNumber operator+(ImaginaryNumber in2);


private:

double a; //실수부

double b; //허수부 (b≠0)

};


ImaginaryNumber::ImaginaryNumber()

{

a = 0;

b = 0;

}

ImaginaryNumber::ImaginaryNumber(double a, double b)

{

this->a = a;

this->b = b;

}

void ImaginaryNumber::SetA(double a)

{

this->a = a;

}

void ImaginaryNumber::SetB(double b)

{

this->b = b;

}

double ImaginaryNumber::GetA()

{

return a;

}

double ImaginaryNumber::GetB()

{

return b;

}


char* ImaginaryNumber::GetImaginaryNumber()

{

static char text[30];

sprintf(text, "%lf %+lf i", a, b);

return text;

}


ImaginaryNumber ImaginaryNumber::addImaginaryNumber(ImaginaryNumber in2)

{

ImaginaryNumber result;

result.a = a + in2.a;

result.b = b + in2.b;

return result;

}


ImaginaryNumber ImaginaryNumber::operator+(ImaginaryNumber in2)

{

ImaginaryNumber result;

result.a = a + in2.a;

result.b = b + in2.b;

return result;

}

int main ()

{

ImaginaryNumber in1( 3 , -4 ); // 3 -4i

ImaginaryNumber in2( 5 , -2 ); // 5 -2i

cout << in1.GetImaginaryNumber() << endl;

cout << in2.GetImaginaryNumber() << endl;

ImaginaryNumber in4 = in1 + in2;


cout << in4.GetImaginaryNumber() << endl;


return 0;

}

CPP 연산자 오버로딩

Programming/C,CPP,CS 2014. 1. 16. 12:28 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

#include <iostream>

#include <string>

using namespace std;


class ImaginaryNumber

{

public:

ImaginaryNumber();

ImaginaryNumber(double a, double b);

void SetA(double a);

void SetB(double b);

double GetA();

double GetB();

char* GetImaginaryNumber();


private:

double a; //실수부

double b; //허수부 (b≠0)

};


ImaginaryNumber::ImaginaryNumber()

{

a = 0;

b = 0;

}

ImaginaryNumber::ImaginaryNumber(double a, double b)

{

this->a = a;

this->b = b;

}

void ImaginaryNumber::SetA(double a)

{

this->a = a;

}

void ImaginaryNumber::SetB(double b)

{

this->b = b;

}

double ImaginaryNumber::GetA()

{

return a;

}

double ImaginaryNumber::GetB()

{

return b;

}


char* ImaginaryNumber::GetImaginaryNumber()

{

static char text[30];

sprintf(text, "%lf %+lf i", a, b);

return text;

}

int main ()

{

ImaginaryNumber in1(3,-4);

ImaginaryNumber in2(5,-2);

cout << in1.GetImaginaryNumber() << endl;

cout << in2.GetImaginaryNumber() << endl;

return 0;

}

JAVA 가계부 #2

Programming/JAVA,JSP 2014. 1. 14. 20:15 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.BufferedReader;

import java.io.FileReader;

import java.io.FileWriter;

import java.util.StringTokenizer;

 

import javax.swing.JComboBox;

import javax.swing.RowSorter;

import javax.swing.table.TableModel;

import javax.swing.table.TableRowSorter;

 

/*

 * To change this template, choose Tools | Templates

 * and open the template in the editor.

 */

 

/**

 *

 * @author Suser

 */

public class NewJFrame extends javax.swing.JFrame implements ActionListener {

 

    /**

     * Creates new form NewJFrame

     */

    public NewJFrame() {

       initComponents();

    }

 

    /**

     * This method is called from within the constructor to initialize the form.

     * WARNING: Do NOT modify this code. The content of this method is always

     * regenerated by the Form Editor.

     */

    @SuppressWarnings("unchecked")

    // <editor-fold defaultstate="collapsed"

    // desc="Generated Code">//GEN-BEGIN:initComponents

    private void initComponents() {

 

       jLabel1 = new javax.swing.JLabel();

      String[] monthArray = { "1", "2", "3", "4", "5", "6", "7", "8",

              "9", "10", "11", "12" };

       jComboBox1 = new JComboBox(monthArray);

       jComboBox1.addActionListener(this);

 

       jScrollPane1 = new javax.swing.JScrollPane();

       jTable1 = new javax.swing.JTable();

       jScrollPane2 = new javax.swing.JScrollPane();

       jTable2 = new javax.swing.JTable();

       jLabel2 = new javax.swing.JLabel();

       jButton1 = new javax.swing.JButton();

       jButton2 = new javax.swing.JButton();

       jButton3 = new javax.swing.JButton();

       jButton4 = new javax.swing.JButton();

       jButton5 = new javax.swing.JButton();

       jButton6 = new javax.swing.JButton();

       jButton7 = new javax.swing.JButton();

       jButton8 = new javax.swing.JButton();

       jButton9 = new javax.swing.JButton();

 

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

 

      jLabel1.setFont(new java.awt.Font("바탕", 1, 24)); // NOI18N

       jLabel1.setForeground(new java.awt.Color(255, 153, 153));

      jLabel1.setText("2014 월별 MoneyBook");

 

       int i = 1;

       jTable1.setModel(new javax.swing.table.DefaultTableModel(

              new Object[][] {

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null } },

              new String[] { "날짜", "수입 항목", "내용", "금액", "지출 항목", "내용", "금액" }));

       jScrollPane1.setViewportView(jTable1);

       // jTable1.getColumnModel().getColumn(0).setCellEditor(new

       // DatePickerCellEditor());

 

       RowSorter<TableModel> sorter = new TableRowSorter<TableModel>(

              jTable1.getModel());

       jTable1.setRowSorter(sorter);

 

        jTable1.setAutoCreateColumnsFromModel(true);

 

       loadFile();

 

       jTable2.setModel(new javax.swing.table.DefaultTableModel(

             new Object[][] { { null, null, null, null, null } },

              new String[] { "전월 이월금", "수입 합계", "지출 합계", " 합계", "잔액" }));

       jScrollPane2.setViewportView(jTable2);

 

       jButton1.setText("항목검색");

       jButton1.addActionListener(new java.awt.event.ActionListener() {

           public void actionPerformed(java.awt.event.ActionEvent evt) {

              jButton1ActionPerformed(evt);

           }

       });

 

       jButton2.setText("오랜순 정렬");

 

       jButton3.setText("낮은금액순정렬");

 

       jButton4.setText("잔액고침");

       jButton4.addActionListener(new java.awt.event.ActionListener() {

           public void actionPerformed(java.awt.event.ActionEvent evt) {

              loadFile();

           }

 

       });

 

       jButton5.setText("사용방법");

 

       jButton6.setText("내보내기");

       jButton6.addActionListener(new java.awt.event.ActionListener() {

           public void actionPerformed(java.awt.event.ActionEvent evt) {

              saveFile();

           }

 

       });

 

       jButton7.setText("항목검색");

       jButton7.addActionListener(new java.awt.event.ActionListener() {

           public void actionPerformed(java.awt.event.ActionEvent evt) {

              jButton7ActionPerformed(evt);

           }

       });

 

       jButton8.setText("높은금액순정렬");

       jButton8.addActionListener(new java.awt.event.ActionListener() {

           public void actionPerformed(java.awt.event.ActionEvent evt) {

              jButton8ActionPerformed(evt);

           }

       });

 

       jButton9.setText("최신순 정렬");

 

       javax.swing.GroupLayout layout = new javax.swing.GroupLayout(

              getContentPane());

       getContentPane().setLayout(layout);

       layout.setHorizontalGroup(layout

           .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

              .addGroup(

                      layout.createSequentialGroup()

                            .addContainerGap()

                            .addGroup(

                                    layout.createParallelGroup(

                                           javax.swing.GroupLayout.Alignment.LEADING)

                                           .addGroup(

                                                  layout.createSequentialGroup()

                                                        .addComponent(

                                                               jComboBox1,

                                                                javax.swing.GroupLayout.PREFERRED_SIZE,

                                                               102,

                                                                javax.swing.GroupLayout.PREFERRED_SIZE)

                                                        .addContainerGap(

                                                                javax.swing.GroupLayout.DEFAULT_SIZE,

                                                               Short.MAX_VALUE))

                                           .addGroup(

                                                  layout.createSequentialGroup()

                                                        .addGroup(

                                                               layout.createParallelGroup(

                                                                       javax.swing.GroupLayout.Alignment.TRAILING,

                                                                      false)

                                                                      .addGroup(

                                                                              layout.createSequentialGroup()

                                                                                    .addGap(10,

                                                                                           10,

                                                                                            10)

                                                                                    .addComponent(

                                                                                           jLabel1,

                                                                                            javax.swing.GroupLayout.DEFAULT_SIZE,

                                                                                            javax.swing.GroupLayout.DEFAULT_SIZE,

                                                                                            Short.MAX_VALUE))

                                                                      .addComponent(

                                                                             jScrollPane2,

                                                                              javax.swing.GroupLayout.Alignment.LEADING)

                                                                      .addComponent(

                                                                             jScrollPane1,

                                                                              javax.swing.GroupLayout.Alignment.LEADING,

                                                                              javax.swing.GroupLayout.DEFAULT_SIZE,

                                                                             518,

                                                                             Short.MAX_VALUE))

                                                        .addGroup(

                                                               layout.createParallelGroup(

                                                                       javax.swing.GroupLayout.Alignment.LEADING)

                                                                      .addGroup(

                                                                              layout.createSequentialGroup()

                                                                                    .addGap(65,

                                                                                           65,

                                                                                           65)

                                                                                    .addComponent(

                                                                                            jLabel2))

                                                                      .addGroup(

                                                                              layout.createSequentialGroup()

                                                                                    .addGap(18,

                                                                                           18,

                                                                                           18)

                                                                                     .addGroup(

                                                                                            layout.createParallelGroup(

                                                                                                   javax.swing.GroupLayout.Alignment.LEADING)

                                                                                                   .addComponent(

                                                                                                         jButton5)

                                                                                                   .addComponent(

                                                                                                         jButton2)

                                                                                                   .addComponent(

                                                                                                         jButton1)

                                                                                                   .addComponent(

                                                                                                         jButton3)

                                                                                                    .addComponent(

                                                                                                         jButton4)

                                                                                                   .addComponent(

                                                                                                         jButton7)

                                                                                                   .addComponent(

                                                                                                         jButton8)

                                                                                                   .addComponent(

                                                                                                         jButton9)

                                                                                                   .addComponent(

                                                                                                         jButton6))))

                                                        .addGap(0,

                                                               38,

                                                               Short.MAX_VALUE)))));

       layout.setVerticalGroup(layout

           .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

              .addGroup(

                      layout.createSequentialGroup()

                             .addComponent(jComboBox1)

                            .addGap(4, 4, 4)

                            .addComponent(jLabel1,

                                    javax.swing.GroupLayout.PREFERRED_SIZE,

                                   33,

                                    javax.swing.GroupLayout.PREFERRED_SIZE)

                            .addPreferredGap(

                                javax.swing.LayoutStyle.ComponentPlacement.RELATED,

                                    javax.swing.GroupLayout.DEFAULT_SIZE,

                                    Short.MAX_VALUE)

                            .addGroup(

                                    layout.createParallelGroup(

                                           javax.swing.GroupLayout.Alignment.LEADING,

                                          false)

                                           .addComponent(

                                                  jButton5,

                                                  javax.swing.GroupLayout.DEFAULT_SIZE,

                                                  javax.swing.GroupLayout.DEFAULT_SIZE,

                                                  Short.MAX_VALUE)

                                           .addComponent(

                                                  jScrollPane2,

                                                  javax.swing.GroupLayout.DEFAULT_SIZE,

                                                  59, Short.MAX_VALUE))

                            .addGroup(

                                    layout.createParallelGroup(

                                           javax.swing.GroupLayout.Alignment.LEADING,

                                          false)

                                           .addGroup(

                                                  layout.createSequentialGroup()

                                                        .addGap(42, 42,

                                                               42)

                                                        .addComponent(

                                                               jLabel2)

                                                        .addPreferredGap(

                                                            javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

                                                        .addComponent(

                                                               jButton1)

                                                        .addGap(14, 14,

                                                               14)

                                                        .addComponent(

                                                               jButton2)

                                                        .addGap(14, 14,

                                                               14)

                                                        .addComponent(

                                                               jButton9)

                                                        .addGap(18, 18,

                                                               18)

                                                        .addComponent(

                                                               jButton7)

                                                        .addGap(18, 18,

                                                               18)

                                                        .addComponent(

                                                               jButton8)

                                                        .addGap(18, 18,

                                                               18)

                                                        .addComponent(

                                                               jButton3)

                                                         .addGap(40, 40,

                                                               40)

                                                        .addComponent(

                                                               jButton4)

                                                        .addPreferredGap(

                                                            javax.swing.LayoutStyle.ComponentPlacement.RELATED,

                                                                javax.swing.GroupLayout.DEFAULT_SIZE,

                                                               Short.MAX_VALUE)

                                                        .addComponent(

                                                               jButton6))

                                           .addGroup(

                                                  layout.createSequentialGroup()

                                                        .addGap(18, 18,

                                                                18)

                                                        .addComponent(

                                                               jScrollPane1,

                                                                javax.swing.GroupLayout.PREFERRED_SIZE,

                                                                javax.swing.GroupLayout.DEFAULT_SIZE,

                                                                javax.swing.GroupLayout.PREFERRED_SIZE)))

                            .addContainerGap(

                                    javax.swing.GroupLayout.DEFAULT_SIZE,

                                    Short.MAX_VALUE)));

 

       pack();

    }// </editor-fold>//GEN-END:initComponents

 

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jComboBox1ActionPerformed

       // TODO add your handling code here:

    }// GEN-LAST:event_jComboBox1ActionPerformed

 

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButton1ActionPerformed

       // TODO add your handling code here:

    }// GEN-LAST:event_jButton1ActionPerformed

 

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButton7ActionPerformed

       // TODO add your handling code here:

    }// GEN-LAST:event_jButton7ActionPerformed

 

    private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButton8ActionPerformed

       // TODO add your handling code here:

    }// GEN-LAST:event_jButton8ActionPerformed

 

    /**

     * @param args

     *            the command line arguments

     */

    public static void main(String args[]) {

       /* Set the Nimbus look and feel */

       // <editor-fold defaultstate="collapsed"

       // desc=" Look and feel setting code (optional) ">

       /*

        * If Nimbus (introduced in Java SE 6) is not available, stay with the

        * default look and feel. For details see

        * http://download.oracle.com/javase

        * /tutorial/uiswing/lookandfeel/plaf.html

        */

       try {

           for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager

                  .getInstalledLookAndFeels()) {

             if ("Nimbus".equals(info.getName())) {

              javax.swing.UIManager.setLookAndFeel(info.getClassName());

                  break;

              }

           }

       } catch (ClassNotFoundException ex) {

       java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(

                  java.util.logging.Level.SEVERE, null, ex);

       } catch (InstantiationException ex) {

       java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(

                  java.util.logging.Level.SEVERE, null, ex);

       } catch (IllegalAccessException ex) {

       java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(

                  java.util.logging.Level.SEVERE, null, ex);

       } catch (javax.swing.UnsupportedLookAndFeelException ex) {

       java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(

                  java.util.logging.Level.SEVERE, null, ex);

       }

       // </editor-fold>

 

       /* Create and display the form */

       java.awt.EventQueue.invokeLater(new Runnable() {

           public void run() {

              new NewJFrame().setVisible(true);

           }

       });

    }

 

    // Variables declaration - do not modify//GEN-BEGIN:variables

    private javax.swing.JButton jButton1;

    private javax.swing.JButton jButton2;

    private javax.swing.JButton jButton3;

    private javax.swing.JButton jButton4;

    private javax.swing.JButton jButton5;

    private javax.swing.JButton jButton6;

    private javax.swing.JButton jButton7;

    private javax.swing.JButton jButton8;

    private javax.swing.JButton jButton9;

    private javax.swing.JComboBox jComboBox1;

    private javax.swing.JLabel jLabel1;

    private javax.swing.JLabel jLabel2;

    private javax.swing.JScrollPane jScrollPane1;

    private javax.swing.JScrollPane jScrollPane2;

    private javax.swing.JTable jTable1;

    private javax.swing.JTable jTable2;

    // End of variables declaration//GEN-END:variables

    int thisMonth = 1;

 

    @Override

    public void actionPerformed(ActionEvent arg0) {

       // TODO Auto-generated method stub

       if (arg0.getSource() == jComboBox1) {

           String str = (String) jComboBox1.getSelectedItem();

           jLabel1.setText("2014 " + str + " MoneyBook");

           // "1"

           // "1"

           thisMonth = Integer.parseInt(str.charAt(0) + "");

       }

 

    }

 

    private void saveFile() {

       try {

           FileWriter out = null;

           out = new FileWriter(thisMonth + ".txt");

           String str = "";

           for (int i = 0; i < 31; i++) {

              str += (String) jTable1.getModel().getValueAt(i, 0);

              str += "\t";

              str += (String) jTable1.getModel().getValueAt(i, 1);

              str += "\t";

              str += (String) jTable1.getModel().getValueAt(i, 2);

              str += "\t";

              str += (String) jTable1.getModel().getValueAt(i, 3);

              str += "\t";

              str += (String) jTable1.getModel().getValueAt(i, 4);

              str += "\t";

              str += (String) jTable1.getModel().getValueAt(i, 5);

              str += "\t";

              str += (String) jTable1.getModel().getValueAt(i, 6);

              str += "\n";

           }

           out.write(str);

           out.flush();

           out.close();

       } catch (Exception e) {

 

       }

    }

 

    private void loadFile() {

       // TODO Auto-generated method stub

 

       try {

           FileReader in = new FileReader(thisMonth + ".txt");

           BufferedReader br = new BufferedReader(in);

           String thisLine;

           int rowIndex = 0;

           while ((thisLine = br.readLine()) != null) { // while loop begins

 

              int columnIndex = 0;

              StringTokenizer tokenizer = new StringTokenizer(thisLine, "\t"); // 설정

              while (tokenizer.hasMoreTokens()) {

                  String token = tokenizer.nextToken();

                  System.out.println(token + " columnIndex " + columnIndex

                         + " rowIndex " + rowIndex);

                  if (token.equals("null")) {

                     token = " ";

                  }

                  jTable1.getModel().setValueAt(token, rowIndex, columnIndex);

 

                  columnIndex++;

              }

 

              rowIndex++;

           }

       } catch (Exception e) {

           e.printStackTrace();

       }

    }

}

 

'Programming > JAVA,JSP' 카테고리의 다른 글

JAVA 공던지기 게임 완성  (0) 2014.01.16
JAVA 공던지기 게임  (0) 2014.01.16
JAVA 가계부  (0) 2014.01.14
JAVA 쿵쿵따 게임 #2 중복 탐지  (0) 2014.01.09
JAVA 쿵쿵따 게임  (0) 2014.01.09

JAVA 가계부

Programming/JAVA,JSP 2014. 1. 14. 19:34 Posted by TanSanC
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.io.FileOutputStream;

import java.io.FileWriter;

 

import javax.swing.JComboBox;

import javax.swing.RowSorter;

import javax.swing.table.TableModel;

import javax.swing.table.TableRowSorter;

 

/*

 * To change this template, choose Tools | Templates

 * and open the template in the editor.

 */

 

/**

 *

 * @author Suser

 */

public class NewJFrame extends javax.swing.JFrame implements ActionListener {

 

    /**

     * Creates new form NewJFrame

     */

    public NewJFrame() {

       initComponents();

    }

 

    /**

     * This method is called from within the constructor to initialize the form.

     * WARNING: Do NOT modify this code. The content of this method is always

     * regenerated by the Form Editor.

     */

    @SuppressWarnings("unchecked")

    // <editor-fold defaultstate="collapsed"

    // desc="Generated Code">//GEN-BEGIN:initComponents

    private void initComponents() {

 

       jLabel1 = new javax.swing.JLabel();

      String[] monthArray = { "1", "2", "3", "4", "5", "6", "7", "8",

              "9", "10", "11", "12" };

       jComboBox1 = new JComboBox(monthArray);

       jComboBox1.addActionListener(this);

 

       jScrollPane1 = new javax.swing.JScrollPane();

       jTable1 = new javax.swing.JTable();

       jScrollPane2 = new javax.swing.JScrollPane();

       jTable2 = new javax.swing.JTable();

       jLabel2 = new javax.swing.JLabel();

       jButton1 = new javax.swing.JButton();

       jButton2 = new javax.swing.JButton();

       jButton3 = new javax.swing.JButton();

       jButton4 = new javax.swing.JButton();

       jButton5 = new javax.swing.JButton();

       jButton6 = new javax.swing.JButton();

       jButton7 = new javax.swing.JButton();

       jButton8 = new javax.swing.JButton();

       jButton9 = new javax.swing.JButton();

 

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

 

      jLabel1.setFont(new java.awt.Font("바탕", 1, 24)); // NOI18N

       jLabel1.setForeground(new java.awt.Color(255, 153, 153));

      jLabel1.setText("2014 월별 MoneyBook");

 

       int i = 1;

       jTable1.setModel(new javax.swing.table.DefaultTableModel(

              new Object[][] {

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null },

                     { (i++) + "", null, null, null, null, null, null } },

              new String[] { "날짜", "수입 항목", "내용", "금액", "지출 항목", "내용", "금액" }));

       jScrollPane1.setViewportView(jTable1);

       // jTable1.getColumnModel().getColumn(0).setCellEditor(new

       // DatePickerCellEditor());

 

       RowSorter<TableModel> sorter = new TableRowSorter<TableModel>(

              jTable1.getModel());

       jTable1.setRowSorter(sorter);

 

        jTable1.setAutoCreateColumnsFromModel(true);

 

       jTable2.setModel(new javax.swing.table.DefaultTableModel(

             new Object[][] { { null, null, null, null, null } },

              new String[] { "전월 이월금", "수입 합계", "지출 합계", " 합계", "잔액" }));

       jScrollPane2.setViewportView(jTable2);

 

       jButton1.setText("항목검색");

       jButton1.addActionListener(new java.awt.event.ActionListener() {

           public void actionPerformed(java.awt.event.ActionEvent evt) {

              jButton1ActionPerformed(evt);

           }

       });

 

       jButton2.setText("오랜순 정렬");

 

       jButton3.setText("낮은금액순정렬");

 

       jButton4.setText("잔액고침");

 

       jButton5.setText("사용방법");

 

       jButton6.setText("내보내기");

       jButton6.addActionListener(new java.awt.event.ActionListener() {

           public void actionPerformed(java.awt.event.ActionEvent evt) {

              saveFile();

           }

 

       });

 

       jButton7.setText("항목검색");

       jButton7.addActionListener(new java.awt.event.ActionListener() {

           public void actionPerformed(java.awt.event.ActionEvent evt) {

              jButton7ActionPerformed(evt);

           }

       });

 

       jButton8.setText("높은금액순정렬");

       jButton8.addActionListener(new java.awt.event.ActionListener() {

           public void actionPerformed(java.awt.event.ActionEvent evt) {

              jButton8ActionPerformed(evt);

           }

       });

 

       jButton9.setText("최신순 정렬");

 

       javax.swing.GroupLayout layout = new javax.swing.GroupLayout(

              getContentPane());

       getContentPane().setLayout(layout);

       layout.setHorizontalGroup(layout

           .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

              .addGroup(

                      layout.createSequentialGroup()

                            .addContainerGap()

                            .addGroup(

                                    layout.createParallelGroup(

                                           javax.swing.GroupLayout.Alignment.LEADING)

                                           .addGroup(

                                                  layout.createSequentialGroup()

                                                        .addComponent(

                                                               jComboBox1,

                                                                javax.swing.GroupLayout.PREFERRED_SIZE,

                                                               102,

                                                                javax.swing.GroupLayout.PREFERRED_SIZE)

                                                        .addContainerGap(

                                                                javax.swing.GroupLayout.DEFAULT_SIZE,

                                                               Short.MAX_VALUE))

                                           .addGroup(

                                                  layout.createSequentialGroup()

                                                        .addGroup(

                                                               layout.createParallelGroup(

                                                                       javax.swing.GroupLayout.Alignment.TRAILING,

                                                                      false)

                                                                      .addGroup(

                                                                              layout.createSequentialGroup()

                                                                                    .addGap(10,

                                                                                           10,

                                                                                           10)

                                                                                    .addComponent(

                                                                                           jLabel1,

                                                                                            javax.swing.GroupLayout.DEFAULT_SIZE,

                                                                                            javax.swing.GroupLayout.DEFAULT_SIZE,

                                                                                            Short.MAX_VALUE))

                                                                      .addComponent(

                                                                             jScrollPane2,

                                                                              javax.swing.GroupLayout.Alignment.LEADING)

                                                                      .addComponent(

                                                                             jScrollPane1,

                                                                              javax.swing.GroupLayout.Alignment.LEADING,

                                                                              javax.swing.GroupLayout.DEFAULT_SIZE,

                                                                             518,

                                                                             Short.MAX_VALUE))

                                                        .addGroup(

                                                               layout.createParallelGroup(

                                                                       javax.swing.GroupLayout.Alignment.LEADING)

                                                                      .addGroup(

                                                                              layout.createSequentialGroup()

                                                                                    .addGap(65,

                                                                                           65,

                                                                                           65)

                                                                                    .addComponent(

                                                                                            jLabel2))

                                                                      .addGroup(

                                                                               layout.createSequentialGroup()

                                                                                    .addGap(18,

                                                                                           18,

                                                                                           18)

                                                                                    .addGroup(

                                                                                            layout.createParallelGroup(

                                                                                                   javax.swing.GroupLayout.Alignment.LEADING)

                                                                                                   .addComponent(

                                                                                                         jButton5)

                                                                                                   .addComponent(

                                                                                                         jButton2)

                                                                                                   .addComponent(

                                                                                                         jButton1)

                                                                                                   .addComponent(

                                                                                                         jButton3)

                                                                                                   .addComponent(

                                                                                                         jButton4)

                                                                                                   .addComponent(

                                                                                                         jButton7)

                                                                                                   .addComponent(

                                                                                                         jButton8)

                                                                                                   .addComponent(

                                                                                                         jButton9)

                                                                                                   .addComponent(

                                                                                                          jButton6))))

                                                        .addGap(0,

                                                               38,

                                                               Short.MAX_VALUE)))));

       layout.setVerticalGroup(layout

           .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

              .addGroup(

                      layout.createSequentialGroup()

                             .addComponent(jComboBox1)

                            .addGap(4, 4, 4)

                            .addComponent(jLabel1,

                                    javax.swing.GroupLayout.PREFERRED_SIZE,

                                   33,

                                    javax.swing.GroupLayout.PREFERRED_SIZE)

                            .addPreferredGap(

                                javax.swing.LayoutStyle.ComponentPlacement.RELATED,

                                    javax.swing.GroupLayout.DEFAULT_SIZE,

                                    Short.MAX_VALUE)

                            .addGroup(

                                    layout.createParallelGroup(

                                           javax.swing.GroupLayout.Alignment.LEADING,

                                          false)

                                           .addComponent(

                                                  jButton5,

                                                  javax.swing.GroupLayout.DEFAULT_SIZE,

                                                  javax.swing.GroupLayout.DEFAULT_SIZE,

                                                  Short.MAX_VALUE)

                                           .addComponent(

                                                  jScrollPane2,

                                                  javax.swing.GroupLayout.DEFAULT_SIZE,

                                                  59, Short.MAX_VALUE))

                            .addGroup(

                                    layout.createParallelGroup(

                                           javax.swing.GroupLayout.Alignment.LEADING,

                                          false)

                                           .addGroup(

                                                  layout.createSequentialGroup()

                                                        .addGap(42, 42,

                                                               42)

                                                        .addComponent(

                                                               jLabel2)

                                                        .addPreferredGap(

                                                            javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

                                                        .addComponent(

                                                               jButton1)

                                                        .addGap(14, 14,

                                                               14)

                                                        .addComponent(

                                                               jButton2)

                                                        .addGap(14, 14,

                                                               14)

                                                        .addComponent(

                                                               jButton9)

                                                        .addGap(18, 18,

                                                               18)

                                                        .addComponent(

                                                               jButton7)

                                                        .addGap(18, 18,

                                                               18)

                                                        .addComponent(

                                                               jButton8)

                                                        .addGap(18, 18,

                                                               18)

                                                        .addComponent(

                                                               jButton3)

                                                        .addGap(40, 40,

                                                               40)

                                                        .addComponent(

                                                               jButton4)

                                                         .addPreferredGap(

                                                            javax.swing.LayoutStyle.ComponentPlacement.RELATED,

                                                                javax.swing.GroupLayout.DEFAULT_SIZE,

                                                               Short.MAX_VALUE)

                                                        .addComponent(

                                                               jButton6))

                                           .addGroup(

                                                  layout.createSequentialGroup()

                                                        .addGap(18, 18,

                                                               18)

                                                        .addComponent(

                                                               jScrollPane1,

                                                                javax.swing.GroupLayout.PREFERRED_SIZE,

                                                                javax.swing.GroupLayout.DEFAULT_SIZE,

                                                                javax.swing.GroupLayout.PREFERRED_SIZE)))

                            .addContainerGap(

                                    javax.swing.GroupLayout.DEFAULT_SIZE,

                                    Short.MAX_VALUE)));

 

       pack();

    }// </editor-fold>//GEN-END:initComponents

 

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jComboBox1ActionPerformed

       // TODO add your handling code here:

    }// GEN-LAST:event_jComboBox1ActionPerformed

 

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButton1ActionPerformed

       // TODO add your handling code here:

    }// GEN-LAST:event_jButton1ActionPerformed

 

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButton7ActionPerformed

       // TODO add your handling code here:

    }// GEN-LAST:event_jButton7ActionPerformed

 

    private void jButton8ActionPerformed(java.awt.event.ActionEvent evt) {// GEN-FIRST:event_jButton8ActionPerformed

       // TODO add your handling code here:

    }// GEN-LAST:event_jButton8ActionPerformed

 

    /**

     * @param args

     *            the command line arguments

     */

    public static void main(String args[]) {

       /* Set the Nimbus look and feel */

       // <editor-fold defaultstate="collapsed"

       // desc=" Look and feel setting code (optional) ">

       /*

        * If Nimbus (introduced in Java SE 6) is not available, stay with the

        * default look and feel. For details see

        * http://download.oracle.com/javase

        * /tutorial/uiswing/lookandfeel/plaf.html

        */

       try {

           for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager

                  .getInstalledLookAndFeels()) {

             if ("Nimbus".equals(info.getName())) {

              javax.swing.UIManager.setLookAndFeel(info.getClassName());

                  break;

              }

           }

       } catch (ClassNotFoundException ex) {

       java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(

                  java.util.logging.Level.SEVERE, null, ex);

       } catch (InstantiationException ex) {

       java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(

                  java.util.logging.Level.SEVERE, null, ex);

       } catch (IllegalAccessException ex) {

       java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(

                  java.util.logging.Level.SEVERE, null, ex);

       } catch (javax.swing.UnsupportedLookAndFeelException ex) {

       java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(

                  java.util.logging.Level.SEVERE, null, ex);

       }

       // </editor-fold>

 

       /* Create and display the form */

       java.awt.EventQueue.invokeLater(new Runnable() {

           public void run() {

              new NewJFrame().setVisible(true);

           }

       });

    }

 

    // Variables declaration - do not modify//GEN-BEGIN:variables

    private javax.swing.JButton jButton1;

    private javax.swing.JButton jButton2;

    private javax.swing.JButton jButton3;

    private javax.swing.JButton jButton4;

    private javax.swing.JButton jButton5;

    private javax.swing.JButton jButton6;

    private javax.swing.JButton jButton7;

    private javax.swing.JButton jButton8;

    private javax.swing.JButton jButton9;

    private javax.swing.JComboBox jComboBox1;

    private javax.swing.JLabel jLabel1;

    private javax.swing.JLabel jLabel2;

    private javax.swing.JScrollPane jScrollPane1;

    private javax.swing.JScrollPane jScrollPane2;

    private javax.swing.JTable jTable1;

    private javax.swing.JTable jTable2;

    // End of variables declaration//GEN-END:variables

    int thisMonth;

 

    @Override

    public void actionPerformed(ActionEvent arg0) {

       // TODO Auto-generated method stub

       if (arg0.getSource() == jComboBox1) {

           String str = (String) jComboBox1.getSelectedItem();

           jLabel1.setText("2014 " + str + " MoneyBook");

           // "1"

           // "1"

           thisMonth = Integer.parseInt(str.charAt(0) + "");

       }

 

    }

 

    private void saveFile() {

       try {

           FileWriter out = null;

           out = new FileWriter(thisMonth+".txt");

           String str = "";

           for (int i = 0; i < 31; i++) {            

              str += (String) jTable1.getModel().getValueAt(i, 0);

              str += "\t";

              str += (String) jTable1.getModel().getValueAt(i, 1);

              str += "\t";

              str += (String) jTable1.getModel().getValueAt(i, 2);

              str += "\t";

              str += (String) jTable1.getModel().getValueAt(i, 3);

              str += "\t";

              str += (String) jTable1.getModel().getValueAt(i, 4);

              str += "\t";

              str += (String) jTable1.getModel().getValueAt(i, 5);

              str += "\t";

              str += (String) jTable1.getModel().getValueAt(i, 6);

              str += "\n";

           }

           out.write(str);

           out.flush();

           out.close();

       } catch (Exception e) {

 

       }

    }

 

    private void loadFile() {

       // TODO Auto-generated method stub

 

       try {

           FileOutputStream out = null;

           out = new FileOutputStream("data.txt", false);

           // out.write();

       } catch (Exception e) {

 

       }

    }

}

 

'Programming > JAVA,JSP' 카테고리의 다른 글

JAVA 공던지기 게임  (0) 2014.01.16
JAVA 가계부 #2  (0) 2014.01.14
JAVA 쿵쿵따 게임 #2 중복 탐지  (0) 2014.01.09
JAVA 쿵쿵따 게임  (0) 2014.01.09
JAVA 제네릭 컬렉션 실습  (1) 2014.01.09