微微微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是什么

    评论

报告相同问题?

悬赏问题

  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 opencv 无法读取视频
  • ¥15 用matlab 实现通信仿真
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数