當前位置:首頁 » 編程語言 » java案例源碼

java案例源碼

發布時間: 2023-05-22 05:29:09

Ⅰ 什麼是java源代碼 怎麼查看

不知道你說的是瀏覽器的還是什麼的,
如果是瀏覽器的那麼簡單找到工具-查看源代碼,你就能看見代碼了,
還有一個就是被編譯成class文件的java用反編譯工具可以看到源代碼,
如果以上都不是你想要的答案,那麼你所說的代碼就是程序員寫好的代碼文件

Ⅱ 高分求兩個簡單的JAVA設計源代碼

上面 wukun12同運譽學寫的不錯,但我想還不能運行,並且還不太完善。我給個能運行的:(注意:文件名為:Test.java)

//要實現對象間的比較,就必須實現Comparable介面,它裡面有個compareTo方法
//Comparable最好使用泛型,這樣,無論是速度還是代碼量都會鬧悄鄭減少
@SuppressWarnings("unchecked")
class Student implements Comparable<Student>{

private String studentNo; //學號
private String studentName; //姓名
private double englishScore; //英語成績
private double computerScore; //計算機成績
private double mathScore; //數學成績
private double totalScore; //總成績

//空構造函數
public Student() {}

//構造函數
public Student(String studentNo,String studentName,double englishSocre,double computerScore,double mathScore) {
this.studentNo = studentNo;
this.studentName = studentName;
this.englishScore = englishSocre;
this.computerScore = computerScore;
this.mathScore = mathScore;
}

//計算總成績
public double sum() {

this.totalScore = englishScore+computerScore+mathScore;
return totalScore;
}

//計算評測成績
public double testScore() {

return sum()/3;
}

//實現compareTO方法
@Override
public int compareTo(Student student) {
double studentTotal = student.getTotalScore();
return totalScore==studentTotal?0:(totalScore>studentTotal?1:-1);
}

//重寫toString方法
public String toString(){
return "學號:"+this.getStudentNo()+" 姓名:"+this.getStudentName()+" 英語成績:"+this.getEnglishScore()+" 數學成績:"+this.getMathScore()+" 計算機成績:"+this.getComputerScore()+" 總成績:"+this.getTotalScore();
}

//重寫equals方法
public boolean equals(Object obj) {
if(obj == null){
return false;
}
if(!(obj instanceof Student)){
return false;
}
Student student = (Student)obj;
if(this.studentNo.equals(student.getStudentName())) { //照現實來說,比較是不是同一個學生,應該只是看他的學號是不是相同
return true;
} else {
return false;
}

}

/*以下為get和set方法,我個人認為,totalScore的set的方法沒必要要,因為它是由其它液頌成績計算出來的
在set方法中,沒設置一次值,調用一次sum方法,即重新計算總成績
*/
public String getStudentNo() {
return studentNo;
}
public void setStudentNo(String studentNo) {
this.studentNo = studentNo;
sum();
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
sum();
}
public double getEnglishScore() {
return englishScore;
}
public void setEnglishScore(double englishScore) {
this.englishScore = englishScore;
sum();
}
public double getComputerScore() {
return computerScore;
}
public void setComputerScore(double computerScore) {
this.computerScore = computerScore;
sum();
}
public double getMathScore() {
return mathScore;
}
public void setMathScore(double mathScore) {
this.mathScore = mathScore;
sum();
}
public double getTotalScore() {
return totalScore;
}

}

//Student子類學習委員類的實現
class StudentXW extends Student {

//重寫父類Student的testScore()方法
@Override
public double testScore() {
return sum()/3+3;
}

public StudentXW() {}

//StudentXW的構造函數
public StudentXW(String studentNo,String studentName,double englishSocre,double computerScore,double mathScore) {
super(studentNo,studentName,englishSocre,computerScore,mathScore);
}
}

//Student子類班長類的實現
class StudentBZ extends Student {

//重寫父類Student的testScore()方法
@Override
public double testScore() {
return sum()/3+5;
}

public StudentBZ() {}

//StudentXW的構造函數
public StudentBZ(String studentNo,String studentName,double englishSocre,double computerScore,double mathScore) {
super(studentNo,studentName,englishSocre,computerScore,mathScore);
}
}

