Java Eclipse Jtable单元格/列 [英] Java Eclipse Jtable Cell / Column

查看:75
本文介绍了Java Eclipse Jtable单元格/列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于Java Kepler Eclipse和Jtable,我试图做到这一点,以便在选择特定表单元格时,该单元格可以用作editorPane;或让整个专栏都充当editorPane.当我单击COMMENTS列上的单元格时,该行会放大,但无法使其用作editorPane.我的项目实际上是非常不同的,但是我用表格编写了这个迷你模型,因此您可以复制,粘贴和运行它,以查看单击COMMENTS单元格时出了什么问题.

for Java Kepler Eclipse and Jtable, I am trying to make it so as when a specific table cell is selected, that cell will work as an editorPane; or have the whole column work as editorPane. When I click a cell on column COMMENTS it enlargens the row but I cant get it to work as an editorPane. My project is actualy very different but I wrote this mini one with the table so you can copy, paste and run it to see exactly what the problem is when you click on a COMMENTS cell.

我试图使该列成为editorPane的开始,就像我使该列使用checkBox完成一样,但它不起作用或我做错了.我也尝试了cellRenderer,但我也无法使之工作.

I tried to make the column an editorPane to begin with like I made the column DONE with checkBox, but it doesnt work or I am doing it wrong. I also tried cellRenderer but I couldnt make that work either.

整个列是用作editorPane还是只是所选单元格都没有关系,只要它更容易,只要它起作用就可以

Whether the whole column works as an editorPane or just the selected cell it doesnt matter, whatever is easier and as long as it works

import javax.swing.*;
import javax.swing.table.*;    
import java.awt.*;
public class JavaTestOne {
    JFrame frmApp;
    private JTable table;
    private JCheckBox checkbox;
    DefaultTableModel model;
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    JavaTestOne window = new JavaTestOne();
                    window.frmApp.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });  
    }
    public JavaTestOne() {  
        initialize();
    }
    private void initialize() {
        frmApp = new JFrame();
        frmApp.getContentPane().setFont(new Font("Tahoma", Font.PLAIN, 13));
        frmApp.setBounds(50, 10, 1050, 650);
        frmApp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmApp.getContentPane().setLayout(new CardLayout(0, 0));
        frmApp.setTitle("App");
        {
            JScrollPane scrollPane = new JScrollPane();
            scrollPane.setBounds(0, 42, 984, 484);
            frmApp.add(scrollPane);
            {
                table = new JTable();
                table.setFillsViewportHeight(true);
                Object[][] data = {
                        {"I01", "Tom",new Boolean(false), ""},
                        {"I02", "Jerry",new Boolean(false), ""},
                        {"I03", "Ann",new Boolean(false), ""}};
                String[] cols = {"ID","NAME","DONE","COMMENTS"};
                model = new DefaultTableModel(data, cols) {
                    private static final long serialVersionUID = -7158928637468625935L;

                    public Class getColumnClass(int column) {
                        return getValueAt(0, column).getClass();
                    }
                };
                table.setModel(model);
                table.setRowHeight(20);

                table.addMouseListener(new java.awt.event.MouseAdapter() {
                    public void mouseClicked(java.awt.event.MouseEvent evt) {
                        int row = table.rowAtPoint(evt.getPoint());
                        int col = table.columnAtPoint(evt.getPoint());
                        table.setRowHeight(20);
                        if(col==3){
                            table.setRowHeight(row, 100);
                            //this is where I need it to work as an editorPane if it is only for the selected cell
                        }
                    }
                });
                table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
                scrollPane.setViewportView(table);
                checkbox = new JCheckBox("OK");
                checkbox.setHorizontalAlignment(SwingConstants.CENTER);
                checkbox.setBounds(360, 63, 97, 23);
            }
        }
    }
}

推荐答案

另一种方法是显示一个弹出窗口来编辑单元格:

Another alternative is to display a popup window to edit the cell:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;

