[英]When i try to run my program, the GUI won't load and I can't figure out why
當不使用數組或數組列表時,這部分代碼可以正常工作。
import javax.swing.*;
public class GUI
{
public static void main(String[] args) {
JFrame frame = new JFrame("01");
frame.getContentPane().add(new Panel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setResizable(false);
frame.setVisible(true);
}
}
當不使用數組或數組列表時,這部分代碼可以正常工作
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Panel extends JPanel
{
private Shapes shapes;
public Panel () {
setFocusable(true);
requestFocusInWindow();
setPreferredSize(new Dimension(500,500));
}
public void paintComponent(Graphics gc) {
super.paintComponent(gc);
shapes.draw(gc);
}
}
在這個類中,如果我不使用數組或數組列表,它將運行良好,但不能使其與它們一起使用。
import java.awt.*;
import java.util.ArrayList;
import javax.swing.*;
import java.awt.event.*;
public class Shapes
{
ArrayList <int[]> blocks = new ArrayList <int[]>();
int[] arr;
int w,x,y,z;
public void draw(Graphics gc) {
gc.setColor(Color.black);
blocks();
for(int i=0; i<blocks.size()-1; i++){
w=blocks.get(i)[0];
x=blocks.get(i)[1];
y=blocks.get(i)[2];
z=blocks.get(i)[3];
gc.fillRect(w, x, y, z);
}
}
public void blocks() {
popBlocks(100,500,300,30);
popBlocks(300,400,150,30);
popBlocks(500,300,150,30);
popBlocks(700,200,150,30);
popBlocks(900,100,150,30);
}
private void popBlocks(int a, int b, int c, int d) {
arr[0] = a;
arr[1] = b;
arr[2] = c;
arr[3] = d;
blocks.add(arr);
}
}
Panel#paintComponent
NullPointerException
,因為未初始化shapes
。
public class Panel extends JPanel {
private Shapes shapes;
public Panel() {
shapes = new Shapes();
Shapes#popBlocks
NullPointerException
,因為未初始化arr
public class Shapes
{
//...
int[] arr = new int[4];
//...
但是等等,那只能畫一個形狀嗎?! 這一切都是用一些新值更新arr
實例並將其添加到blocks
List
private void popBlocks(int a, int b, int c, int d) {
arr[0] = a;
arr[1] = b;
arr[2] = c;
arr[3] = d;
blocks.add(arr);
}
這意味着您有5個塊,其值分別為900,100,150,30
。
而不是使用實例字段,您應該使arr
成為方法級別的字段,例如...
public class Shapes
{
//...
//int[] arr;
//...
private void popBlocks(int a, int b, int c, int d) {
int[] arr = new int[4];
arr[0] = a;
arr[1] = b;
arr[2] = c;
arr[3] = d;
blocks.add(arr);
}
}
同樣, draw
方法中的for-loop
是錯誤的,例如,它應該從0-size - 1
而不是0-size - 2
循環。
public void draw(Graphics gc) {
//...
for(int i=0; i < blocks.size(); i++){
//...
for(int i=0; i<blocks.size()-1; i++){
for循環上的條件應該是錯誤的
for(int i=0; i<=blocks.size()-1; i++) .
or
for(int i=0; i<blocks.size(); i++)
您可能想嘗試一下。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.