//測試類
public class Test {

public static void main(String[] args) {

//生成若干個student類、StudentXW類、StudentBZ類
Student student1 = new Student("s001","張三",70.5,50,88.5);
Student student2 = new Student("s002","李四",88,65,88.5);
Student student3 = new Student("s003","王五",67,77,90);
StudentXW student4 = new StudentXW("s004","李六",99,88,99.5);
StudentBZ student5 = new StudentBZ("s005","朱漆",56,65.6,43.5);

Student[] students = {student1,student2,student3,student4,student5};

for(int i = 0 ; i<students.length; i++){
double avgScore = students[i].testScore();
System.out.println(students[i].getStudentName()+"學生的評測成績為:"+ avgScore+"分");
}

}
}
運行結果為:
張三學生的評測成績為:69.66666666666667分
李四學生的評測成績為:80.5分
王五學生的評測成績為:78.0分
李六學生的評測成績為:98.5分
朱漆學生的評測成績為:60.03333333333333分

Ⅲ java swing左邊樹圖,當點擊任意節點時,右邊顯示顯示數據, 求一個簡單的源碼例子

importjava.awt.BorderLayout;
importjava.awt.Container;
importjava.awt.Dimension;

importjavax.swing.JFrame;
importjavax.swing.JLabel;
importjavax.swing.JPanel;
importjavax.swing.JTree;
importjavax.swing.event.TreeSelectionEvent;
importjavax.swing.event.TreeSelectionListener;
importjavax.swing.tree.DefaultMutableTreeNode;

{
privateJPanelp;

publicTestSwingTree(Stringtitle){
super(title);
}
publicvoidinit(){
Containerc=this.getContentPane();

DefaultMutableTreeNoderoot=newDefaultMutableTreeNode("root");
DefaultMutableTreeNodechild1=newDefaultMutableTreeNode("child1");
DefaultMutableTreeNodechild11=newDefaultMutableTreeNode("child11");
DefaultMutableTreeNodechild12=newDefaultMutableTreeNode("child12");
DefaultMutableTreeNodechild2=newDefaultMutableTreeNode("child2");
DefaultMutableTreeNodechild3=newDefaultMutableTreeNode("child3");
DefaultMutableTreeNodechild31=newDefaultMutableTreeNode("child31");
root.add(child1);
root.add(child2);
root.add(child3);
child1.add(child11);
child1.add(child12);
child3.add(child31);
JTreetree=newJTree(root);
tree.setPreferredSize(newDimension(120,400));
tree.addTreeSelectionListener(newTreeSelectionListener(){

publicvoidvalueChanged(TreeSelectionEvente){
p.removeAll();
JLabell=newJLabel(e.getPath().toString());
l.setBounds(5,190,170,20);
p.add(l);
p.repaint();
}
});
c.add(tree,BorderLayout.WEST);

p=newJPanel();
p.setLayout(null);
p.setPreferredSize(newDimension(180,400));
c.add(p,BorderLayout.CENTER);
this.setLocation(400,300);
this.setSize(300,400);
this.setResizable(false);
this.setVisible(true);
this.setDefaultCloseOperation(this.DISPOSE_ON_CLOSE);
}
publicstaticvoidmain(String[]args){
newTestSwingTree("TestSwingJtree").init();
}
}

Ⅳ 用JAVA 編程的源代碼

直接定義兩個介面學生介面裡面定義一個學費的變數,老師介面裡面定義一個工資變數,
eclipse裡面可以自動幫你添加相關變數的getterhe
setter方法的。

Ⅳ 求幾個JAVA小項目源代碼,供自己學習參考

package com.test01;
import java.util.Scanner;
public class oop5 { public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// int x = 9;
// int y = 1;
int x = sc.nextInt();
int y = sc.nextInt();
int z;
z = add(x, y);
System.out.println("x的值為:" + x);
System.out.println("y的值為:" + y);
System.out.println("二者之和為:" + z);
}

/** 四種小演算法 */
// 加法運算
public static int add(int a, int b) {
int c;
c = a + b;
return c;
}

// 減法運算
public static int jian(int d, int v) {
int m;
m = d - v;
return m;
}

// 乘積運算
public static int addAdd(int q, int w) {
int e;
e = q * w;
return e;
}

// 除法運算
public static int chu(int p, int k) {
int f;
f = p / k;
return f;
}
}

