วันพุธที่ 7 กันยายน พ.ศ. 2554

วันอังคารที่ 6 กันยายน พ.ศ. 2554

ตัวอย่างเกม อัจฉริยะข้ามคืน

คำตอบอยู่ใน file ชื่อ jote.txt

เกมนี้คือเกมทายตัวเลข 4 หลัก ตามคำใบ้
ให้เอาไปทำเป็นตัวอย่างไม่ใช่ให้ลอกนะครับ แต่ถ้าจะลอกไปต้องทำให้ดีกว่านี้ มาก ถึงมากที่สุด
กดโหลดที่นี่

วันจันทร์ที่ 5 กันยายน พ.ศ. 2554

จับการทำงานของ keyboard

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class KeyTest {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Key Listener");
    Container contentPane = frame.getContentPane();
    KeyListener listener = new KeyListener() {
      public void keyPressed(KeyEvent e) {
        dumpInfo("Pressed", e);
      }
      public void keyReleased(KeyEvent e) {
        dumpInfo("Released", e);
      }
      public void keyTyped(KeyEvent e) {
        dumpInfo("Typed", e);
      }
      private void dumpInfo(String s, KeyEvent e) {
        System.out.println(s);
        int code = e.getKeyCode();
        System.out.println("\tCode: " + KeyEvent.getKeyText(code));
        System.out.println("\tChar: " + e.getKeyChar());
        int mods = e.getModifiersEx();
        System.out.println("\tMods: "
            + KeyEvent.getModifiersExText(mods));
        System.out.println("\tLocation: "
            + location(e.getKeyLocation()));
        System.out.println("\tAction? " + e.isActionKey());
      }
      private String location(int location) {
        switch (location) {
        case KeyEvent.KEY_LOCATION_LEFT:
          return "Left";
        case KeyEvent.KEY_LOCATION_RIGHT:
          return "Right";
        case KeyEvent.KEY_LOCATION_NUMPAD:
          return "NumPad";
        case KeyEvent.KEY_LOCATION_STANDARD:
          return "Standard";
        case KeyEvent.KEY_LOCATION_UNKNOWN:
        default:
          return "Unknown";
        }
      }
    };
    JTextField text = new JTextField();
    text.addKeyListener(listener);
    contentPane.add(text, BorderLayout.NORTH);
    frame.pack();
    frame.show();
  }
}

ดูว่า Click Mouse ที่ตำแหน่งไหน

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainClass extends JPanel {
  public MainClass() {
      addMouseListener(new MouseAdapter() {
          public void mousePressed(MouseEvent me) {
            System.out.println(me.getXOnScreen()+","+me.getYOnScreen());
          }
        });
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.getContentPane().add(new MainClass());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   
    frame.setSize(200, 200);
    frame.setVisible(true);
  }
}

ดูว่า click Mouse ไปกี่ที

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainClass extends JPanel {
  public MainClass() {
      addMouseListener(new MouseAdapter() {
          public void mousePressed(MouseEvent me) {
            System.out.println(me.getClickCount());
          }
        });
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.getContentPane().add(new MainClass());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   
    frame.setSize(200, 200);
    frame.setVisible(true);
  }
}

Hight Score from File on Dialog

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Read {
 Read() throws IOException{
  FileReader read = new FileReader("score.txt");
  BufferedReader file = new BufferedReader(read);
  String readFile = file.readLine();
  String real = "";
  while (readFile!=null) {
   real = real+readFile;
   readFile = file.readLine();
  
  
  
  }
  String hightscore[] = real.split(",");
  String name[] = new String[hightscore.length];
  String score[] = new String[hightscore.length];
  String scoreCheck[] = new String[hightscore.length];
  for(int i =0;i<hightscore.length;i++){
   String nameSp[] = hightscore[i].split(" ");
    name[i] = nameSp[0];
    score[i] = nameSp[1];
   
  
  }
  scoreCheck = score;
  Arrays.sort(score);
  String showHighScore[] =new String[score.length];
  String showOnDilog ="";
  for(int i=0; i<score.length;i++){
  
   for(int j=0;j<scoreCheck.length;j++){
   
    if(score[i].equals(scoreCheck[j])){
     showHighScore[i] = name[j]+"                   "+score[i];
    
    
    }
   }
  }
 
  for(int i=showHighScore.length-1;i>=0;i--){
   showOnDilog = showOnDilog+showHighScore[i]+"\n";
  }
 
   JOptionPane.showMessageDialog(null,"              Hight Score\n"+showOnDilog ,"High Score",JOptionPane.INFORMATION_MESSAGE );
 }
 public static void main(String[] args) throws IOException {
  new Read();
 }
}

