要求:
在一个窗口中有两个Button,一个为Circle一个为Rectangle,点击CirckeButton,在窗口上出现
一个圆,点击RectangleButton出现一个矩形.以下是小弟写的程序,不知道那里错了,就是画不出东西...
小弟刚学,求教各位大虾!!
import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.awt.geom.*;
public class Cf { public static void main(String[] args) { Drawframe frame=new Drawframe(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.show(); } } class Drawframe extends JFrame { private static final int DW=400; private static final int DH=400; public Drawframe() { setTitle("CF"); setSize(DW,DH); Buttonpanel panel=new Buttonpanel(); Container content=getContentPane(); content.add(panel); } } class Drawpanel extends JPanel { Rectangle2D rect; Ellipse2D circle; Graphics2D g2; public void paintComponent(Graphics g) { super.paintComponent(g); g2=(Graphics2D)g; rect=new Rectangle.Double(100,100,200,150); double x=rect.getCenterX(); double y=rect.getCenterY(); double r=100; circle=new Ellipse2D.Double(); circle.setFrameFromCenter(x,y,x+r,y+r); } } class Buttonpanel extends JPanel { JButton CircleButton=new JButton("Circle"); JButton RectButton=new JButton("Rectangle"); public Buttonpanel () { add(CircleButton); add(RectButton); DrawAction draw=new DrawAction(); CircleButton.addActionListener(draw); RectButton.addActionListener(draw); }
private class DrawAction implements ActionListener { public void actionPerformed(ActionEvent event) { Drawpanel s=new Drawpanel(); Object source=event.getSource(); if(source==CircleButton) {repaint();s.g2.draw(s.circle);} else if (source==RectButton) {repaint();s.g2.draw(s.rect);} } } }