/*
 * The editor button that brings up the dialog.
 */
//public class TablePopupEditor extends AbstractCellEditor
public class TablePopupEditor extends DefaultCellEditor
    implements TableCellEditor
{
    private PopupDialog popup;
    private String currentText = "";
    private JButton editorComponent;

    public TablePopupEditor()
    {
        super(new JTextField());

        setClickCountToStart(1);

        //  Use a JButton as the editor component

        editorComponent = new JButton();
        editorComponent.setBackground(Color.white);
        editorComponent.setBorderPainted(false);
        editorComponent.setContentAreaFilled( false );

        // Make sure focus goes back to the table when the dialog is closed
        editorComponent.setFocusable( false );

        //  Set up the dialog where we do the actual editing

        popup = new PopupDialog();
    }

    public Object getCellEditorValue()
    {
        return currentText;
    }

    public Component getTableCellEditorComponent(
        JTable table, Object value, boolean isSelected, int row, int column)
    {

        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                popup.setText( currentText );
//              popup.setLocationRelativeTo( editorComponent );
                Point p = editorComponent.getLocationOnScreen();
                popup.setLocation(p.x, p.y + editorComponent.getSize().height);
                popup.show();
                fireEditingStopped();
            }
        });

        currentText = value.toString();
        editorComponent.setText( currentText );
        return editorComponent;
    }

    /*
    *   Simple dialog containing the actual editing component
    */
    class PopupDialog extends JDialog implements ActionListener
    {
        private JTextArea textArea;

        public PopupDialog()
        {
            super((Frame)null, "Change Description", true);

            textArea = new JTextArea(5, 20);
            textArea.setLineWrap( true );
            textArea.setWrapStyleWord( true );
            KeyStroke keyStroke = KeyStroke.getKeyStroke("ENTER");
            textArea.getInputMap().put(keyStroke, "none");
            JScrollPane scrollPane = new JScrollPane( textArea );
            getContentPane().add( scrollPane );

            JButton cancel = new JButton("Cancel");
            cancel.addActionListener( this );
            JButton ok = new JButton("Ok");
            ok.setPreferredSize( cancel.getPreferredSize() );
            ok.addActionListener( this );

            JPanel buttons = new JPanel();
            buttons.add( ok );
            buttons.add( cancel );
            getContentPane().add(buttons, BorderLayout.SOUTH);
            pack();

            getRootPane().setDefaultButton( ok );
        }

        public void setText(String text)
        {
            textArea.setText( text );
        }

        /*
        *   Save the changed text before hiding the popup
        */
        public void actionPerformed(ActionEvent e)
        {
            if ("Ok".equals( e.getActionCommand() ) )
            {
                currentText = textArea.getText();
            }

            textArea.requestFocusInWindow();
            setVisible( false );
        }
    }

    private static void createAndShowUI()
    {
        String[] columnNames = {"Item", "Description"};
        Object[][] data =
        {
            {"Item 1", "Description of Item 1"},
            {"Item 2", "Description of Item 2"},
            {"Item 3", "Description of Item 3"}
        };

        JTable table = new JTable(data, columnNames);
        table.getColumnModel().getColumn(1).setPreferredWidth(300);
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
        JScrollPane scrollPane = new JScrollPane(table);

        // Use the popup editor on the second column

        TablePopupEditor popupEditor = new TablePopupEditor();
        table.getColumnModel().getColumn(1).setCellEditor( popupEditor );

        JFrame frame = new JFrame("Popup Editor Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new JTextField(), BorderLayout.NORTH);
        frame.add( scrollPane );
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }

}

使用这种方法,您不会不断地操纵行的大小.您甚至可以自定义代码,以使对话框适合单元格的宽度并显示在单元格的下方.

Using this approach you don't continually manipulate the row size. You could even customize the code to make the dialog fit the width of the cell and appear below the cell.

这篇关于Java Eclipse Jtable单元格/列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