Ⅵ 求編寫一個超級簡單的Java的程序源代碼

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class Login {

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

class LoginFrm extends JFrame implements ActionListener{
JLabel nameLabel=new JLabel("用戶名:");
JLabel pwdLabel=new JLabel("密碼:");
JTextField name=new JTextField(10);
JPasswordField password=new JPasswordField(10);
JButton butnSure=new JButton("確定");
JButton butnCancel=new JButton("取消");
public LoginFrm() {
super("登陸");
setBounds(500, 200, 280, 220);
setVisible(true);
setLayout(null);
nameLabel.setBounds(45, 20, 100, 25);
add(nameLabel);
add(name);
name.setBounds(105, 20, 110, 25);
add(pwdLabel);
pwdLabel.setBounds(45, 60, 100, 25);
add(password);
password.setBounds(105, 60, 110, 25);
add(butnSure);
butnSure.setBounds(45, 100, 80, 25);
add(butnCancel);
butnCancel.setBounds(135, 100, 80, 25);
butnSure.addActionListener(this);
butnCancel.addActionListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
validate();//刷新橡猜
}

public void actionPerformed(ActionEvent e) {
if (e.getSource() ==butnSure){
System.out.println("用戶名:"+name.getText());
System.out.println("密碼:"+name.getText());
if("admin".equals(name.getText().trim())&&"123".equals(password.getText().trim())){
this.dispose();
new MainFrm("碼迅用戶界面",name.getText().trim(),password.getText().trim());
}else {
JOptionPane.showMessageDialog(this, "用遲如此戶不存在");
}
}else if(e.getSource()==butnCancel){
System.exit(1);
}
}

class MainFrm extends JFrame{
private JLabel info;

public MainFrm(String s,String name,String password) {
super(s);
setBounds(400, 200, 500, 400);
setLayout(new FlowLayout());
info=new JLabel("登陸成功,用戶名:"+name+",密碼:"+password);
add(info);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
validate();
}
}
}

Ⅶ 求java小游戲源代碼

[最佳答案] 連連看java源代碼 import javax.swing.*; import java.awt.*; import java.awt.event.*; pu... int x0=0,y0=0,x=0,y=0,fristMsg=0,secondMsg=0,validateLV; //游戲按鈕的位...

Ⅷ Java記事本源代碼

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.filechooser.FileFilter;

public class Demo extends JFrame {

private static final long serialVersionUID = 1L; //Eclipse自動生成序列號

String name = "無標題";

JPanel menuPanel = new JPanel();

JTextArea text = new TextAreaMenu(); //文本編輯區
JScrollPane jsp = new JScrollPane(text); //可滾動編輯區
JMenuBar mnbMain = new JMenuBar();

JMenu mnServer = new JMenu("文件(F)");
JMenu mnEdit = new JMenu("編輯(E)"槐頌雀);

JMenuItem[] mniServers = new JMenuItem[]{
new JMenuItem("新建(N)"),
new JMenuItem("鉛早保存(S)"),
new JMenuItem("打開(O)"),
new JMenuItem("退出(X)"),
};
{
menuPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
mnbMain.add(mnServer);
menuPanel.add(mnbMain);
mnbMain.setBounds(5, 0, 50, 30);
for (int i = 0; i <櫻此 mniServers.length; i++) {
mnServer.add(mniServers[i]);
}
mniServers[0].addActionListener(new ActionListener() { //定義"新建"組件操作

@Override
public void actionPerformed(ActionEvent arg0) {
new Demo(getLocation().x+15,getLocation().y+5);
}
});

mniServers[1].addActionListener(new ActionListener() { //定義"保存"組件操作

@Override
public void actionPerformed(ActionEvent arg0) {
chooseToSave();
}

});
mniServers[2].addActionListener(new ActionListener() { //定義"打開"組件操作

@Override
public void actionPerformed(ActionEvent arg0) {
chooseToOpen();
}
});
mniServers[3].addActionListener(new ActionListener() { //定義"退出"組件操作

@Override
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});

text.addFocusListener(new FocusListener() {

@Override
public void focusLost(FocusEvent e) {
// TODO Auto-generated method stub

}

@Override
public void focusGained(FocusEvent e) {

}
});

}
public Demo(int x,int y) {
this.setTitle( name +" - 記事本");
this.setBounds(x, y, 600, 400);
this.setLayout(new BorderLayout());
this.add(menuPanel, BorderLayout.NORTH);
this.add(jsp);
jsp.setBounds(5, 30, getWidth()-10, getHeight()-50);

this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.setVisible(true);
}

public Demo() {
this(200,200);
}

protected void chooseToSave() {

File file = chooseFile();
if(null==file)return;
if(file.exists()){
int cho = JOptionPane.showConfirmDialog(this, "文件已存在,是否覆蓋?");
System.out.println(cho);
if(cho==JOptionPane.OK_OPTION)save(file);
else return;
}
else save(file);

}

private void save(File file) {
name = file.getName();
write(text.getText(),file.getPath());
this.setTitle( name +" - 記事本");
}

protected void chooseToOpen() {
File file = chooseFile();
if(null==file||!file.exists())return;
name = file.getName();
Demo.this.setTitle( name +" - 記事本");
read(text,file);
}
/*********************************************MAIN**************************************************/
public static void main(String[] args) {
new Demo();
}

private File chooseFile(){

JFileChooser chooser = new JFileChooser(); //構建文件選擇器
chooser.setFileFilter(new FileFilter() {
@Override
public String getDescription() {
return "文本文件";
}

@Override
public boolean accept(File f) {
String name = f.getName().toLowerCase();

return f.isDirectory() || name.endsWith(".txt")
||name.endsWith(".c") || name.endsWith(".java")
||name.endsWith(".cpp"); //可識別文件
}
});
int result = chooser.showDialog(null, "確定");
if (result==JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
System.out.println(file.getAbsolutePath());
} else {
System.out.println("未選擇文件");
}
return chooser.getSelectedFile();
}

public static void read(JTextArea text,File file){ //定義讀取文件操作
FileReader fr;
try {
fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String string = null;
while((string = br.readLine()) != null){
text.append(string+"\n");
}
br.close();
fr.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public static void write(String txt,String fileName){
FileWriter fw;
try {
fw = new FileWriter(fileName);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(txt);
bw.flush();
bw.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}

class TextAreaMenu extends JTextArea implements MouseListener {

private static final long serialVersionUID = -2308615404205560110L;

private JPopupMenu pop = null; // 彈出菜單

private JMenuItem selectAll = null, = null, paste = null, cut = null, cancel=null; // 功能菜單

public TextAreaMenu() {
super();
init();
}

private void init() {
this.addMouseListener(this);
this.setSelectedTextColor(Color.red);
pop = new JPopupMenu();
pop.add(selectAll = new JMenuItem("全選"));
pop.add( = new JMenuItem("復制"));
pop.add(paste = new JMenuItem("粘貼"));
pop.add(cut = new JMenuItem("剪切"));
pop.add(cancel = new JMenuItem("撤銷"));
selectAll.setAccelerator(KeyStroke.getKeyStroke('A', InputEvent.CTRL_MASK));
.setAccelerator(KeyStroke.getKeyStroke('C', InputEvent.CTRL_MASK));
paste.setAccelerator(KeyStroke.getKeyStroke('V', InputEvent.CTRL_MASK));
cut.setAccelerator(KeyStroke.getKeyStroke('X', InputEvent.CTRL_MASK));
cancel.setAccelerator(KeyStroke.getKeyStroke('Z', InputEvent.CTRL_MASK));
.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
action(e);
}
});
paste.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
action(e);
}
});
cut.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
action(e);
}
});
this.add(pop);
}

