Java Swing, 在JPanel上添加JTable
程序员文章站
2024-02-01 14:38:34
...
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
public class MyJFrame extends JFrame {
private JPanel contentPane;
/**
* Create the frame.
*/
public MyJFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 400, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
// set the header of the table
String[] header = {"CurrencyName", "CurrencyNumber"};
// set the data of the table
String[][] data = {{"USD", "1000.00"}, {"GBP", "1000.00"}, {"EUR", "1000.00"}, {"CNY", "1000.00"}};
// create a table model
DefaultTableModel model = new DefaultTableModel(data, header);
// create a JTable object
JTable table = new JTable(model);
// set the style of the table
table.setGridColor(Color.BLACK);
table.setEnabled(false);
// must do: bind a JTable object to a JScrollPane object, otherwise the header of the table will not be displayed in the JPanel.
JScrollPane jScrollPane = new JScrollPane();
// key, crucial!
jScrollPane.setViewportView(table);
// set the position of the JScrollPane object
jScrollPane.setBounds(20, 20, 360, 100);
// add the JScrollPane object to JPanel
add(jScrollPane);
}
}