gpt4 book ai didi

java - 创建一个上面有文字的矩形

转载 作者:行者123 更新时间:2023-12-02 04:49:55 25 4
gpt4 key购买 nike

所以我试图在我的java项目中绘制一个矩形,由于某种原因我收到错误并且应用程序关闭。错误是 03-28 09:05:50.332: E/AndroidRuntime(4611): 致命异常: main03-28 09:05:50.332:E/AndroidRuntime(4611):进程:com.Tripp.thebasics,PID:461103-28 09:05:50.332: E/AndroidRuntime(4611): java.lang.NullPointerException: 尝试在空对象引用上调用虚拟方法“void android.graphics.Paint.setColor(int)”

package com.Tripp.thebasics;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

public class DrawingView extends View {
Paint paint;

public DrawingView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}

public DrawingView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}

public DrawingView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// TODO Auto-generated constructor stub
}

@Override
protected void onDraw(Canvas canvas){
super.onDraw(canvas);

Rect ourRect = new Rect();

ourRect.set(0,0,canvas.getWidth(),canvas.getHeight()/2 );
paint.setColor(Color.RED);

canvas.drawRect(ourRect, paint);
}

}

这是转到下面该类的按钮

public class JokeOfTheDay extends Activity {

DrawingView v;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
v = new DrawingView(this);
setContentView(v);

}



}

最佳答案

在尝试使用绘制变量之前,请在构造函数中初始化它。 paint = new Paint();

关于java - 创建一个上面有文字的矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29324098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com