Quellcode
- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.table.*;
- class tableExample {
- DefaultTableModel tabModel;
- JTable table;
- public static void main(String[] args) {
- tableExample t = new tableExample();
- }
- public tableExample() {
- String[] columnNames = {"Column1", "Column2", "Column3"};
- Object[][] data = {
- { "A1", "A2", "A3" },
- { "B1", "B2", "B3" },
- { "C1", "C2", "C3" },
- { "D1", "D2", "D3" }
- };
- tabModel = new DefaultTableModel(data, columnNames);
- table = new JTable(tabModel);
- JScrollPane scrollPane = new JScrollPane(table);
- JPanel buttonPanel = new JPanel();
- JButton cmdAdd = new JButton("Neue Zeile");
- JButton cmdDelete = new JButton("Markierte Zeile löschen");
- buttonPanel.add(cmdAdd);
- buttonPanel.add(cmdDelete);
- cmdAdd.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- Object[] tmp = {"","",""};
- tabModel.addRow(tmp);
- }
- });
- cmdDelete.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- if (table.getSelectedRow() != -1) {
- tabModel.removeRow(table.getSelectedRow());
- }
- }
- });
- JPanel mainPanel = new JPanel();
- JFrame frame = new JFrame("JTable mit JModel");
- mainPanel.setLayout(new BorderLayout());
- mainPanel.add(scrollPane, "Center");
- mainPanel.add(buttonPanel, "South");
- frame.getContentPane().add(mainPanel);
- frame.pack();
- frame.setVisible(true);
- }
- }
16.833 mal gelesen