java画出斜椭圆_【转】画图java源代码,只画直线,矩形,椭圆
/*
*只畫直線,矩形,橢圓,只能向右下角畫
*
*PainterPanel extends JPanel implements MouseListener
*addMouseListener(this);
*
*JToggleButton
*
*hxz*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class PainterPanel extends JPanel implements MouseListener{
int shape=-1; //圖案類型
Point[] point=new Point[2]; //記錄鼠標拖動的起始點和終點
public PainterPanel(){
super(); //調用父類構造函數
this.setBackground(Color.white); //設置背景顏色
point[0]=new Point(-1,-1); //初始化變量
point[1]=new Point(-1,-1);
addMouseListener(this); //增加鼠標事件
}
public void mouseReleased(MouseEvent e){ //鼠標釋放事件
point[1]=new Point(e.getX(),e.getY()); //設置終點位置
repaint(); //重繪屏幕
}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mouseClicked(MouseEvent e){}
public void mousePressed(MouseEvent e){ //鼠標按下時事件
point[0]=new Point(e.getX(),e.getY()); //設置起始點位置
}
public void paint(Graphics g){
super.paint(g);
switch (shape){ //根據shape值繪制圖形
case 0:
g.drawLine(point[0].x,point[0].y,point[1].x,point[1].y); //繪線
break;
case 1:
int width=point[1].x-point[0].x;
int height=point[1].y-point[0].y;
g.drawOval(point[0].x,point[0].y,width,height); //繪橢圓
break;
case 2:
width=point[1].x-point[0].x;
height=point[1].y-point[0].y;
g.drawRect(point[0].x,point[0].y,width,height); //繪矩形
break;
}
}
public void drawShape(int shape){
this.shape=shape;
}
}
/*
*JToggleButton
*
*JToolBar
*
*hxz*/
public class PainterDemo extends JFrame{
JToggleButton[] button=new JToggleButton[3]; //按鈕組
PainterPanel painter=new PainterPanel(); //繪圖面板
public PainterDemo(){
super("Java畫圖程序"); //調用父類構造函數
String[] buttonName={"直線","橢圓","矩形"}; //按鈕文字
DrawShapeListener buttonListener=new DrawShapeListener(); //按鈕事件
JToolBar toolBar=new JToolBar(); //實例化工具欄
ButtonGroup buttonGroup=new ButtonGroup(); //實例化按鈕組
for (int i=0;i
button[i]=new JToggleButton(buttonName[i]); //實例化按鈕
button[i].addActionListener(buttonListener); //增加按鈕事件處理
buttonGroup.add(button[i]); //增加按鈕到按鈕組
toolBar.add(button[i]); //增加按鈕到工具欄
}
Container container=getContentPane(); //得到窗口容器
container.add(toolBar,BorderLayout.NORTH); //增加組件到容器上
container.add(painter,BorderLayout.CENTER);
setSize(300,200); //設置窗口尺寸
setVisible(true); //設置窗口為可視
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //關閉窗口時退出程序
}
//內部類
class DrawShapeListener implements ActionListener{ //按鈕事件處理
public void actionPerformed(ActionEvent e){
for (int i=0;i
if (e.getSource()==button[i]){ //判斷來自于哪個按鈕
painter.drawShape(i); //繪制圖形
}
}
}
}
public static void main(String[] args){
new PainterDemo();
}
}
總結
以上是生活随笔為你收集整理的java画出斜椭圆_【转】画图java源代码,只画直线,矩形,椭圆的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: foxmail 怎么修改存储路径_Fox
- 下一篇: java list 自定义类型转换_ja