19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

an array, or row data and column header names in vec<strong>to</strong>rs. Listing<br />

40.1 creates a table with the row data and column names (line 20)<br />

and places it in a scroll pane (line 23). The table is displayed<br />

in Figure 40.1.<br />

Listing 40.1 TestTable.java<br />

<br />

<br />

<br />

<br />

<br />

1 import javax.swing.*;<br />

2<br />

3 public class TestTable extends JApplet {<br />

4 // Create table column names<br />

5 private String[] columnNames =<br />

6 {"Country", "Capital", "Population in Millions", "Democracy"};<br />

7<br />

8 // Create table data<br />

9 private Object[][] data = {<br />

10 {"USA", "Washing<strong>to</strong>n DC", 280, true},<br />

11 {"Canada", "Ottawa", 32, true},<br />

12 {"United Kingdom", "London", 60, true},<br />

13 {"Germany", "Berlin", 83, true},<br />

14 {"France", "Paris", 60, true},<br />

15 {"Norway", "Oslo", 4.5, true},<br />

16 {"India", "New Delhi", 1046, true}<br />

17 };<br />

18<br />

19 // Create a table<br />

20 private JTable jTable1 = new JTable(data, columnNames);<br />

21<br />

22 public TestTable() {<br />

23 add(new JScrollPane(jTable1));<br />

24 }<br />

25 }<br />

NOTE<br />

<br />

Primitive type values such as 280 and true in line 10 are<br />

au<strong>to</strong>boxed in<strong>to</strong> new Integer(280) and new Boolean(true).<br />

JTable is a powerful control with a variety of properties that<br />

provide many ways <strong>to</strong> cus<strong>to</strong>mize tables. All the frequently used<br />

properties are documented in Figure 40.3. The au<strong>to</strong>ResizeMode<br />

property specifies how columns are resized (you can resize table<br />

columns but not rows). Possible values are:<br />

JTable.AUTO_RESIZE_OFF<br />

JTable.AUTO_RESIZE_LAST_COLUMN<br />

JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS<br />

JTable.AUTO_RESIZE_NEXT_COLUMN<br />

JTable.AUTO_RESIZE_ALL_COLUMNS<br />

The default mode is JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS.<br />

Initially, each column in the table occupies the same width (75<br />

pixels). With AUTO_RESIZE_OFF, resizing a column does not affect<br />

the widths of the other columns. With AUTO_RESIZE_LAST_COLUMN,<br />

4

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!