JAVA Play Audio Sound (.wav)

import java.io.File;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

public class audio extends Thread {

    private String filename;

    private Position curPosition;

    private final int EXTERNAL_BUFFER_SIZE = 524288; // 128Kb

    enum Position {
        LEFT, RIGHT, NORMAL
    };

    public audio(String wavfile) {
        filename = wavfile;
        curPosition = Position.NORMAL;
    }

    public audio(String wavfile, Position p) {
        filename = wavfile;
        curPosition = p;
    }

    public void run() {

        File soundFile = new File(filename);
        if (!soundFile.exists()) {
            System.err.println("Wave file not found: " + filename);
            return;
        }

        AudioInputStream audioInputStream = null;
        try {
            audioInputStream = AudioSystem.getAudioInputStream(soundFile);
        } catch (UnsupportedAudioFileException e1) {
            e1.printStackTrace();
            return;
        } catch (IOException e1) {
            e1.printStackTrace();
            return;
        }

        AudioFormat format = audioInputStream.getFormat();
        SourceDataLine auline = null;
        DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

        try {
            auline = (SourceDataLine) AudioSystem.getLine(info);
            auline.open(format);
        } catch (LineUnavailableException e) {
            e.printStackTrace();
            return;
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        if (auline.isControlSupported(FloatControl.Type.PAN)) {
            FloatControl pan = (FloatControl) auline
                    .getControl(FloatControl.Type.PAN);
            if (curPosition == Position.RIGHT)
                pan.setValue(1.0f);
            else if (curPosition == Position.LEFT)
                pan.setValue(-1.0f);
        }

        auline.start();
        int nBytesRead = 0;
        byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];

        try {
            while (nBytesRead != -1) {
                nBytesRead = audioInputStream.read(abData, 0, abData.length);
                if (nBytesRead >= 0)
                    auline.write(abData, 0, nBytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return;
        } finally {
            auline.drain();
            auline.close();
        }

    }
    public static void main(String[] args) {
  new audio("tada.wav").start();
 }
}

ส่งค่าจาก Textfield ไป หน้าอื่น


import javax.swing.JFrame;
import javax.swing.JLabel;
public class P2 extends JFrame{

 P2(String Gebtx1,String GebTx2,int sum){
 
  JLabel lb1 = new JLabel(Gebtx1);
  JLabel lb2 = new JLabel(GebTx2);
  JLabel lb3 = new JLabel(""+sum);
 
 
 
  setLayout(null);
  setBounds(50,100,300,500);
  setVisible(true);
 
 
  add(lb1);
  add(lb2);
  add(lb3);
 
  lb1.setBounds(10, 10, 100, 25);
  lb2.setBounds(10, 40, 100, 25);
  lb3.setBounds(10, 70, 100, 25);
 }
}

/////////////Class  ที่สอง


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class Send extends JFrame implements ActionListener{
 JTextField tx1 = new JTextField(10);
 JTextField tx2 = new JTextField(10);
 JButton click = new JButton("pk");
 String GebTx1 ="";
 String GebTx2 ="";
 Send(){
  setLayout(null);
  setBounds(50,100,300,500);
  setVisible(true);
  add(tx1);
  add(tx2);
  add(click);
 
  tx1.setBounds(10, 10, 100, 25);
  tx2.setBounds(10, 40, 100, 25);
  click.setBounds(10, 70, 100, 25);
 
  click.addActionListener(this);
 }
 public static void main(String[] args) {
  new Send();
 }
 @Override
 public void actionPerformed(ActionEvent e) {
  if(e.getSource()==click){
   GebTx1 = tx1.getText();
   GebTx2 = tx2.getText();
   int num1 = Integer.parseInt(GebTx1);
   int num2 = Integer.parseInt(GebTx2);
  
   JOptionPane.showMessageDialog(null, num1+num2)
;   new P2(GebTx1,GebTx2,num1+num2);
  }
 
 }
}