I recently started my adventure with Java, I use IntelliJ IDEA 13.1.1. My problem is: When I want to paint an array on the screen it's being painted as it was transposed.
import java.awt.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class Main extends JPanel
{
public int tab[][]=new int[3][6];
public static final int CANVAS_WIDTH=1280;
public static final int CANVAS_HEIGHT=1024;
public Main()
{
for(int i=0; i<3; i++)
for(int j=0;j<6;j++)
tab[i][j]=3*j+i*2;
tab[1][4]=99;
setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
setBackground(Color.BLACK);
g.setColor(Color.WHITE);
for(int i=0; i<3; i++)
for(int j=0;j<6;j++)
g.drawString(tab[i][j]+"", 20+i*20, 20+j*20);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
JFrame frame=new JFrame("tests");
frame.setContentPane(new Main());
frame.pack();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
As a result on screen I get:
0 2 4
3 5 7
6 8 10
9 11 13
12 99 16
15 17 19
When I display the array outside painting function using System.out.print I get:
0 3 6 9 12 15
2 5 8 11 99 17
4 7 10 13 16 19
Does anyone know what is causing this? It makes working with arrays that I want to paint data from not as intuitive and quite inconvenient.
Try writing your method like this:
g.drawString(tab[i][j]+"", 20+j*20, 20+i*20);
(i and j are swapped in the last two arguments)