代碼如下:import javax.microedition.lci.Canvas;import javax.microedition.lci.Display;import javax.microedition.lci.Graphics;import javax.microedition.midlet.MIDlet;import javax.microedition.midlet.MIDletStateChangeException;public class Zfx extends MIDlet { private Display display; public Zfx() { display=Display.getDisplay(this); Zfxc qs=new Zfxc(); display.setCurrent(qs); } protected void destroyApp(boolean arg0) throws MIDletStateChangeException { } protected void pauseApp() { } protected void startApp() throws MIDletStateChangeException { }}class Zfxc extends Canvas implements Runnable{ private int x,y,x1,y1,i; private boolean flag; Zfxc(){ init(); } private void init(){ Thread thread=new Thread(this); thread.start(); } protected void paint(Graphics g) { g.setColor(255,255,255); g.fillRect(0, 0, this.getWidth(), this.getHeight()); g.setColor(0); g.fillRect(x, y, 10, 10); } private void logic(){ if(x=this.getWidth()-10){ x1=2; } if(x1==1){ x+=3; }else if(x1==2){ x-=3; } if(y=this.getHeight()-10){ y1=2; } if(y1==1){ y+=3; }else if(y1==2){ y-=3; } } protected void keyPressed(int keyCode) { if(keyCode==-5){ if(i==0){ flag=true; i=1; }else if(i==1){ flag=false; i=0; } } } public void run() { while(true){ if(flag){ logic(); } repaint(); try { Thread.sleep(80); } catch (InterruptedException e) { e.printStackTrace(); } } }}求Java 實現繪制圖形並移動代碼
② 求一個,java圖形化界面的源碼
自己寫的石頭剪子布代碼,有圖形界面,可以把自己選中的圖片命名為.jpg放到工程目錄下做背景圖片。//////////////////////////// package HomeWork;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
public class StoneShearsSack { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new StoneWindow("Sample Game");
}
}
final class StoneWindow extends JFrame implements ActionListener,ItemListener{
JLabel win,draw,lose,score,count;
JTextArea text;
JComboBox list;
JButton fight,clear;
int swin,sdraw,slose,sscore;
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
String str1,str2,str3;
Random rdm = new Random();
int flag,random ,flag1, count1;
//final ImageIcon con = new ImageIcon("a.jpg") ;
public StoneWindow(String s){
setTitle("Sample Game");
fight = new JButton("出招");
clear = new JButton("清除分數");
//final ImageIcon con = new ImageIcon("b.jpg") ;
text = new JTextArea(){
final ImageIcon con = new ImageIcon("a.jpg");
Image mg = con.getImage();
{setOpaque(false);}
public void paintComponent(Graphics g){
g.drawImage(mg, 0, 0, this);
super.paintComponent(g);
}
};
text.setForeground(Color.black);
Font f = new Font("華文行楷",Font.BOLD,50);
text.setFont(f);
list = new JComboBox();
list.addItem("石頭");
list.addItem("剪子");
list.addItem("布");
panel2.setBackground(Color.blue);
panel2.add(list);
panel2.add(fight);
panel2.add(clear);
panel2.setPreferredSize(new Dimension(900,50));
list.addItemListener(this);
fight.addActionListener(this);
clear.addActionListener(this);
win = new JLabel("贏:" + swin);
draw = new JLabel(" 和:" + sdraw);
lose = new JLabel(" 輸:" + slose);
score = new JLabel(" 得分:" + sscore);
count = new JLabel(" 總局:" + count1);
Font f1 = new Font("宋體",1,30);
win.setFont(f1);
draw.setFont(f1);
lose.setFont(f1);
score.setFont(f1);
count.setFont(f1);
win.setForeground(Color.cyan);
draw.setForeground(Color.green);
lose.setForeground(Color.blue);
score.setForeground(Color.black);
count.setForeground(Color.pink);
panel1.setBackground(Color.red);
panel1.add(win);
panel1.add(draw);
panel1.add(lose);
panel1.add(score);
panel1.add(count);
panel1.setPreferredSize(new Dimension(900,50));
add(panel1,BorderLayout.NORTH);
add(text,BorderLayout.CENTER);
add(panel2,BorderLayout.SOUTH);
setBounds(100,100,900,450);
validate();
setVisible(true);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == fight){
if(list.getSelectedItem() == "石頭"){
flag = 0;
}
else if(list.getSelectedItem() == "剪子"){
flag = 1;
}
else if(list.getSelectedItem() == "布"){
flag = 2;
}
str1 = (String)list.getSelectedItem();
text.setText("");
text.append("\n");
text.append(" 你 出: " + str1 + "\n");
text.append(" 電腦出: " + this.random() + "\n");
text.append(" 結 果: " + this.result() + "\n");
this.finalresult();
}
if(e.getSource() == clear){
swin = 0;
sdraw = 0;
slose = 0;
sscore = 0;
count1 = 0;
text.setText("");
win.setText(" 贏:" + swin);
draw.setText(" 和:" + sdraw);
lose.setText(" 輸:" + slose);
score.setText(" 得分:" + sscore);
count.setText(" 總局:" + count1);
}
}
public String random(){
random = rdm.nextInt(3);
if(random == 0)
str2 = "石頭";
else if(random == 1)
str2 = "剪子";
else if(random == 2)
str2 = "布";
return str2;
}
public String result(){
if(random == flag){
str3 ="打平";
flag1 = 0;
}
else if(random < flag &&flag == 1){
str3 = "你輸了";
flag1 = 1;
}
else if(random <flag && random ==1){
str3 = "你輸了";
flag1 = 1;
}
else if(random ==2 && flag == 0){
str3 = "你輸了";
flag1 = 1;
}
else{
str3 = "你贏了";
flag1 = 2;
}
return str3;
}
public void finalresult(){
if(flag1 == 0){
sdraw ++;
draw.setText(" 平:" + sdraw);
score.setText(" 得分:" + sscore);
}
if(flag1 == 1){
slose ++;
sscore = sscore - 10;
lose.setText(" 輸:" + slose);
score.setText(" 得分:" + sscore);
}
if(flag1 == 2) {
swin ++;
sscore = sscore + 10;
win.setText(" 贏:" + swin);
score.setText(" 得分:" + sscore);
}
count1 = swin + slose + sdraw;
count.setText(" 總局:" + count1);
}
public void itemStateChanged(ItemEvent e){
}
}
③ java圖形用戶界面的選擇一個文件並復制(另存為)的代碼,麻煩了。
可以給JTextField t1 一個初始路徑,那樣,如果每次都是備份同一個文件直接點保存選路徑就可以,如果想備份其他文件再選其他文件就可以了
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Calendar;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class BakTo extends JFrame implements ActionListener {
JLabel l1 = new JLabel("原始文件");
JTextField t1 = new JTextField(40);
JButton b1 = new JButton("選擇");
JLabel l2 = new JLabel("保存目錄");
JTextField t2 = new JTextField(40);
JButton b2 = new JButton("保存");
JFileChooser j1 = new JFileChooser();
JFileChooser j2 = new JFileChooser();
static File fileFlag = new File("");
public BakTo() {
setBounds(200, 200, 600, 140);
setLayout(new FlowLayout());
add(l1);
add(t1);
add(b1);
add(l2);
add(t2);
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
setResizable(false);
setVisible(true);
validate();
}
public void actionPerformed(ActionEvent e) {
try {
if (e.getSource() == b1) {
int n = j1.showOpenDialog(null);
String filename = j1.getSelectedFile().toString();
if (n == JFileChooser.APPROVE_OPTION) {
t1.setText(filename);
fileFlag = new File(filename);
}
}
else if (e.getSource() == b2) {
j2.setCurrentDirectory(fileFlag);// 設置打開對話框的默認路徑
j2.setSelectedFile(fileFlag);// 設置選中原來的文件
int n = j2.showSaveDialog(null);
String filename2 = j2.getSelectedFile().toString();
if(filename2.indexOf(".")!=-1){
filename2=filename2.substring(0,filename2.indexOf("."));
}
// 以下兩句是獲得原文件的擴展名
int flag = t1.getText().lastIndexOf(".");
String kuozhan = t1.getText().substring(flag);
String date = getDate();// 取得當前日期
if (n == JFileChooser.APPROVE_OPTION) {
t2.setText(filename2 +date+ kuozhan);// 把日期和擴展名添加到原來文件的後面
}
int b;
char[] t = new char[25];
// 這里我改用了文件流
FileInputStream input = new FileInputStream(t1.getText());
FileOutputStream output = new FileOutputStream(filename2+date
+ kuozhan);// 把擴展名添加到原來文件的後面
int in = input.read();
while (in != -1) {
output.write(in);
in = input.read();
}
input.close();
output.close();
}
} catch (Exception x) {
System.out.println(x);
}
}
public String getDate() {
Calendar rightNow = Calendar.getInstance();
System.out.println(rightNow.toString());
int year = rightNow.YEAR;
int date = rightNow.DATE;
int month = rightNow.MONTH + 1;
String d = year + "年" + month + "月" + date + "日";
return d;
}
public static void main(String args[]) {
BakTo c1 = new BakTo();
}
}
④ 求一個java程序:繪圖程序包括畫圓,橢圓,線,矩形,自定義。並且可以調圖形顏色!
publicenumShapeTypes{
LINE,CIRCLE,RECTANGLE
}
publicinterfaceShape{
voidpaint(Graphicsg);
}
{
//矩形左上角的坐標
privateintx,y;
//矩形的寬度和高度
privateintwidth,height;
privateColorrectangleColor;
publicRectangle(){
super();
}
publicRectangle(intx,inty,intwidth,intheight,ColorrectangleColor){
super();
this.x=x;
this.y=y;
this.width=width;
this.height=height;
this.rectangleColor=rectangleColor;
}
@Override
publicvoidpaint(Graphicsg){
g.setColor(rectangleColor);
g.drawRect(x,y,width,height);
}
}
{
//直線的起始位置
privateintx1,y1;
//直線的終止位置
privateintx2,y2;
privateColorlineColor;
publicLine(intx1,inty1,intx2,inty2,ColorlineColor){
super();
this.x1=x1;
this.y1=y1;
this.x2=x2;
this.y2=y2;
this.lineColor=lineColor;
}
publicLine(){
super();
}
@Override
publicvoidpaint(Graphicsg){
g.setColor(lineColor);
g.drawLine(x1,y1,x2,y2);
}
}
{
//圓的顏色
privateColorcircleColor;
//圓心的坐標
privateintx,y;
//圓的半徑
privateintradius;
publicCircle(){
super();
}
publicCircle(intx,inty,intradius,ColorcircleColor){
super();
this.circleColor=circleColor;
this.x=x;
this.y=y;
this.radius=radius;
}
@Override
publicvoidpaint(Graphicsg){
g.setColor(circleColor);
//畫弧,當弧的寬度和高度一致且從0~360度時就是原形了
g.drawArc(x,y,radius,radius,0,360);
}
}
,MouseMotionListener{
=-5229161042153132522L;
//滑鼠點擊起始坐標和當前坐標
privateintbeginX=0,beginY=0,currentX=0,currentY=0;
//判斷滑鼠是否被按下
privatebooleanisMousePressing=false;
//保存當前的圖形,在撤銷和恢復時使用
privatefinalStack<Shape>currentShapes=newStack<Shape>();
//保存已經刪除過的圖形
privatefinalStack<Shape>deletedShapes=newStack<Shape>();
privateShapeTypestype;
privateColorcolor;
publicSketchpadPanel(){
addMouseListener(this);
addMouseMotionListener(this);
}
/**
*撤銷方法
*/
publicvoindo(){
if(currentShapes.size()>0){
//從所有保存過的圖形中取出最後一個,放入到已刪除的圖形中去
Shapeshape=currentShapes.pop();
deletedShapes.push(shape);
repaint();
}
}
/**
*恢復撤銷方法
*/
publicvoidredo(){
if(deletedShapes.size()>0){
//從所有刪除的圖形中取出最後一個,放入保存的圖形中
Shapeshape=deletedShapes.pop();
currentShapes.push(shape);
repaint();
}
}
/**
*設置命令
*
*@paramtype
*/
publicvoidsetShapeType(ShapeTypestype){
this.type=type;
}
/**
*設置顏色
*
*@paramcolor
*/
publicvoidsetColor(Colorcolor){
this.color=color;
}
publicvoipdete(Graphicsg){
paint(g);
}
/**
*繪制畫板
*/
@Override
publicvoidpaint(Graphicsg){
//繪制畫板
Dimensionsize=getSize();
intwidth=size.width;
intheight=size.height;
g.setColor(Color.WHITE);
g.fillRect(0,0,width,height);
//繪制所有圖形
Shapeshape=null;
Enumeration<Shape>e=currentShapes.elements();
while(e.hasMoreElements()){
shape=e.nextElement();
shape.paint(g);
}
//如果當前滑鼠沒有釋放
if(isMousePressing){
g.setColor(color);
switch(type){
//繪制直線
caseLINE:
g.drawLine(beginX,beginY,currentX,currentY);
break;
//繪制矩形
caseRECTANGLE:
if(currentX<beginX){
if(currentY<beginY){
//如果當前位置在起始位置的左上方,則以滑鼠當前位置為矩形的左上角位置
g.drawRect(currentX,currentY,beginX-currentX,beginY-currentY);
}else{
//如果當前位置在起始位置的左下方,則以滑鼠當前位置的橫坐標和起始位置的縱坐標作為矩形的左上角位置
g.drawRect(currentX,beginY,beginX-currentX,currentY-beginY);
}
}else{
if(currentY<beginY){
//如果當前位置在起始位置的右上方,則以滑鼠起始位置的很坐標和當前位置的縱坐標作為矩形的左上角位置
g.drawRect(beginX,currentY,currentX-beginX,beginY-currentY);
}else{
//如果當前位置在起始位置的右下方,則已起始位置作為矩形的左上叫位置
g.drawRect(beginX,beginY,currentX-beginX,currentY-beginY);
}
}
break;
//繪制圓形
caseCIRCLE:
//半徑為a*a+b*b的平方根
intradius=(int)Math
.sqrt((beginX-currentX)*(beginX-currentX)+(beginY-currentY)*(beginY-currentY));
g.drawArc(beginX-radius/2,beginY-radius/2,radius,radius,0,360);
break;
}
}
}
@Override
publicvoidmouseClicked(MouseEvente){
}
@Override
publicvoidmouseEntered(MouseEvente){
}
@Override
publicvoidmouseExited(MouseEvente){
}
/**
*當滑鼠按下的時候獲得起始坐標
*/
@Override
publicvoidmousePressed(MouseEvente){
beginX=e.getX();
beginY=e.getY();
isMousePressing=true;
}
/**
*當滑鼠釋放時獲得當前坐標
*/
@Override
publicvoidmouseReleased(MouseEvente){
currentX=e.getX();
currentY=e.getY();
isMousePressing=false;
//當釋放滑鼠時,將繪制的圖形保存到shapes中
switch(type){
//繪制直線
caseLINE:
Lineline=newLine(beginX,beginY,currentX,currentY,color);
currentShapes.push(line);
break;
//繪制圓形
caseCIRCLE:
//半徑為a*a+b*b的平方根
intradius=(int)Math
.sqrt((beginX-currentX)*(beginX-currentX)+(beginY-currentY)*(beginY-currentY));
Circlecircle=newCircle(beginX-radius/2,beginY-radius/2,radius,color);
currentShapes.push(circle);
break;
//繪制矩形
caseRECTANGLE:
Rectanglerectangle=null;
if(currentX<beginX){
if(currentY<beginY){
rectangle=newRectangle(currentX,currentY,beginX-currentX,beginY-currentY,color);
}else{
rectangle=newRectangle(currentX,beginY,beginX-currentX,currentY-beginY,color);
}
}else{
if(currentY<beginY){
rectangle=newRectangle(beginX,currentY,currentX-beginX,beginY-currentY,color);
}else{
rectangle=newRectangle(beginX,beginY,currentX-beginX,currentY-beginY,color);
}
}
currentShapes.push(rectangle);
break;
}
repaint();
}
@Override
publicvoidmouseDragged(MouseEvente){
currentX=e.getX();
currentY=e.getY();
this.repaint();
}
@Override
publicvoidmouseMoved(MouseEvente){
}
}
{
=-7080053971741609904L;
=newJPanel();//存放命令的面板
privatefinalJPanelcolorPanel=newJPanel();//存放顏色的面板
privatefinalJPanelmainPanel=newJPanel();//主面板
privatefinalJButtonredButton=newJButton("紅色");
privatefinalJButtonblueButton=newJButton("藍色");
=newJButton("綠色");
privatefinalJButtonlineButton=newJButton("直線");
=newJButton("圓");
=newJButton("矩形");
privatefinalJButtonundoButton=newJButton("撤銷");
privatefinalJButtonredoButton=newJButton("恢復撤銷");
privatefinalJButtonexitButton=newJButton("退出");
SketchpadPanelsketchPanel=newSketchpadPanel();
privatevoidinitFrame(){
commandPanel.setLayout(newFlowLayout());
commandPanel.add(lineButton);
commandPanel.add(circleButton);
commandPanel.add(rectangleButton);
commandPanel.add(undoButton);
commandPanel.add(redoButton);
commandPanel.add(exitButton);
colorPanel.setLayout(newFlowLayout());
colorPanel.add(redButton);
colorPanel.add(blueButton);
colorPanel.add(greenButton);
mainPanel.setLayout(newBorderLayout());
mainPanel.add(commandPanel,BorderLayout.NORTH);
mainPanel.add(colorPanel,BorderLayout.CENTER);
getContentPane().add("South",mainPanel);
getContentPane().add("Center",sketchPanel);
//初始化設置:顏色和命令
lineButton.setForeground(Color.RED);
sketchPanel.setColor(Color.RED);
redButton.setForeground(Color.RED);
sketchPanel.setShapeType(ShapeTypes.LINE);
}
privatevoidinitListener(){
redButton.addActionListener(newActionListener(){
@Override
publicvoidactionPerformed(ActionEvente){
redAction(e);
}
});
blueButton.addActionListener(newActionListener(){
@Override
publicvoidactionPerformed(ActionEvente){
blueAction(e);
}
});
greenButton.addActionListener(newActionListener(){
@Override
publicvoidactionPerformed(ActionEvente){
greenAction(e);
}
});
undoButton.addActionListener(newActionListener(){
@Override
publicvoidactionPerformed(ActionEvente){
undoAction(e);
}
});
redoButton.addActionListener(newActionListener(){
@Override
publicvoidactionPerformed(ActionEvente){
redoAction(e);
}
});
exitButton.addActionListener(newActionListener(){
@Override
publicvoidactionPerformed(ActionEvente){
exitAction(e);
}
});
lineButton.addActionListener(newActionListener(){
@Override
publicvoidactionPerformed(ActionEvente){
lineAction(e);
}
});
circleButton.addActionListener(newActionListener(){
@Override
publicvoidactionPerformed(ActionEvente){
circleAction(e);
}
});
rectangleButton.addActionListener(newActionListener(){
@Override
publicvoidactionPerformed(ActionEvente){
rectangleAction(e);
}
});
}
publicSketchpadFrame(){
initFrame();
initListener();
this.setSize(500,600);
setLocationByPlatform(true);
setResizable(true);
}
/*********************處理事件**********************/
privatevoindoAction(ActionEvente){
sketchPanel.undo();
}
privatevoidredoAction(ActionEvente){
sketchPanel.redo();
}
privatevoidexitAction(ActionEvente){
System.exit(0);
}
privatevoidlineAction(ActionEvente){
//選中按鈕為紅色,其餘為黑色
lineButton.setForeground(Color.RED);
circleButton.setForeground(Color.BLACK);
rectangleButton.setForeground(Color.BLACK);
sketchPanel.setShapeType(ShapeTypes.LINE);
}
privatevoidcircleAction(ActionEvente){
circleButton.setForeground(Color.RED);
lineButton.setForeground(Color.BLACK);
rectangleButton.setForeground(Color.BLACK);
sketchPanel.setShapeType(ShapeTypes.CIRCLE);
}
privatevoidrectangleAction(ActionEvente){
rectangleButton.setForeground(Color.RED);
lineButton.setForeground(Color.BLACK);
circleButton.setForeground(Color.BLACK);
sketchPanel.setShapeType(ShapeTypes.RECTANGLE);
}
privatevoidredAction(ActionEvente){
redButton.setForeground(Color.RED);
blueButton.setForeground(Color.BLACK);
greenButton.setForeground(Color.BLACK);
sketchPanel.setColor(Color.RED);
}
privatevoidblueAction(ActionEvente){
blueButton.setForeground(Color.RED);
redButton.setForeground(Color.BLACK);
greenButton.setForeground(Color.BLACK);
sketchPanel.setColor(Color.BLUE);
}
privatevoidgreenAction(ActionEvente){
greenButton.setForeground(Color.RED);
redButton.setForeground(Color.BLACK);
blueButton.setForeground(Color.BLACK);
sketchPanel.setColor(Color.GREEN);
}
}
/**
*
*@author不落的太陽(SeanYang)
*@version1.0
*@sinceJDK1.8
*
*/
publicclassSketchpadMain{
/**
*測試方法
*
*@paramargs命令行參數
*/
publicstaticvoidmain(String[]args){
EventQueue.invokeLater(newRunnable(){
@Override
publicvoidrun(){
JFrameframe=newSketchpadFrame();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
}
}
⑤ java Graphics 畫了很多線,如何滑鼠點擊選中其中一根線
把線或者點用容器保存下來,然後繪制,點擊滑鼠的時候遍歷容器,比較滑鼠點擊點,確定選中的點或線,繪制的時候改變這條線的顏色,達到選中的效果
⑥ JAVA也可以用於圖像的設計嗎
是的,Java可以用於圖像的設計。Java提供了許多圖形庫和工具,可以用於創建和處理圖像。以下是一些常用的Java圖形庫和工具:搭衡
1. Java 2D API:Java 2D API提供了一組用於創建和處理2D圖形的類和介面,包括繪圖、圖像處理、顏色管理和字體等方面的功能。
2. JavaFX:JavaFX是一個用於創建富客戶端應用程序的凱困框架,包括圖形、媒體、界面和動畫等方面的功能。JavaFX提供了一組用於創建和處理圖像的類和介面,可以用於創建各種類型的圖像和動畫效果。
3. AWT:Abstract Window Toolkit(AWT)是Java的原始圖形庫,提供了一組用於創建和處理圖形用戶界面(GUI)的類和介面。AWT包括一些基本的繪圖和事件處理功能,但是相對於Java 2D API和JavaFX,其功能較為有限。
4. Java圖像處理庫(Java Image Processing Library,JIPL):JIPL是一個開源的Java圖像處理庫,提供了一組用於處理和編輯圖像的類和方法,包括圖像過濾器盯枝念、雜訊消除、邊緣檢測、圖像變換和顏色空間轉換等方面的功能。
總之,Java可以用於圖像的設計,開發人員可以根據具體需求選擇適合的圖形庫和工具。