jtable selectionlistener不起作用

时间:2016-11-13 12:11:12

标签: java swing

我已经写了一个带有表格的小程序,我已经尝试并阅读了很多文档和答案,但我真的不明白我做错了什么,因为第4列仍然是可编辑的,没有事件是当我选择行时触发...

主要

public class Main extends JFrame{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;


    private JLabel banner;

    private String[] tecnici;
    private String[] columnNames;
    private Object[][] data;
    private JTable table;
    Map<String,List<Cliente>> clientiList;
    private Container pane = getContentPane();
    GroupLayout gl = new GroupLayout(pane);

    Main(){
        init();
    }

    private void init(){
        ImageIcon webIcon = new ImageIcon(Constants.WORK_GUI_LOGO);
        setIconImage(webIcon.getImage());

        setTitle(Constants.WORK_GUI_TITLE);
        setSize(300, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        banner=new JLabel("", webIcon, JLabel.CENTER);

        MenuBar menu=new MenuBar();

        setJMenuBar(menu.getMenuBar());

        System.out.println("Leggo i tecnici dal db");
        tecnici=new String[] {"Tarzan","Cita","Jane"};

        clientiList=new HashMap();

        for(String tec:tecnici){
            List<Cliente> l=new ArrayList<>();
            Cliente c=new Cliente();
            c.setConsultivoIncassi(1000);
            c.setNome("Clnl ross");
            c.setPreventivoIncassi(1000);
            l.add(c);
            c=new Cliente();
            c.setConsultivoIncassi(2000);
            c.setNome("Clnl ross");
            c.setPreventivoIncassi(2000);
            l.add(c);
            clientiList.put(tec, l);
        }
        data=createTableFromMap(clientiList);
        columnNames=new String[]{"Tecs","Customer","count","credit"};
        table=new JTable(data, columnNames){
            public boolean isCellEditable(int row, int col) {
                //where i want to make editable only the 4th col
                return col==4;
            }

        };
        table.getSelectionModel().addListSelectionListener(new TableSelectionListener());

        createWindowLayout(
                banner,
                new JLabel("Tecnici"),
                new JCheckBox(tecnici[0]),
                new JCheckBox(tecnici[1]),
                new JCheckBox(tecnici[2]),
                new JTable(data, columnNames));
    }

    public void createWindowLayout(JComponent... arg) {

        pane = getContentPane();
        gl = new GroupLayout(pane);
        pane.setLayout(gl);        

        gl.setAutoCreateContainerGaps(true);
        gl.setAutoCreateGaps(true);

        gl.setHorizontalGroup(gl.createParallelGroup()
            .addComponent(arg[0])
            .addGroup(gl.createSequentialGroup()
                    .addComponent(arg[1])
                    .addGroup(gl.createParallelGroup(Alignment.LEADING)
                        .addComponent(arg[2])
                        .addComponent(arg[3])
                        .addComponent(arg[4])                                   
                        )
                    )   
            .addComponent(arg[5])
        );

        gl.setVerticalGroup(gl.createSequentialGroup()
            .addComponent(arg[0])
            .addGroup(gl.createParallelGroup()
                .addComponent(arg[1])
                .addComponent(arg[2]))
            .addComponent(arg[3])
            .addComponent(arg[4])
            .addComponent(arg[5])
        );

        pack();
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
                Main ex = new Main();
                ex.setVisible(true);
        });
    }

    private Object[][] createTableFromMap(Map<String,List<Cliente>> clienti ){
        Iterator it= clienti.entrySet().iterator();
        Object[][] tabella=new Object[clienti.size()][4];
        int counter=0;
        while(it.hasNext()){
            Map.Entry entry=(Map.Entry) it.next();
            for(Cliente c:(List<Cliente>)entry.getValue()){
                tabella[counter]=new Object[]{entry.getKey(),
                        c.getNome(),
                        c.getPreventivoIncassi(),
                        c.getConsultivoIncassi()};
            }
            counter++;
        }
        return tabella;
    }

    class TableSelectionListener implements ListSelectionListener{

        @Override
        public void valueChanged(ListSelectionEvent arg0) {
            String selectedData = null;

            int[] selectedRow = table.getSelectedRows();
            int[] selectedColumns = table.getSelectedColumns();

            for (int i = 0; i < selectedRow.length; i++) {
                for (int j = 0; j < selectedColumns.length; j++) {
                    selectedData = (String) table.getValueAt(selectedRow[i], selectedColumns[j]);
                  }
            }
            System.out.println("Selected: " + selectedData);
        }

    }
}

2 个答案:

答案 0 :(得分:2)

仔细查看您的代码并在此处发表评论:

        public boolean isCellEditable(int row, int col) {
            //where i want to make editable only the 4th row
            return col==4;
        }

评论不符合代码吗?你的方法是检查col应该检查行,不是吗? e.g:

        public boolean isCellEditable(int row, int col) {
            //where i want to make editable only the 4th row
            return row == 4;  // ****** note change ******
        }

MCVE&#39;代码:

import java.awt.Container;
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.event.*;

public class Main extends JFrame {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private JLabel banner;

    private String[] tecnici;
    private String[] columnNames;
    private Object[][] data;
    private JTable table;
    Map<String,List<Cliente>> clientiList;
    private Container pane = getContentPane();
    GroupLayout gl = new GroupLayout(pane);

    Main(){
        init();
    }

