微微微love笑 2017-05-19 14:34 采纳率: 0%
浏览 1006

为啥空指针异常啊???

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

class Text extends JFrame
{
public static void main(String[] args)
{
Text t = new Text();
t.initBoard();

}
public void initBoard()
{
    setTitle("画板");
    setLayout(new FlowLayout());
    this.getContentPane().setBackground(Color.WHITE);
    setBounds(400, 20, 500, 500);
    ButtonGroup group = new ButtonGroup();
    String names[] =
    { "Line", "Hoval", "Soval", "Hrec", "Srec", "Pol" };
    for (int i = 0; i < names.length; i++)
    {
        JRadioButton jrb = new JRadioButton(names[i]);
        jrb.setActionCommand(names[i]);
        group.add(jrb);
        add(jrb);
        if (i == 0)
        {
            jrb.setSelected(true);
        }

    }
    Graphics g = this.getGraphics();
    DrawListener3 d = new DrawListener3(g, group);
    addMouseListener(d);

    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
}

}

class DrawListener3 implements MouseListener
{
private Graphics g;
private ButtonGroup group;
private int x1, x2, y1, y2;
private String type = "Line";
public DrawListener3(Graphics g, ButtonGroup group)
{
this.g = g;
this.group = group;
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
ButtonModel bm = group.getSelection();
type = bm.getActionCommand();
x1 = e.getX();
y1 = e.getY();
System.out.println(x1+"----"+y1);
}

@Override
public void mouseReleased(MouseEvent e)
{
    x2 = e.getX();
    y2 = e.getY();
    System.out.println(x2+"----"+y2);
    if (type.equals("Line"))
    {
        g.drawLine(x1, y1, x2, y2);
    } else if (type.equals("Hrec"))
    {
        g.drawRect(x1, y1, Math.abs(x2 - x1), Math.abs(y2 - y1));
    } else if (type.equals("Srec"))
    {
        g.fillRect(x1, y1, Math.abs(x2 - x1), Math.abs(y2 - y1));
    } else if (type.equals("Hoval"))
    {
        g.drawOval(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x1 - x2), Math.abs(y1 - y2));
    } else if (type.equals("Soval"))
    {
        g.fillOval(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x1 - x2), Math.abs(y1 - y2));
    } else if (type.equals("Pol"))
    {
        int a[] =
        { 200, 400, 300, 50, 60 };
        int b[] =
        { 450, 200, 100, 330, 400 };
        g.drawPolygon(a, b, 5);
    }


}

}
图片说明

  • 写回答

2条回答 默认 最新

  • threenewbee 2017-05-19 16:30
    关注

    调试下type = bm.getActionCommand();type是什么

    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