/**
* 菜單動作
* @param e
*/
public void action(ActionEvent e) {
String str = e.getActionCommand();
if (str.equals(selectAll.getText())) { // 全選
this.selectAll();
}
else if (str.equals(.getText())) { // 復制
this.();
} else if (str.equals(paste.getText())) { // 粘貼
this.paste();
} else if (str.equals(cut.getText())) { // 剪切
this.cut();
}
else if (str.equals(cancel.getText())) { //撤銷
this.cut();
}
}

public JPopupMenu getPop() {
return pop;
}

public void setPop(JPopupMenu pop) {
this.pop = pop;
}

/**
* 剪切板中是否有文本數據可供粘貼
*
* @return true為有文本數據
*/
public boolean isClipboardString() {
boolean b = false;
Clipboard clipboard = this.getToolkit().getSystemClipboard();
Transferable content = clipboard.getContents(this);
try {
if (content.getTransferData(DataFlavor.stringFlavor) instanceof String) {
b = true;
}
} catch (Exception e) {
}
return b;
}

/**
* 文本組件中是否具備復制的條件
*
* @return true為具備
*/
public boolean isCanCopy() {
boolean b = false;
int start = this.getSelectionStart();
int end = this.getSelectionEnd();
if (start != end)
b = true;
return b;
}

