2

在此处输入图像描述

我刚刚开始使用JTable. 这是我的表格示例。添加行按钮将行添加到表中。我想为此表创建行标题。我怎样才能做到这一点?

任何人都可以帮助我吗?

示例表的代码是:

package test;

import javax.swing.*;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.table.*;

import test.InsertRows.CellEditor;

public class SampleTable extends JFrame {

JTable table;
JPanel panel;
DefaultTableModel dataModel;

public SampleTable () {
    super("My Table Example");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    onInit();
} 

void onInit()
{
    JButton b=new JButton("Add Row");
    b.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e)
        {
            // TODO Auto-generated method stub
            insertNewRow();

        }


    });

    panel = new JPanel(new BorderLayout());

    String[] columnNames = {
            "Name",
            "OID",
            "Index",
            "Value",
    };
    Object[][] data = {
            {"sysLocation","1.3.6.1.2.1.1.6","0",""},
                {"sysContact","1.3.6.1.2.1.1.4","0",""},
                    {"sysDescr","1.3.6.1.2.1.1.1","0",""}

    };

    dataModel = new DefaultTableModel();
    for (int col = 0; col < columnNames.length; col++) {
        dataModel.addColumn(columnNames[col]);
    }
    for (int row = 0; row < 3; row++) {
        dataModel.addRow(data[row]);
    }

    table = new JTable(dataModel);
    table.setDefaultEditor(Object.class, new CellEditor(this, table));
    table.setPreferredScrollableViewportSize(new Dimension(600, 120));
    table.setFillsViewportHeight(true);

    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);

    //Add the scroll pane to this panel.
    panel.add(scrollPane,BorderLayout.CENTER);
    panel.add(b,BorderLayout.SOUTH);
    panel.setOpaque(true); //content panes must be opaque
    setContentPane(panel);

    //Display the window.
    pack();
    setVisible(true);
}
public static void main(String[] args) {
    SampleTable myFrame = new SampleTable();
} 
private void insertNewRow()
{

    if(vaidCheck(table)){
        dataModel.insertRow(table.getRowCount(),
                new Object[] {"", "", "", ""}
                );
        dataModel.fireTableRowsInserted(
                dataModel.getRowCount(),
                dataModel.getRowCount()
        );
    }
    else{
        JOptionPane.showMessageDialog(null,"Field is empty");                                                                            
    }

}
public boolean vaidCheck(JTable table)
{
      if(table.getCellEditor()!=null){
          table.getCellEditor().stopCellEditing();
      }
      for(int row=0;row< table.getRowCount();row++){
          for (int col=0;col<table.getColumnCount();col++){
              String om=table.getValueAt(row,col).toString();
              if(om.trim().length()==0){
                  return false;
              }
          }
      }
      return true;
 }

 public class CellEditor extends DefaultCellEditor
  {

        /**
         * 
         */
        private static final long serialVersionUID = 1L;
        private JTable m_Table = null;
        public CellEditor(JFrame parentFrame, JTable table) { 
            super(new JTextField());
            super.setClickCountToStart(1);
            m_Table = table;
        }
        @Override
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, final int row, int column)
        {
            if(column == 0){
                 Object[] objectArray = {"Nikhil","Nijil"};
                    JComboBox comboBox = new JComboBox(objectArray);
                    comboBox.setEditable(true);
                    comboBox.setSelectedItem(value);

                    ItemListener itemListener = new ItemListener() {
                        public void itemStateChanged(ItemEvent e) {
                            if(e.getStateChange() == ItemEvent.SELECTED) {
                                if(null != m_Table.getCellEditor()){ 
                                    m_Table.getCellEditor().stopCellEditing();
                                }

                                m_Table.setValueAt(e.getItem(), row, 0);
                            }
                        }
                    };
                    comboBox.addItemListener(itemListener);
                    return comboBox;
            }
            if(column == 2){

            }
            JTextField textField = (JTextField)super.getTableCellEditorComponent(table, value, isSelected, row, column);
            return textField;

        }
  }
} 

在此处输入图像描述

4

1 回答 1

5

我希望我对这个问题的解释是正确的。要显示行标题,您需要创建一个新的单元格渲染器并将其设置在所需的列上。例如,这是一个模拟表头的基本渲染器:

static class RowHeaderRenderer extends DefaultTableCellRenderer {
    public RowHeaderRenderer() {
        setHorizontalAlignment(JLabel.CENTER);
    }

    public Component getTableCellRendererComponent(JTable table,
            Object value, boolean isSelected, boolean hasFocus, int row,
            int column) {
        if (table != null) {
            JTableHeader header = table.getTableHeader();

            if (header != null) {
                setForeground(header.getForeground());
                setBackground(header.getBackground());
                setFont(header.getFont());
            }
        }

        if (isSelected) {
            setFont(getFont().deriveFont(Font.BOLD));
        }

        setValue(value);
        return this;
    }
}

要设置它,您可以执行以下操作:

table.getColumnModel().getColumn(0).setCellRenderer(new RowHeaderRenderer());

这是基于发布的代码的样子:

在此处输入图像描述

于 2012-11-01T05:35:03.550 回答