程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> JAVA 用鍵盤在面板上畫圖形 實現代碼

JAVA 用鍵盤在面板上畫圖形 實現代碼

編輯:關於JAVA
 

package test;

import java.awt.*;
import java.awt.geom.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
public class test06{
public static void main(String[]args)
{
SketchFrame frame=new SketchFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
class SketchFrame extends JFrame
{
public SketchFrame()
{
setTitle("java3");
setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);
SketchPanel panel=new SketchPanel();
Container contentPane=getContentPane();
contentPane.add(panel);
}
public static final int DEFAULT_WIDTH=300;
public static final int DEFAULT_HEIGHT=200;
}
class SketchPanel extends JPanel
{
public SketchPanel()
{
last=new Point2D.Double(100,100);
lines=new ArrayList();
KeyHandler listener=new KeyHandler();
addKeyListener(listener);
setFocusable(true);
}
public void add(int dx,int dy)
{
Point2D end=new Point2D.Double(last.getX()+dx,
last.getY()+dy);
Line2D line=new Line2D.Double(last,end);
lines.add(line);
repaint();
last=end;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2=(Graphics2D)g;
for(int i=0;i<lines.size();i++)
g2.draw((Line2D)lines.get(i));
}
private Point2D last;
private ArrayList lines;
private static final int SMALL_INCREMENT=1;
private static final int LARGE_INCREMENT=5;
private class KeyHandler implements KeyListener
{
public void keyPressed(KeyEvent event)
{
int keyCode=event.getKeyCode();
int d;
if (event.isShiftDown ())
d=LARGE_INCREMENT;
else
d=SMALL_INCREMENT;
if(keyCode==KeyEvent.VK_LEFT)add(-d,0);
else if(keyCode==KeyEvent.VK_RIGHT)add(d,0);
else if(keyCode==KeyEvent.VK_UP)add(0,-d);
else if(keyCode==KeyEvent.VK_DOWN)add(0,d);
}
public void keyReleased(KeyEvent event){}
public void keyTyped(KeyEvent event)
{
char keyChar=event.getKeyChar();
int d;
if(Character.isUpperCase(keyChar))
{
d=LARGE_INCREMENT;
keyChar=Character.toLowerCase(keyChar);
}
else
d=SMALL_INCREMENT;
}
}
}

JAVA 用鍵盤在面板上畫圖形 實現代碼
JAVA 用鍵盤在面板上畫圖形 實現代碼
 

 

 
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved