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

    评论

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决