java如何在事件监听中显示 直线?比如说按一个按钮就自动显示出来一个图形……
展开全部
例子。画一条直线和多个椭圆。
import java.awt.*;
import java.awt.Graphics2D;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
public class TestFrame2 extends JFrame implements ActionListener{
private JButton jb;
public TestFrame2() {
setName("画直线");
setBounds(200,200,300,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jb = new JButton("按钮");
jb.addActionListener(this);
add(jb,BorderLayout.SOUTH);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
//获得窗口的pane再获得该pane的画笔
Graphics2D g = (Graphics2D) getContentPane().getGraphics();
//画直线
g.drawLine(10, 10, 40, 40);
g.setColor(Color.blue);
Ellipse2D.Float e1 = new Ellipse2D.Float(110f, 30f, 50, 200);//椭圆
paintEllipse2(e1,g);
}
//把一个单精度的圆根据其圆心旋转画地按一定间隔的角度画一个图案
public void paintEllipse2(Ellipse2D.Float e, Graphics2D g2) {
double x = e.width/2 + e.x;
double y = e.height/2 + e.y;
for (double i = 0; i < 360f; i+=10f) {
AffineTransform at = AffineTransform.getRotateInstance((Math.PI/180)*i,x,y);
g2.draw(at.createTransformedShape(e));
}
}
public static void main(String[] args) {
TestFrame2 tf = new TestFrame2();
}
}
import java.awt.*;
import java.awt.Graphics2D;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
public class TestFrame2 extends JFrame implements ActionListener{
private JButton jb;
public TestFrame2() {
setName("画直线");
setBounds(200,200,300,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jb = new JButton("按钮");
jb.addActionListener(this);
add(jb,BorderLayout.SOUTH);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
//获得窗口的pane再获得该pane的画笔
Graphics2D g = (Graphics2D) getContentPane().getGraphics();
//画直线
g.drawLine(10, 10, 40, 40);
g.setColor(Color.blue);
Ellipse2D.Float e1 = new Ellipse2D.Float(110f, 30f, 50, 200);//椭圆
paintEllipse2(e1,g);
}
//把一个单精度的圆根据其圆心旋转画地按一定间隔的角度画一个图案
public void paintEllipse2(Ellipse2D.Float e, Graphics2D g2) {
double x = e.width/2 + e.x;
double y = e.height/2 + e.y;
for (double i = 0; i < 360f; i+=10f) {
AffineTransform at = AffineTransform.getRotateInstance((Math.PI/180)*i,x,y);
g2.draw(at.createTransformedShape(e));
}
}
public static void main(String[] args) {
TestFrame2 tf = new TestFrame2();
}
}
追问
(Graphics2D) getContentPane()是神么意思呢??
追答
getContentPane()就是获得该窗口的Panel实例(JFrame窗口本身就有一个panel)。再由panel的getGraphics()方法获得画笔。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询