微微微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 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配