Right so I have a pretty simple code that draws the contents of a 2D array onto a panel and the panel is placed onto a frame. The array is of type String and just houses a number of different fruit. The problem is that when the contents is painted onto the panel it flashes up and then disappears right away - why is this?
I dont repaint the code anywhere - below are the two classes:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import javax.swing.*;
public class Cell_JPanel extends JPanel
{
private int x = 0, y = 15;
private String [][] twoDCells = {
{"Apples", "Oranges", "Bananas"},
{"Cherries", "Plums", "Nectarines"},
{"Coconuts", "Mango", "Dragon Fruit" },
{"Blueberries", "Raspberries", "Poisonberries"}
};
public Cell_JPanel()
{
setBackground( Color.WHITE );
setDoubleBuffered( true );
}
public void paint(Graphics g)
{
super.paint( g );
Graphics2D g2 = ( Graphics2D )g;
for( int i = 0; i < 4; i++ )
{
for( int j = 0; j < 3; j++ )
{
g2.drawString( twoDCells[i][j], x, y ) ;
y += 30;
}
}
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
}
Second class:
import javax.swing.*;
public class Cell_JFrame extends JFrame
{
public Cell_JFrame()
{
add( new Cell_JPanel() );
setDefaultCloseOperation( EXIT_ON_CLOSE );
setTitle( "Cells" );
setSize( 450,150 );
setVisible( true );
setLocationRelativeTo( null );
setResizable( false );
}
public static void main(String [] args)
{
new Cell_JFrame();
}
}