Saturday 26 April 2014

Java: Array Tutorial

public class ArrayBasic
{
 public static void main(String[] args)
{
//Declare an int array of size 100
int[] array = new int[100];

//insert elements using for loop
for(int i= 0; i<=99; i++)
{
array[i] = i;
}

//display elements
for(int i = 0; i <=99; i++)
{
System.out.println("Index" + i + " =" + array[i]);
}
}
}

Wednesday 2 April 2014

JTable Example

import javax.swing.*;
import java.awt.*;

@SuppressWarnings("serial")
public class JTableExample extends JPanel
{
public JTableExample()
{
super(new GridLayout(1, 0));

JTable table = new JTable(5, 4);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);

Color light_blue = new Color(205, 235, 255);
scrollPane.setBackground(light_blue);
scrollPane.getViewport().setBackground(light_blue);
table.getTableHeader().setBackground(light_blue);
}

public static void createAndShowGUI()
{
JFrame frame = new JFrame("JTableExample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JTableExample newContentPane = new JTableExample();
frame.setContentPane(newContentPane);

frame.pack();
frame.setVisible(true);
}
}

public class Driver
{
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
JTableExample.createAndShowGUI();
}
});
}
}


Java: Changing JTable's Background Color in a JScrollpane

If a JTable is being displayed in a JScrollPane and the table shows only few rows of data and the rest of table is empty. Changing the color of the empty table space wont work with setBackground(...). To do this

JTable#setFillsViewportHeight(true);

or

JScrollPane#getViewport().setBackground(JTable#getBackground());

or you can to fits JScrollPanes JViewport to the JTables view by

JTable#setPreferredScrollableViewportSize(JTable#getPreferredSize());

This solution is taken from stackoverflow.