public void mouseClicked(MouseEvent e) {
}

public void mouseEntered(MouseEvent e) {
}

public void mouseExited(MouseEvent e) {
}

public void mousePressed(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON3) {
.setEnabled(isCanCopy());
paste.setEnabled(isClipboardString());
cut.setEnabled(isCanCopy());
pop.show(this, e.getX(), e.getY());
}
}

public void mouseReleased(MouseEvent e) {
}

}

Ⅸ 求用JAVA編寫俄羅斯方塊游戲的源代碼

俄羅斯方塊——java源代碼提供 import java.awt.*; import java.awt.event.*; //俄羅斯方塊類 public class ERS_Block extends Frame{ public static boolean isPlay=false; public static int level=1,score=0; public static TextField scoreField,levelField; public static MyTimer timer; GameCanvas gameScr; public static void main(String[] argus){ ERS_Block ers = new ERS_Block("俄羅斯方塊游戲 V1.0 Author:Vincent"); WindowListener win_listener = new WinListener(); ers.addWindowListener(win_listener); } //俄羅斯方塊類的構造方法 ERS_Block(String title){ super(title); setSize(600,480); setLayout(new GridLayout(1,2)); gameScr = new GameCanvas(); gameScr.addKeyListener(gameScr); timer = new MyTimer(gameScr); timer.setDaemon(true); timer.start(); timer.suspend(); add(gameScr); Panel rightScr = new Panel(); rightScr.setLayout(new GridLayout(2,1,0,30)); rightScr.setSize(120,500); add(rightScr); //右邊信息窗體的布局 MyPanel infoScr = new MyPanel(); infoScr.setLayout(new GridLayout(4,1,0,5)); infoScr.setSize(120,300); rightScr.add(infoScr); //定義標簽和初始值 Label scorep = new Label("分數:",Label.LEFT); Label levelp = new Label("級數:",Label.LEFT); scoreField = new TextField(8); levelField = new TextField(8); scoreField.setEditable(false); levelField.setEditable(false); infoScr.add(scorep); infoScr.add(scoreField); infoScr.add(levelp); infoScr.add(levelField); scorep.setSize(new Dimension(20,60)); scoreField.setSize(new Dimension(20,60)); levelp.setSize(new Dimension(20,60)); levelField.setSize(new Dimension(20,60)); scoreField.setText("0"); levelField.setText("1"); //右邊控制按鈕窗體的布局 MyPanel controlScr = new MyPanel(); controlScr.setLayout(new GridLayout(5,1,0,5)); rightScr.add(controlScr); //定義按鈕play Button play_b = new Button("開始游戲"); play_b.setSize(new Dimension(50,200)); play_b.addActionListener(new Command(Command.button_play,gameScr)); //定義按鈕Level UP Button level_up_b = new Button("提高級數"); level_up_b.setSize(new Dimension(50,200)); level_up_b.addActionListener(new Command(Command.button_levelup,gameScr)); //定義按鈕Level Down Button level_down_b =new Button("降低級數"); level_down_b.setSize(new Dimension(50,200)); level_down_b.addActionListener(new Command(Command.button_leveldown,gameScr)); //定義按鈕Level Pause Button pause_b =new Button("游戲暫停"); pause_b.setSize(new Dimension(50,200)); pause_b.addActionListener(new Command(Command.button_pause,gameScr)); //定義按鈕Quit Button quit_b = new Button("退出遊戲"); quit_b.setSize(new Dimension(50,200)); quit_b.addActionListener(new Command(Command.button_quit,gameScr)); controlScr.add(play_b); controlScr.add(level_up_b); controlScr.add(level_down_b); controlScr.add(pause_b); controlScr.add(quit_b); setVisible(true); gameScr.requestFocus(); } } //重寫MyPanel類,使Panel的四周留空間 class MyPanel extends Panel{ public Insets getInsets(){ return new Insets(30,50,30,50); } } //游戲畫布類 class GameCanvas extends Canvas implements KeyListener{ final int unitSize = 30; //小方塊邊長 int rowNum; //正方格的行數 int columnNum; //正方格的列數 int maxAllowRowNum; //允許有多少行未削 int blockInitRow; //新出現塊的起始行坐標 int blockInitCol; //新出現塊的起始列坐標 int [][] scrArr; //屏幕數組 Block b; //對方快的引用 //畫布類的構造方法 GameCanvas(){ rowNum = 15; columnNum = 10; maxAllowRowNum = rowNum - 2; b = new Block(this); blockInitRow = rowNum - 1; blockInitCol = columnNum/2 - 2; scrArr = new int [32][32]; } //初始化屏幕,並將屏幕數組清零的方法 void initScr(){ for(int i=0;i<rowNum;i++) for (int j=0; j<columnNum;j++) scrArr[j]=0; b.reset(); repaint(); } //重新刷新畫布方法 public void paint(Graphics g){ for(int i = 0; i < rowNum; i++) for(int j = 0; j < columnNum; j++) drawUnit(i,j,scrArr[j]); } //畫方塊的方法 public void drawUnit(int row,int col,int type){ scrArr[row][col] = type; Graphics g = getGraphics(); tch(type){ //表示畫方快的方法 case 0: g.setColor(Color.black);break; //以背景為顏色畫 case 1: g.setColor(Color.blue);break; //畫正在下落的方塊 case 2: g.setColor(Color.magenta);break; //畫已經落下的方法 } g.fill3DRect(col*unitSize,getSize().height-(row+1)*unitSize,unitSize,unitSize,true); g.dispose(); } public Block getBlock(){ return b; //返回block實例的引用 } //返回屏幕數組中(row,col)位置的屬性值 public int getScrArrXY(int row,int col){ if (row < 0 || row >= rowNum || col < 0 || col >= columnNum) return(-1); else return(scrArr[row][col]); } //返回新塊的初始行坐標方法 public int getInitRow(){ return(blockInitRow); //返回新塊的初始行坐標 } //返回新塊的初始列坐標方法 public int getInitCol(){ return(blockInitCol); //返回新塊的初始列坐標 } //滿行刪除方法 void deleteFullLine(){ int full_line_num = 0; int k = 0; for (int i=0;i<rowNum;i++){ boolean isfull = true; L1:for(int j=0;j<columnNum;j++) if(scrArr[j] == 0){ k++; isfull = false; break L1; } if(isfull) full_line_num++; if(k!=0 && k-1!=i && !isfull) for(int j = 0; j < columnNum; j++){ if (scrArr[j] == 0) drawUnit(k-1,j,0); else drawUnit(k-1,j,2); scrArr[k-1][j] = scrArr[j]; } } for(int i = k-1 ;i < rowNum; i++){ for(int j = 0; j < columnNum; j++){ drawUnit(i,j,0); scrArr[j]=0; } } ERS_Block.score += full_line_num; ERS_Block.scoreField.setText(""+ERS_Block.score); } //判斷游戲是否結束方法 boolean isGameEnd(){ for (int col = 0 ; col <columnNum; col ++){ if(scrArr[maxAllowRowNum][col] !=0) return true; } return false; } public void keyTyped(KeyEvent e){ } public void keyReleased(KeyEvent e){ } //處理鍵盤輸入的方法 public void keyPressed(KeyEvent e){ if(!ERS_Block.isPlay) return; tch(e.getKeyCode()){ case KeyEvent.VK_DOWN:b.fallDown();break; case KeyEvent.VK_LEFT:b.leftMove();break; case KeyEvent.VK_RIGHT:b.rightMove();break; case KeyEvent.VK_SPACE:b.leftTurn();break; } } } //處理控制類 class Command implements ActionListener{ static final int button_play = 1; //給按鈕分配編號 static final int button_levelup = 2; static final int button_leveldown = 3; static final int button_quit = 4; static final int button_pause = 5; static boolean pause_resume = true; int curButton; //當前按鈕 GameCanvas scr; //控制按鈕類的構造方法 Command(int button,GameCanvas scr){ curButton = button; this.scr=scr; } //按鈕執行方法 public void actionPerformed (ActionEvent e){ tch(curButton){ case button_play:if(!ERS_Block.isPlay){ scr.initScr(); ERS_Block.isPlay = true; ERS_Block.score = 0; ERS_Block.scoreField.setText("0"); ERS_Block.timer.resume(); } scr.requestFocus(); break; case button_levelup:if(ERS_Block.level < 10){ ERS_Block.level++; ERS_Block.levelField.setText(""+ERS_Block.level); ERS_Block.score = 0; ERS_Block.scoreField.setText(""+ERS_Block.score); } scr.requestFocus(); break; case button_leveldown:if(ERS_Block.level > 1){ ERS_Block.level--; ERS_Block.levelField.setText(""+ERS_Block.level); ERS_Block.score = 0; ERS_Block.scoreField.setText(""+ERS_Block.score); } scr.requestFocus(); break; case button_pause:if(pause_resume){ ERS_Block.timer.suspend(); pause_resume = false; }else{ ERS_Block.timer.resume(); pause_resume = true; } scr.requestFocus(); break; case button_quit:System.exit(0); } } } //方塊類 class Block { static int[][] pattern = { {0x0f00,0x4444,0x0f00,0x4444},//用十六進至表示,本行表示長條四種狀態 {0x04e0,0x0464,0x00e4,0x04c4}, {0x4620,0x6c00,0x4620,0x6c00}, {0x2640,0xc600,0x2640,0xc600}, {0x6220,0x1700,0x2230,0x0740}, {0x6440,0x0e20,0x44c0,0x8e00}, {0x0660,0x0660,0x0660,0x0660} }; int blockType; //塊的模式號(0-6) int turnState; //塊的翻轉狀態(0-3) int blockState; //快的下落狀態 int row,col; //塊在畫布上的坐標 GameCanvas scr; //塊類的構造方法 Block(GameCanvas scr){ this.scr = scr; blockType = (int)(Math.random() * 1000)%7; turnState = (int)(Math.random() * 1000)%4; blockState = 1; row = scr.getInitRow(); col = scr.getInitCol(); } //重新初始化塊,並顯示新塊 public void reset(){ blockType = (int)(Math.random() * 1000)%7; turnState = (int)(Math.random() * 1000)%4; blockState = 1; row = scr.getInitRow(); col = scr.getInitCol(); dispBlock(1); } //實現「塊」翻轉的方法 public void leftTurn(){ if(assertValid(blockType,(turnState + 1)%4,row,col)){ dispBlock(0); turnState = (turnState + 1)%4; dispBlock(1); } } //實現「塊」的左移的方法 public void leftMove(){ if(assertValid(blockType,turnState,row,col-1)){ dispBlock(0); col--; dispBlock(1); } } //實現塊的右移 public void rightMove(){ if(assertValid(blockType,turnState,row,col+1)){ dispBlock(0); col++; dispBlock(1); } } //實現塊落下的操作的方法 public boolean fallDown(){ if(blockState == 2) return(false); if(assertValid(blockType,turnState,row-1,col)){ dispBlock(0); row--; dispBlock(1); return(true); }else{ blockState = 2; dispBlock(2); return(false); } } //判斷是否正確的方法 boolean assertValid(int t,int s,int row,int col){ int k = 0x8000; for(int i = 0; i < 4; i++){ for(int j = 0; j < 4; j++){ if((int)(pattern[t][s]&k) != 0){ int temp = scr.getScrArrXY(row-i,col+j); if (temp<0||temp==2) return false; } k = k >> 1; } } return true; } //同步顯示的方法 public synchronized void dispBlock(int s){ int k = 0x8000; for (int i = 0; i < 4; i++){ for(int j = 0; j < 4; j++){ if(((int)pattern[blockType][turnState]&k) != 0){ scr.drawUnit(row-i,col+j,s); } k=k>>1; } } } } //定時線程 class MyTimer extends Thread{ GameCanvas scr; public MyTimer(GameCanvas scr){ this.scr = scr; } public void run(){ while(true){ try{ sleep((10-ERS_Block.level + 1)*100); } catch(InterruptedException e){} if(!scr.getBlock().fallDown()){ scr.deleteFullLine(); if(scr.isGameEnd()){ ERS_Block.isPlay = false; suspend(); }else scr.getBlock().reset(); } } } } class WinListener extends WindowAdapter{ public void windowClosing (WindowEvent l){ System.exit(0); } } 22

