简体   繁体   中英

creating an uneditable jtable displayed in jframe

i have come across jtables today, as a nice way of representing information retrieved from a database, for example, like in the following code:

import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class JTableCreatingDemo {
  public static void main(String args[]) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Object rowData[][] = { { "Row1-Column1", "Row1-Column2", "Row1-Column3" },
        { "Row2-Column1", "Row2-Column2", "Row2-Column3" } };
    Object columnNames[] = { "Column One", "Column Two", "Column Three" };
    JTable table = new JTable(rowData, columnNames);

    JScrollPane scrollPane = new JScrollPane(table);
    frame.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(300, 150);
    frame.setVisible(true);

  }
}

the only thing i don't like about it is that if i click on the table entries, i can change them. i don't like this. i was wondering if there is a way that i can prevent this from happening?

You could use an AbstractTableModel , but that might be more work than you're prepared for, instead, use a DefaultTableModel and override it's isCellEditable method to return false

For example...

DefaultTableModel model = new DefaultTableModel(rowData, columnNames) {
    @Override
    public boolean isCellEditable(int row, int column) {
        return false;
    }
};
JTable table = new JTable(model);

See How to Use Tables for more details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM