当前位置: 代码迷 >> Java相关 >> [求助]求助 一道java习题
  详细解决方案

[求助]求助 一道java习题

热度:266   发布时间:2004-12-20 16:17:00.0
[求助]求助 一道java习题

题目要求: 在一个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(); } } 不知道那里错了.请哪位大侠帮帮忙.

搜索更多相关的解决方案: java  习题  

----------------解决方案--------------------------------------------------------
Drawpanel 的对象 s 未实例化;因此发生java.lang.NullPointerException异常。
----------------解决方案--------------------------------------------------------

----------------解决方案--------------------------------------------------------
运行一下啊
偶还没那个功力看懂它

----------------解决方案--------------------------------------------------------
编译时没错
运行时
java.lang.ClassCastException
        at sun.applet.AppletPanel.createApplet(AppletPanel.java:617)
        at sun.applet.AppletPanel.runLoader(AppletPanel.java:546)
        at sun.applet.AppletPanel.run(AppletPanel.java:298)
        at java.lang.Thread.run(Thread.java:534)
是啥意思?
----------------解决方案--------------------------------------------------------
类型转换错误
----------------解决方案--------------------------------------------------------
把 Drawpanel s; 改为 Drawpanel s = new Drawpanel();  后

编译运行没出问题,但画不出矩形或圆


----------------解决方案--------------------------------------------------------
  相关解决方案