    private void init(){
        ImageIcon webIcon = new ImageIcon(Constants.WORK_GUI_LOGO);
        setIconImage(webIcon.getImage());

        setTitle(Constants.WORK_GUI_TITLE);
        setSize(300, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        banner=new JLabel("", webIcon, JLabel.CENTER);

        MenuBar menu=new MenuBar();

        setJMenuBar(menu.getMenuBar());

        System.out.println("Leggo i tecnici dal db");
        tecnici=new String[] {"Tarzan","Cita","Jane"};

        clientiList=new HashMap<>();

        for(String tec:tecnici){
            List<Cliente> l=new ArrayList<>();
            Cliente c=new Cliente();
            c.setConsultivoIncassi(1000);
            c.setNome("Clnl ross");
            c.setPreventivoIncassi(1000);
            l.add(c);
            c=new Cliente();
            c.setConsultivoIncassi(2000);
            c.setNome("Clnl ross");
            c.setPreventivoIncassi(2000);
            l.add(c);
            clientiList.put(tec, l);
        }
        data=createTableFromMap(clientiList);
        columnNames=new String[]{"Tecs","Customer","count","credit"};
        table=new JTable(data, columnNames){
            public boolean isCellEditable(int row, int col) {
                //where i want to make editable only the 4th row
                return col==4;
            }

        };
        table.getSelectionModel().addListSelectionListener(new TableSelectionListener());

        createWindowLayout(
                banner,
                new JLabel("Tecnici"),
                new JCheckBox(tecnici[0]),
                new JCheckBox(tecnici[1]),
                new JCheckBox(tecnici[2]),
                new JTable(data, columnNames));
    }

    public void createWindowLayout(JComponent... arg) {

        pane = getContentPane();
        gl = new GroupLayout(pane);
        pane.setLayout(gl);        

        gl.setAutoCreateContainerGaps(true);
        gl.setAutoCreateGaps(true);

        gl.setHorizontalGroup(gl.createParallelGroup()
            .addComponent(arg[0])
            .addGroup(gl.createSequentialGroup()
                    .addComponent(arg[1])
                    .addGroup(gl.createParallelGroup(Alignment.LEADING)
                        .addComponent(arg[2])
                        .addComponent(arg[3])
                        .addComponent(arg[4])                                   
                        )
                    )   
            .addComponent(arg[5])
        );

        gl.setVerticalGroup(gl.createSequentialGroup()
            .addComponent(arg[0])
            .addGroup(gl.createParallelGroup()
                .addComponent(arg[1])
                .addComponent(arg[2]))
            .addComponent(arg[3])
            .addComponent(arg[4])
            .addComponent(arg[5])
        );

        pack();
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
                Main ex = new Main();
                ex.setVisible(true);
        });
    }

    private Object[][] createTableFromMap(Map<String,List<Cliente>> clienti ){
        Iterator it= clienti.entrySet().iterator();
        Object[][] tabella=new Object[clienti.size()][4];
        int counter=0;
        while(it.hasNext()){
            Map.Entry entry=(Map.Entry) it.next();
            for(Cliente c:(List<Cliente>)entry.getValue()){
                tabella[counter]=new Object[]{entry.getKey(),
                        c.getNome(),
                        c.getPreventivoIncassi(),
                        c.getConsultivoIncassi()};
            }
            counter++;
        }
        return tabella;
    }

    class TableSelectionListener implements ListSelectionListener{

        @Override
        public void valueChanged(ListSelectionEvent arg0) {
            String selectedData = null;

            int[] selectedRow = table.getSelectedRows();
            int[] selectedColumns = table.getSelectedColumns();

            for (int i = 0; i < selectedRow.length; i++) {
                for (int j = 0; j < selectedColumns.length; j++) {
                    selectedData = (String) table.getValueAt(selectedRow[i], selectedColumns[j]);
                  }
            }
            System.out.println("Selected: " + selectedData);
        }

    }

    private static class Cliente {

        private String nome;
        private int preventivoIncassi;
        private int consultivoIncassi;

        public String getNome() {
            return nome;
        }

        public void setPreventivoIncassi(int preventivoIncassi) {
            this.preventivoIncassi = preventivoIncassi;            
        }

        public void setNome(String nome) {
            this.nome = nome;
        }

        public void setConsultivoIncassi(int consultivoIncassi) {
            this.consultivoIncassi = consultivoIncassi;
        }

        public int getConsultivoIncassi() {
            return consultivoIncassi;
        }

        public int getPreventivoIncassi() {
            return preventivoIncassi;
        }

    }

    private static class Constants {

        public static final String WORK_GUI_LOGO = null;
        public static final String WORK_GUI_TITLE = null;

    }

    private static class MenuBar {

        public JMenuBar getMenuBar() {
            // TODO Auto-generated method stub
            return null;
        }

    }
}

答案 1 :(得分:2)

return col==4;

你有没有做过任何基本的调试,看看“col”变量的值是多少?当您遇到问题时,您应该做的第一件事是使用System.out.println(...)来显示该值,以便您可以确定您的if条件是否正确。

如果你这样做,你会注意到两件事:

  1. 您没有得到任何输出,因为代码永远不会被执行。
  2. 即使是执行它也行不通,因为你的表只有4列而Java使用0基于偏移,如果你应该使用“3”作为第4列。
  3. 永远不会执行代码的原因是因为你有两个表。您使用重写的isCellEditable()方法创建的第一个。但是你永远不会将该表添加到GUI中,因此这是死代码。然后创建一个添加到GUI的第二个表:

    new JCheckBox(tecnici[2]),
    new JTable(data, columnNames));
    

    所以摆脱上面的陈述,只需使用:

    new JCheckBox(tecnici[2]),
    //new JTable(data, columnNames));
    table);
    

    由于表变量是具有自定义方法的表。