你的問題是請問如何用主方法調用下面代碼中的方法?還是
java實例源碼沒有main方法,如何運行呢?
如果是單獨運行一般需要有main方法,或者採用new 對象時調用此方法。或者 加一個static 方法試下。
publictIconRender (){加方法 }。
如果是別的類調,就直接new 對象.方法就行了。
② 求大師寫一下Java代碼源代碼
package Project;
import java.util.Scanner;
public class Complex {
int x;
int y;
Complex(){
x=0;
y=0;
}
Complex(int i,int j){
x=i;
y=j;
}
//顯示
public void showComp(){
if(y>0){
System.out.print(x+"+"+y+"i"+'\t');
}
if(y<0){
System.out.print(x+""+y+"i"+'\t');
}
if(y==0){
System.out.print(x+""+'\t');
}
}
//求和
public static Complex addComp(Complex C1,Complex C2){
Complex newComplex=new Complex();
newComplex.x=C1.x+C2.x;
newComplex.y=C1.y+C2.y;
System.out.println();
System.out.print("和為:");
return newComplex;
}
//求差
public static Complex subComp(Complex C1,Complex C2){
Complex newComplex=new Complex();
newComplex.x=C1.x-C2.x;
newComplex.y=C1.y-C2.y;
System.out.println();
System.out.print("差為:");
return newComplex;
}
//求積
public static Complex multiComp(Complex C1,Complex C2){
Complex newComplex=new Complex();
newComplex.x=C1.x*C2.x-C1.y*C2.y;
newComplex.y=C1.x*C2.y+C1.y*C2.x;
System.out.println();
System.out.print("積為:");
return newComplex;
}
//是否相等
public static boolean equalComp(Complex C1,Complex C2){
System.out.println();
System.out.print("是否相等:");
return ((C1.x==C2.x)&&(C1.y==C2.y));
}
public static void main(String[] args){
Scanner data=new Scanner(System.in);
int x=data.nextInt();
int y=data.nextInt();
int m=data.nextInt();
int n=data.nextInt();
Complex Comp1=new Complex(x,y);
Complex Comp2=new Complex(m,n);
data.close();
//顯示
Comp1.showComp();
Comp2.showComp();
Complex.addComp(Comp1,Comp2).showComp(); //顯示 和
Complex.subComp(Comp1, Comp2).showComp(); //顯示 差
Complex.multiComp(Comp1, Comp2).showComp(); //顯示 積
System.out.println( Complex.equalComp(Comp1, Comp2));
}
}
③ 求JAVA源代碼
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class GradeStatistic {
public static void main(String[] args) {
GradeStatistic gs = new GradeStatistic();
List<Mark> list = new ArrayList<Mark>();
float sum = 0;
while(true){
Scanner sc = new Scanner(System.in);
System.out.print("Please input student name: ");
String name = sc.nextLine();
if(name.equals("end")){
break;
}
System.out.print("Please input student score: ");
float score = sc.nextFloat();
sum += score;
list.add(gs.new Mark(name, score));
}
float max = list.get(0).getScore();
float min = list.get(0).getScore();
for(Mark mark: list){
if(max < mark.getScore()){
max = mark.getScore();
}
if(min > mark.getScore()){
min = mark.getScore();
}
}
float average = sum / list.size();
System.out.println("Average is: " + average);
System.out.println("Max is: " + max);
System.out.println("Min is: " + min);
}
private class Mark{
private String name;
private float score;
public Mark(String name, float score){
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public float getScore() {
return score;
}
}
}
----------------------
Please input student name: Zhang san
Please input student score: 100
Please input student name: Li Si
Please input student score: 91
Please input student name: Ec
Please input student score: 35
Please input student name: ma qi
Please input student score: 67
Please input student name: end
Average is: 73.25
Max is: 100.0
Min is: 35.0
④ 求用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源代碼
我用了半個小時 幫你寫了一個簡單的驗證用戶名和密碼登陸問題 別辜負我的好意 下面是代碼!(建好包和類 代碼粘過去就能用)
實體類 包entity
-------------------------------------------------------------
package entity;
/**
* 用戶實體類
* @author new
*
*/
public class Users {
private String name;//用戶名
private String pass;//用戶密碼
/**
* 空的構造函數 用戶實力化 此類對象
*/
public Users(){
}
/**
* 構造函數 接收用戶名和密碼
* @param name
* @param pass
*/
public Users(String name, String pass) {
this.name = name;
this.pass = pass;
}
/**
* 下面set和get方法就不用解釋了吧
* @return
*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
}
資料庫類 包(我是模擬一下資料庫 沒有用到資料庫)
--------------------------------------------------------------
package ;
import java.util.*;
import entity.Users;//導入實體類
/**
* 模擬資料庫 用戶DAO
* @author new
*
*/
public class UsersDAO {
private static Users users=new Users();
static
{
users.setName("tom");
users.setPass("jerry");
}
/**
* 根據姓名查找這個用戶 (模擬一下資料庫)
* @param name
* @return
*/
public Users findUserByName(String name)
{
if(name.equals(this.users.getName()))
{
return this.users;
}
return null;
}
}
業務類 包service (驗證用戶名和密碼)
------------------------------------------------------------
package service;
import .UsersDAO;
import entity.Users;
/**
* 驗證密碼 業務類
* @author new
*
*/
public class validatePass {
//實力化DAO對象
private UsersDAO us=new UsersDAO();
/**
* 驗證輸入的密碼是否正確
* @param name
* @param pass
* @return
*/
public Users validate(String name,String pass)
{
Users user=null;
user=us.findUserByName(name);
//如果不為空 說明查到了
if(user!=null)
{
//用查詢出來對象的密碼和傳過來的密碼比較
if(user.getPass().equals(pass))
{
return user;
}
}
return null;
}
}
最後是測試test類 包test
----------------------------------------------------------
package test;
import entity.Users;
import service.validatePass;
/**
* 測試類
* @author new
*
*/
public class test {
/**
* main方法 用於測試
* @param args
*/
public static void main(String[] args)
{
//實例化業務類對象
validatePass v=new validatePass();
//用戶名和密碼
String name="tom";
String pass="jerry";
//開始驗證
Users user=v.validate(name, pass);
if(user==null)
{
System.out.println("你輸入的用戶名或密碼錯誤!");
}else
{
System.out.println("你已經通過驗證,成功登陸!");
}
}
}
⑥ 用JAVA 編程的源代碼
直接定義兩個介面學生介面裡面定義一個學費的變數,老師介面裡面定義一個工資變數,
eclipse裡面可以自動幫你添加相關變數的getterhe
setter方法的。
⑦ 用Java編寫簡易記事本源代碼
importjava.awt.BorderLayout;importjava.awt.Container;importjava.awt.Font;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.awt.event.InputEvent;importjava.awt.event.KeyAdapter;importjava.awt.event.KeyEvent;importjava.awt.event.MouseAdapter;importjava.awt.event.MouseEvent;importjava.awt.event.WindowAdapter;importjava.awt.event.WindowEvent;importjava.io.BufferedReader;importjava.io.BufferedWriter;importjava.io.File;importjava.io.FileReader;importjava.io.FileWriter;importjava.io.IOException;importjavax.swing.BorderFactory;importjavax.swing.JFileChooser;importjavax.swing.JFrame;importjavax.swing.JLabel;importjavax.swing.JMenu;importjavax.swing.JMenuBar;importjavax.swing.JMenuItem;importjavax.swing.JOptionPane;importjavax.swing.JPopupMenu;importjavax.swing.JScrollPane;importjavax.swing.JTextArea;importjavax.swing.KeyStroke;importjavax.swing.ScrollPaneConstants;importjavax.swing.SwingConstants;{privateJMenuItemmenuOpen;privateJMenuItemmenuSave;privateJMenuItemmenuSaveAs;privateJMenuItemmenuClose;privateJMenueditMenu;privateJMenuItemmenuCut;privateJMenuItemmenuCopy;privateJMenuItemmenuPaste;privateJMenuItemmenuAbout;privateJTextAreatextArea;privateJLabelstateBar;;privateJPopupMenupopUpMenu;publicJNotePadUI(){super("新建文本文件");setUpUIComponent();setUpEventListener();setVisible(true);}privatevoidsetUpUIComponent(){setSize(640,480);//菜單欄JMenuBarmenuBar=newJMenuBar();//設置「文件」菜單JMenufileMenu=newJMenu("文件");menuOpen=newJMenuItem("打開");//快捷鍵設置menuOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,InputEvent.CTRL_MASK));menuSave=newJMenuItem("保存");menuSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,InputEvent.CTRL_MASK));menuSaveAs=newJMenuItem("另存為");menuClose=newJMenuItem("關閉");menuClose.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,InputEvent.CTRL_MASK));fileMenu.add(menuOpen);fileMenu.addSeparator();//分隔線fileMenu.add(menuSave);fileMenu.add(menuSaveAs);fileMenu.addSeparator();//分隔線fileMenu.add(menuClose);//設置「編輯」菜單JMenueditMenu=newJMenu("編輯");menuCut=newJMenuItem("剪切");menuCut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,InputEvent.CTRL_MASK));menuCopy=newJMenuItem("復制");menuCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_MASK));menuPaste=newJMenuItem("粘貼");menuPaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,InputEvent.CTRL_MASK));editMenu.add(menuCut);editMenu.add(menuCopy);editMenu.add(menuPaste);//設置「關於」菜單JMenuaboutMenu=newJMenu("關於");menuAbout=newJMenuItem("關於JNotePad");aboutMenu.add(menuAbout);menuBar.add(fileMenu);menuBar.add(editMenu);menuBar.add(aboutMenu);setJMenuBar(menuBar);//文字編輯區域textArea=newJTextArea();textArea.setFont(newFont("宋體",Font.PLAIN,16));textArea.setLineWrap(true);JScrollPanepanel=newJScrollPane(textArea,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);ContainercontentPane=getContentPane();contentPane.add(panel,BorderLayout.CENTER);//狀態欄stateBar=newJLabel("未修改");stateBar.setHorizontalAlignment(SwingConstants.LEFT);stateBar.setBorder(BorderFactory.createEtchedBorder());contentPane.add(stateBar,BorderLayout.SOUTH);popUpMenu=editMenu.getPopupMenu();fileChooser=newJFileChooser();}privatevoidsetUpEventListener(){//按下窗口關閉鈕事件處理addWindowListener(newWindowAdapter(){publicvoidwindowClosing(WindowEvente){closeFile();}});//菜單-打開menuOpen.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){openFile();}});//菜單-保存menuSave.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){saveFile();}});//菜單-另存為menuSaveAs.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){saveFileAs();}});//菜單-關閉文件menuClose.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){closeFile();}});//菜單-剪切menuCut.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){cut();}});//菜單-復制menuCopy.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){();}});//菜單-粘貼menuPaste.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){paste();}});//菜單-關於menuAbout.addActionListener(newActionListener(){publicvoidactionPerformed(ActionEvente){//顯示對話框JOptionPane.showOptionDialog(null,"程序名稱:\nJNotePad\n"+"程序設計:\n\n"+"簡介:\n一個簡單的文字編輯器\n"+"可作為驗收Java的實現對象\n"+"歡迎網友下載研究交流\n\n"+"/","關於JNotePad",JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE,null,null,null);}});//編輯區鍵盤事件textArea.addKeyListener(newKeyAdapter(){publicvoidkeyTyped(KeyEvente){processTextArea();}});//編輯區滑鼠事件textArea.addMouseListener(newMouseAdapter(){publicvoidmouseReleased(MouseEvente){if(e.getButton()==MouseEvent.BUTTON3)popUpMenu.show(editMenu,e.getX(),e.getY());}publicvoidmouseClicked(MouseEvente){if(e.getButton()==MouseEvent.BUTTON1)popUpMenu.setVisible(false);}});}privatevoidopenFile(){if(isCurrentFileSaved()){//文件是否為保存狀態open();//打開}else{//顯示對話框intoption=JOptionPane.showConfirmDialog(null,"文件已修改,是否保存?","保存文件?",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE,null);switch(option){//確認文件保存caseJOptionPane.YES_OPTION:saveFile();//保存文件break;//放棄文件保存caseJOptionPane.NO_OPTION:open();break;}}}(){if(stateBar.getText().equals("未修改")){returnfalse;}else{returntrue;}}privatevoidopen(){//fileChooser是JFileChooser的實例//顯示文件選取的對話框intoption=fileChooser.showDialog(null,null);//使用者按下確認鍵if(option==JFileChooser.APPROVE_OPTION){try{//開啟選取的文件BufferedReaderbuf=newBufferedReader(newFileReader(fileChooser.getSelectedFile()));//設定文件標題setTitle(fileChooser.getSelectedFile().toString());//清除前一次文件textArea.setText("");//設定狀態欄stateBar.setText("未修改");//取得系統相依的換行字元StringlineSeparator=System.getProperty("line.separator");//讀取文件並附加至文字編輯區Stringtext;while((text=buf.readLine())!=null){textArea.append(text);textArea.append(lineSeparator);}buf.close();}catch(IOExceptione){JOptionPane.showMessageDialog(null,e.toString(),"開啟文件失敗",JOptionPane.ERROR_MESSAGE);}}}privatevoidsaveFile(){//從標題欄取得文件名稱Filefile=newFile(getTitle());//若指定的文件不存在if(!file.exists()){//執行另存為saveFileAs();}else{try{//開啟指定的文件BufferedWriterbuf=newBufferedWriter(newFileWriter(file));//將文字編輯區的文字寫入文件buf.write(textArea.getText());buf.close();//設定狀態欄為未修改stateBar.setText("未修改");}catch(IOExceptione){JOptionPane.showMessageDialog(null,e.toString(),"寫入文件失敗",JOptionPane.ERROR_MESSAGE);}}}privatevoidsaveFileAs(){//顯示文件對話框intoption=fileChooser.showSaveDialog(null);//如果確認選取文件if(option==JFileChooser.APPROVE_OPTION){//取得選擇的文件Filefile=fileChooser.getSelectedFile();//在標題欄上設定文件名稱setTitle(file.toString());try{//建立文件file.createNewFile();//進行文件保存saveFile();}catch(IOExceptione){JOptionPane.showMessageDialog(null,e.toString(),"無法建立新文件",JOptionPane.ERROR_MESSAGE);}}}privatevoidcloseFile(){//是否已保存文件if(isCurrentFileSaved()){//釋放窗口資源,而後關閉程序dispose();}else{intoption=JOptionPane.showConfirmDialog(null,"文件已修改,是否保存?","保存文件?",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE,null);switch(option){caseJOptionPane.YES_OPTION:saveFile();break;caseJOptionPane.NO_OPTION:dispose();}}}privatevoidcut(){textArea.cut();stateBar.setText("已修改");popUpMenu.setVisible(false);}privatevoid(){textArea.();popUpMenu.setVisible(false);}privatevoidpaste(){textArea.paste();stateBar.setText("已修改");popUpMenu.setVisible(false);}privatevoidprocessTextArea(){stateBar.setText("已修改");}publicstaticvoidmain(String[]args){newJNotePadUI();}}
⑧ 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源代碼 怎麼查看
不知道你說的是瀏覽器的還是什麼的,
如果是瀏覽器的那麼簡單找到工具-查看源代碼,你就能看見代碼了,
還有一個就是被編譯成class文件的java用反編譯工具可以看到源代碼,
如果以上都不是你想要的答案,那麼你所說的代碼就是程序員寫好的代碼文件
⑩ 顯示一個國際象棋棋盤的java源代碼
import java.awt.Color;
import javax.swing.*;
public class Chess extends JPanel
{// 繼承面板類
public Chess(int grids,int gridsize)
{//grids:行數和列數, gridsize:單元格的高和寬
super(null);
for(int i=0; i<grids; i++)
{
for(int j=0; j<grids; j++)
{
JLabel l = new JLabel();//生成標簽實例
l.setSize(gridsize,gridsize);
l.setLocation(i*gridsize,j*gridsize);
if((i+j)%2==0)
{ //當小方格的坐標和剛好是偶數時,
l.setBackground(Color.black); //設置為方格為黑色
l.setOpaque(true); //設置為不透明
}
l.setBorder(BorderFactory.createLineBorder(Color.black)); //設置邊界為黑色
add(l);//將l標簽添加到面板
}
}
}
public static void main(String[] args)
{
JFrame f = new JFrame();
f.setSize(658,677); //邊框的長和寬
f.setLocationRelativeTo(null); //設置窗口相對於指定組件的位置
f.add(new Chess(8,80));
f.setVisible(true);
}
}