我想顯示一個數組,但我有問題。如何以圖形方式重新繪製字符串數組而不重疊文本?
在我填滿數組之前,鞋子「null」,但填充數組後,它會繪製「null」,這使得它很難閱讀。
我怎樣才能讓畫布在我填滿陣列後清理並重繪。
這是到目前爲止我的代碼:
public class wordManager extends JFrame
{
String[] array = new String[15];
private BufferedImage buffered;
public wordManager()
{
super("Word Managery");
setSize(300,600);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint(Graphics window)
{
if(buffered==null)
buffered = (BufferedImage)(createImage(getWidth(),getHeight()));
Graphics windowTemp = buffered.createGraphics();
int y = 50;
for(int i = 0; i<array.length; i++)
{
windowTemp.drawString(array[i] + "", 10,y);
y+=10;
}
window.drawImage(buffered, 0, 0, null);
}
public void read(String filename) throws IOException
{
String word;
int i = 0;
Scanner file = new Scanner(new File(filename+".txt"));
while(file.hasNext())
{
word = file.next();
array[i] = word;
i++;
}
repaint();
}
public void scramble()
{
for(int i=0;i<array.length;i++)
{
int a = (int) (Math.random()*array.length);
String b = array[i];
array[i] = array[a];
array[a] = b;
}
repaint();
}
public void sort()
{
for (int i = 1; i < array.length; i++)
{
int s = i-1;
for (int j = i; j < array.length; j++)
{
if (array[j].compareTo(array[s]) < 0)
{
s = j;
}
}
String temp = array[i-1];
array[i-1] = array[s];
array[s] = temp;
}
repaint();
}
public void write() throws IOException
{
PrintWriter fileOut = new PrintWriter(new FileWriter("out.txt"));
for(int i = 0; i<array.length; i++)
{
fileOut.println(array[i]);
}
fileOut.close();
}
public void printArray()
{
for(String term : array)
{
System.out.println(term);
}
}
}
public class runner
{
public static void main(String args[]) throws IOException
{
wordManager run = new wordManager();
Scanner keyboard = new Scanner(System.in);
System.out.println("In put file name");
String filename = keyboard.next();
run.read(filename);
System.out.println("");
run.printArray();
System.out.println("");
System.out.println("Enter 1 if you want to sort\n");
System.out.println("Enter 2 if you want to scramble");
int selection = keyboard.nextInt();
if(selection == 1)
{
run.sort();
}
if(selection == 2)
{
run.scramble();
}
run.printArray();
System.out.println("");
run.write();
}
}
我一直使用paintComponent(),但是我的老師給我們提供了這個新的代碼 現在我該如何克服我的問題 我是初學者 – user1972355 2013-02-11 04:32:29
如果你不能改變代碼,調用'super.paint(window)'作爲'paint'方法的第一行,然後找一個新老師; – MadProgrammer 2013-02-11 04:34:13
+ 1爲線高度計算。我打算編輯我的帖子,但你打敗了我:) – camickr 2013-02-11 04:43:18