题目要求: 在一个JComboBox选中其中的Rect,在面板内画个矩形,选中Circle 则画个圆.
以下是小弟写的程序:
import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.geom.*; public class DrawCombo { public static void main(String[] args) { Drawframe frame=new Drawframe(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.show(); } } class Drawframe extends JFrame { Drawpanel s; private JComboBox drawCombo; public Drawframe() { setTitle("DrawFrame"); setSize(300,200); drawCombo=new JComboBox(); drawCombo.setEditable(false); drawCombo.addItem("Circle"); drawCombo.addItem("Rect"); drawCombo.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { String s2=(String)drawCombo.getSelectedItem(); if(s2=="Circle"){ s.drawf(Drawpanel.CIRCLE);} else if (s2=="Rect"){s.drawf(Drawpanel.SQUARE);} } }); Drawpanel panel=new Drawpanel(); Container contentPane=getContentPane(); JPanel comboPanel=new JPanel(); comboPanel.add(drawCombo); contentPane.add(panel); contentPane.add(comboPanel,BorderLayout.SOUTH); } }
class Drawpanel extends JPanel { public final static int CIRCLE = 1,SQUARE = 2; private int shape;
public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D f2=(Graphics2D)g; Rectangle2D rect=new Rectangle.Double(100,100,200,150); double x=rect.getCenterX(); double y=rect.getCenterY(); double r=50; Ellipse2D circle=new Ellipse2D.Double(); circle.setFrameFromCenter(x,y,x+r,y+r); if ( shape == CIRCLE) {f2.draw(circle);} else if (shape == SQUARE ) {f2.draw(rect);} } public void drawf (int shapeToDraw) { shape = shapeToDraw; repaint(); } } 不知道那里错了.请哪位大侠帮帮忙.
急