JTable
![](zzz/editor/img/code.gif)
程序代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PrintJTable
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new PlanetTableFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class PlanetTableFrame extends JFrame
{
public PlanetTableFrame()
{
setTitle("PlanetTable");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
final JTable table = new JTable(cells, columnNames);
table.setAutoCreateRowSorter(true);
add(new JScrollPane(table), BorderLayout.CENTER);
JButton printButton = new JButton("Print");
printButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
try
{
table.print();
}
catch (java.awt.print.PrinterException e)
{
e.printStackTrace();
}
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(printButton);
add(buttonPanel, BorderLayout.SOUTH);
}
private Object[][] cells = { { "Mercury", 240, 0, false, Color.yellow },
{ "Venus", 600, 0, false, Color.yellow }, { "Earth", 6378.0, 1, false, Color.blue },
{ "Mars", 3397.0, 2, false, Color.red }, { "Jupiter", 71492.0, 16, true, Color.orange },
{ "Saturn", 6020, 18, true, Color.orange },
{ "Uranus", 2550, 17, true, Color.blue }, { "Neptune", 2470, 8, true, Color.blue },
{ "Pluto", 110, 1, false, Color.black } };
private String[] columnNames = { "Planet", "Radius", "Moons", "Gaseous", "Color" };
private static final int DEFAULT_WIDTH = 400;
private static final int DEFAULT_HEIGHT = 200;
}