Ⅹ java語言寫一個文本編輯器的源代碼

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import java.util.*; //Date needed
import java.io.PrintWriter;
public class NotePad extends JFrame
{
JTextArea jta;
class newl implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
jta.setText("");
}
}

class openl implements ActionListener
{ public void actionPerformed(ActionEvent e)
{
JFileChooser jf=new JFileChooser();
jf.showOpenDialog(NotePad.this);

}

}
//保存文件的監聽
class savel implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JFileChooser jf = new JFileChooser();
jf.showSaveDialog(NotePad.this);

}
}
//列印的監聽 ?
class printl implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// PrintWriter p = new PrintWriter(NotePad.this);
}
}
//退出記事本的監聽
class exitl implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);//退出
}
}

//拷貝的監聽
class l implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
jta.();
}
}

//粘貼的監聽
class pastel implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
jta.paste();
}
}
//剪切的監聽
class cutl implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
jta.cut();
}
}
//查找的監聽

//添加日期的監聽
class datel implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
Date d=new Date();
jta.append(d.toString());
}
}

//構造函數
public NotePad()
{
jta=new JTextArea("",24,40);
JScrollPane jsp=new JScrollPane(jta);
JMenuBar jmb=new JMenuBar();
JMenu mFile=new JMenu("File");
JMenu mEdit=new JMenu("Edit");

JMenuItem mNew=new JMenuItem("New",KeyEvent.VK_N);
mNew.addActionListener(new newl());
mFile.add(mNew);

JMenuItem mOpen=new JMenuItem("Open",KeyEvent.VK_O);
mOpen.addActionListener(new openl());
mFile.add(mOpen);

JMenuItem mSave=new JMenuItem("Save");
mSave.addActionListener(new savel());
mFile.add(mSave);

mFile.addSeparator(); //添加分割線

JMenuItem mPrint = new JMenuItem("Print");
mPrint.addActionListener(new printl());
mFile.add(mPrint);

mFile.addSeparator(); //添加分割線

JMenuItem mExit=new JMenuItem("Exit");
mExit.addActionListener(new exitl());
mFile.add(mExit);
mFile.setMnemonic(KeyEvent.VK_F);

//編輯菜單的子菜單的處理
JMenuItem jmi;
jmi=new JMenuItem("Copy");
jmi.addActionListener(new l());
mEdit.add(jmi);

jmi=new JMenuItem("Cut");
jmi.addActionListener(new cutl());
mEdit.add(jmi);

jmi=new JMenuItem("Paste");
jmi.addActionListener(new pastel());
mEdit.add(jmi);

mEdit.addSeparator(); //添加分割線

jmi=new JMenuItem("Find");

mEdit.add(jmi);

jmi=new JMenuItem("FindNext");
mEdit.add(jmi);
mEdit.addSeparator();
jmi=new JMenuItem("Select All");
mEdit.add(jmi);
jmi=new JMenuItem("Date/Time");
jmi.addActionListener(new datel());
mEdit.add(jmi);

jmb.add(mFile);
jmb.add(mEdit);

this.setJMenuBar(jmb);

this.getContentPane().add(jsp);
this.setSize(200,200);
this.setVisible(true);
}
//主函數,程序入口點
public static void main(String s[])
{
new NotePad();
}

}

熱點內容
如何獲得列印機無線密碼 發布:2024-05-04 06:44:59 瀏覽:416
上古諸神錄哪裡改密碼 發布:2024-05-04 06:43:55 瀏覽:261
灌籃高手手游自動蓋帽腳本 發布:2024-05-04 06:42:31 瀏覽:423
javajs引擎 發布:2024-05-04 06:37:33 瀏覽:796
javalist重復 發布:2024-05-04 06:19:27 瀏覽:509
max腳本管理 發布:2024-05-04 06:02:31 瀏覽:44
自行搭建伺服器 發布:2024-05-04 06:01:12 瀏覽:125
h3c如何查看所有配置 發布:2024-05-04 05:26:39 瀏覽:493
java統計字元串中字母個數 發布:2024-05-04 05:22:58 瀏覽:888
throwablejava 發布:2024-05-04 05:22:56 瀏覽:792