我試圖製作一個簡單的顏色處理程序,該程序允許您更改窗口中某個框的顏色。我使用一些預設的顏色,將它們從文件中讀入我專門設置用於包含這些值的類中。我使用數組來包含所有預設值,當我嘗試訪問該數組的各個元素時,我總是收到一個空指針異常。這是我第一次嘗試使用java,所以我認爲我犯了一個頭腦發熱的錯誤。 這裏是我的代碼:嘗試訪問java中另一個類中的整數時出現空指針
package color.sampler;
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;
public class ColorSampler extends JFrame
{
protected ColorFrame sampler;
public JList colorList;
protected colors [] listOfColors;
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException
{
new ColorSampler("ColorSampler");
}
public ColorSampler(String title) throws IOException
{
super(title);
setBounds(100,100,300,300);
addWindowListener(new WindowDestroyer());
sampler = new ColorFrame();
getContentPane().setLayout(null);
getContentPane().add(sampler);
sampler.setBounds(10,10,270,200);
FileInputStream stream = new FileInputStream("C:\\java input\\input.txt");
InputStreamReader reader;
reader = new InputStreamReader(stream);
StreamTokenizer tokens = new StreamTokenizer(reader);
int numColors, counter;
numColors = 11;
counter = 0;
listOfColors = new colors[numColors];
while(tokens.nextToken() != tokens.TT_EOF)
{
listOfColors[counter].name = (String)tokens.sval;
tokens.nextToken();
listOfColors[counter].r = (int)tokens.nval;
System.out.println(listOfColors[counter].r);
tokens.nextToken();
listOfColors[counter].g = (int)tokens.nval;
tokens.nextToken();
listOfColors[counter].b = (int)tokens.nval;
counter++;
}
stream.close();
colorList = new JList();
colorList.addListSelectionListener(new ListHandler());
String colorString[];
colorString = new String[numColors];
for(counter = 0; counter < numColors; counter++)
{
colorString[counter] = listOfColors[counter].name;
}
colorList.setListData(colorString);
getContentPane().add(colorList);
setVisible(true);
// TODO code application logic here
}
private class ListHandler implements ListSelectionListener
{
@Override
public void valueChanged(ListSelectionEvent e)
{
if(e.getSource() == colorList)
{
if(!e.getValueIsAdjusting())
{
int i = colorList.getSelectedIndex();
String s = (String) colorList.getSelectedValue();
System.out.println("Position " + i + " selected: " + s);
}
}
}
}
}
和我使用存儲的值類:
public class colors
{
public int r, g, b;
public String name;
public colors()
{
r = 0;
g = 0;
b = 0;
name = "bob";
}
}
所以,我將如何解決這個問題引起的,當我嘗試訪問的第一個元素的名稱在數組中?
在哪一行,你越來越NPE? –
你可以PLZ張貼錯誤日誌,控制檯輸出 –
在哪些語句你是例外。請在上面的評論中寫下 –