jtable的问题

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了jtable的问题相关的知识,希望对你有一定的参考价值。

当光标在jtable中的某一个单元格中闪着的时候,在这个单元格中新更改的数据并没有被读入(按下enter或者点击另一个单元格后新数据才被读入),用getvalueat()方法也不能够读出新的值,读出来的只是旧值。怎么解决?

参考技术A 需要给jtable添加选择事件,其它的只需要用按钮事件就可以了。
一会给你一个代码你看看,别追问,要不然不够贴代码。

好了,下边是代码,你看一下吧。
-----------------------------------------------------------------------------------------
import javax.swing.JFrame;

public class TableDemo extends JFrame

// name文本框
private JTextField nameTextField;
// email文本框
private JTextField emailTextField;
private JTable table;
// Swing中的Table数据是通过DefaultTableModel来实现的,(API上解释是表格模型什么的,具体的记不清了)
private DefaultTableModel model;
private String[] columnNames = "name", "email" ;
private JScrollPane scrollPane;

public TableDemo()
getContentPane().setLayout(null);

model = new DefaultTableModel(columnNames, 0);
// JLabel只是显示文字用的
JLabel lblName = new JLabel("name");
// 设置JLabel的显示位置及大小。
// setBounds(x, y, width, height)
lblName.setBounds(12, 10, 50, 13);
getContentPane().add(lblName);

JLabel lblEmail = new JLabel("email");
lblEmail.setBounds(182, 10, 50, 13);
getContentPane().add(lblEmail);

// 文本框对象实例化,设置大小及显示位置
nameTextField = new JTextField();
nameTextField.setBounds(74, 7, 96, 19);
getContentPane().add(nameTextField);
nameTextField.setColumns(10);

emailTextField = new JTextField();
emailTextField.setBounds(244, 7, 96, 19);
getContentPane().add(emailTextField);
emailTextField.setColumns(10);

// 按钮对象实例化,设置大小及显示位置
JButton btnAdd = new JButton("add");
// 添加按钮事件
btnAdd.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
String[] row = nameTextField.getText(),
emailTextField.getText() ;
// 添加数据
model.addRow(row);

);
btnAdd.setBounds(151, 36, 91, 21);
getContentPane().add(btnAdd);

JButton btnRefresh = new JButton("refresh");
btnRefresh.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
// 取得选中的行。
int rowIndex = table.getSelectedRow();
// 将数据设置到指定的单元格中。
model.setValueAt(nameTextField.getText(), rowIndex, 0);
model.setValueAt(emailTextField.getText(), rowIndex, 1);

);
btnRefresh.setBounds(254, 36, 91, 21);
getContentPane().add(btnRefresh);

scrollPane = new JScrollPane();
scrollPane.addMouseListener(new MouseAdapter()
public void mouseClicked(MouseEvent e)
// 表格的鼠标点击事件。取得表中的选中行。
int rowIndex = table.getSelectedRow();
// 从指定的单元格中取得数据,显示在文本框中。
nameTextField.setText((String) model.getValueAt(rowIndex, 0));
emailTextField.setText((String) model.getValueAt(rowIndex, 1));

);
scrollPane.setBounds(12, 67, 370, 195);
getContentPane().add(scrollPane);

table = new JTable(model);
scrollPane.setViewportView(table);

// 使窗体的X按钮可用。如果不设置 ,按下没有效果。
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
// 设置窗体大小
setSize(400, 300);
// 设置窗本大小不可改变。
setResizable(false);
setVisible(true);


public static void main(String[] args)
new TableDemo();


请采纳。追问

写这么多,让你受累了

本回答被提问者采纳

JTable - 布尔单元格类型 - 背景

【中文标题】JTable - 布尔单元格类型 - 背景【英文标题】:JTable - Boolean Cell Type - Background 【发布时间】:2011-09-29 22:16:17 【问题描述】:

我将 Nimbus L&F 与 JTable 一起使用,该 JTable 有一个布尔(复选框)元素作为其列之一。

我遇到的问题是布尔列不遵循 Nimbus L&F 中存在的自然行背景交替。

【问题讨论】:

【参考方案1】:

这是安装合成器的渲染器中的一个错误,快速破解是强制渲染复选框不透明度为true:

    ((JComponent) table.getDefaultRenderer(Boolean.class)).setOpaque(true);

【讨论】:

非常感谢您提供的解决方案!你为我节省了一个小时的睡眠时间;)【参考方案2】:

嗯,我有相反的问题,检查一下,如果没有代码示例,真的没有人可以帮助你,也许有人可以使用 TableCellRenderer 来玩未选择的 AlternateTableColor

Nimbus Defaults

import javax.swing.*;
import javax.swing.table.*;
import java.util.Date;
import java.util.Vector;
import java.awt.*;
import java.awt.event.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import javax.swing.UIManager.LookAndFeelInfo;

public class TableTestPanel extends JPanel 

    private static final String[] COLUMN_NAMES = "List ID", "Expiration Date", "Status", "Date Created";
    private static final DateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM/yyyy");
    private static final long serialVersionUID = 1L;

    private static class StatusPanel extends JPanel 

        private static final long serialVersionUID = 1L;
        private JRadioButton theSingleOption;
        private JRadioButton theMarriedOption;
        private JRadioButton theDivorcedOption;

        StatusPanel() 
            super(new GridLayout(3, 1));
            setOpaque(true);
            ButtonGroup buttonGroup = new ButtonGroup();
            theSingleOption = new JRadioButton("Single");
            theSingleOption.setOpaque(false);
            add(theSingleOption);
            buttonGroup.add(theSingleOption);
            theMarriedOption = new JRadioButton("Married");
            theMarriedOption.setOpaque(false);
            add(theMarriedOption);
            buttonGroup.add(theMarriedOption);
            theDivorcedOption = new JRadioButton("Divorced");
            theDivorcedOption.setOpaque(false);
            add(theDivorcedOption);
            buttonGroup.add(theDivorcedOption);
        

        public Status getStatus() 
            if (theMarriedOption.isSelected()) 
                return Status.MARRIED;
             else if (theDivorcedOption.isSelected()) 
                return Status.DIVORCED;
             else 
                return Status.SINGLE;
            
        

        public void setStatus(Status status) 
            if (status == Status.MARRIED) 
                theMarriedOption.setSelected(true);
             else if (status == Status.DIVORCED) 
                theDivorcedOption.setSelected(true);
             else 
                theSingleOption.setSelected(true);
            
        
    

    private static class Status 

        static final Status SINGLE = new Status("Single");
        static final Status MARRIED = new Status("Married");
        static final Status DIVORCED = new Status("Divorced");
        private final String myName; // for debug only

        private Status(String name) 
            myName = name;
        

        @Override
        public String toString() 
            return myName;
        
    

    private static class TableEntry 

        private static int instanceNumber;
        private Long theId;
        private Date theExpirationDate;
        private Status theStatus;
        private Date theCreationDate;

        TableEntry() 
            instanceNumber++;
            theId = new Long(instanceNumber);
            theExpirationDate = new Date();
            theStatus = Status.SINGLE;
            theCreationDate = new Date();
        

        TableEntry(Long anId, Date anExpirationDate, Status aStatus, Date aCreationDate) 
            theId = anId;
            theExpirationDate = anExpirationDate;
            theStatus = aStatus;
            theCreationDate = aCreationDate;
        

        public Long getId() 
            return theId;
        

        public Date getExpirationDate() 
            return theExpirationDate;
        

        public Status getStatus() 
            return theStatus;
        

        public Date getCreationDate() 
            return theCreationDate;
        

        public void setId(Long anId) 
            theId = anId;
        

        public void setExpirationDate(Date anExpirationDate) 
            theExpirationDate = anExpirationDate;
        

        public void setStatus(Status aStatus) 
            theStatus = aStatus;
        

        public void setCreationDate(Date aCreationDate) 
            theCreationDate = aCreationDate;
        
    

    private static class MyTableModel extends AbstractTableModel 

        private static final long serialVersionUID = 1L;
        private Vector<Object> theEntries;

        MyTableModel() 
            theEntries = new Vector<Object>();
        

        @SuppressWarnings("unchecked")
        public void add(TableEntry anEntry) 
            int index = theEntries.size();
            theEntries.add(anEntry);
            fireTableRowsInserted(index, index);
        

        public void remove(int aRowIndex) 
            if (aRowIndex < 0 || aRowIndex >= theEntries.size()) 
                return;
            
            theEntries.removeElementAt(aRowIndex);
            fireTableRowsDeleted(aRowIndex, aRowIndex);

        

        public int getRowCount() 
            return theEntries.size();
        

        @Override
        public String getColumnName(int column) 
            return COLUMN_NAMES[column];
        

        @Override
        public Class<?> getColumnClass(int columnIndex) 
            switch (columnIndex) 
                case 0:
                    return Long.class;
                case 1:
                    return Date.class;
                case 2:
                    return Status.class;
                case 3:
                    return Date.class;
            
            return Object.class;
        

        @Override
        public void setValueAt(Object aValue, int rowIndex, int columnIndex) 
            TableEntry entry = (TableEntry) theEntries.elementAt(rowIndex);
            switch (columnIndex) 
                case 0:
                    try 
                        entry.setId(new Long(Long.parseLong(aValue.toString())));
                     catch (NumberFormatException nfe) 
                        return;
                    
                    break;
                case 1:
                    entry.setExpirationDate((Date) aValue);
                    break;
                case 2:
                    entry.setStatus((Status) aValue);
                    break;
                case 3:
                    entry.setCreationDate((Date) aValue);
                    break;
                default:
                    return;
            
            fireTableCellUpdated(rowIndex, columnIndex);
        

        @Override
        public boolean isCellEditable(int rowIndex, int columnIndex) 
            return true;
        

        @Override
        public int getColumnCount() 
            return 4;
        

        @Override
        public Object getValueAt(int rowIndex, int columnIndex) 
            TableEntry entry = (TableEntry) theEntries.elementAt(rowIndex);
            switch (columnIndex) 
                case 0:
                    return entry.getId();
                case 1:
                    return entry.getExpirationDate();
                case 2:
                    return entry.getStatus();
                case 3:
                    return entry.getCreationDate();
            
            return null;
        
    

    private static class DateRenderer extends DefaultTableCellRenderer 

        private static final long serialVersionUID = 1L;

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) 
            super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            if (!(value instanceof Date)) 
                return this;
            
            setText(DATE_FORMAT.format((Date) value));
            return this;
        
    

    private static class DateEditor extends AbstractCellEditor implements TableCellEditor 

        private static final long serialVersionUID = 1L;
        private JSpinner theSpinner;
        private Object value;

        DateEditor() 
            theSpinner = new JSpinner(new SpinnerDateModel());
            theSpinner.setOpaque(true);
            theSpinner.setEditor(new JSpinner.DateEditor(theSpinner, "dd/MM/yyyy"));
        

        @Override
        public Object getCellEditorValue() 
            return theSpinner.getValue();
        

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) 
            theSpinner.setValue(value);
            if (isSelected) 
                theSpinner.setBackground(table.getSelectionBackground());
             else 
                theSpinner.setBackground(table.getBackground());
            
            return theSpinner;
        
    

    private static class StatusEditor extends AbstractCellEditor implements TableCellEditor 

        private static final long serialVersionUID = 1L;
        private StatusPanel theStatusPanel;

        StatusEditor() 
            theStatusPanel = new StatusPanel();
        

        @Override
        public Object getCellEditorValue() 
            return theStatusPanel.getStatus();
        

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) 
            theStatusPanel.setStatus((Status) value);
            if (isSelected) 
                theStatusPanel.setBackground(table.getSelectionBackground());
             else 
                theStatusPanel.setBackground(table.getBackground());
            
            return theStatusPanel;
        
    

    private static class StatusRenderer extends StatusPanel implements TableCellRenderer 

        private static final long serialVersionUID = 1L;

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) 
            setStatus((Status) value);
            if (isSelected) 
                setBackground(table.getSelectionBackground());
             else 
                setBackground(table.getBackground());
            
            return this;
        
    
    private MyTableModel theTableModel;
    private JTable theTable;

    public TableTestPanel() 
        super(new BorderLayout(0, 5));
        setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        theTableModel = new MyTableModel();
        theTable = new JTable(theTableModel);
        theTable.setDefaultEditor(Date.class, new DateEditor());
        theTable.setDefaultRenderer(Date.class, new DateRenderer());
        theTable.setDefaultEditor(Status.class, new StatusEditor());
        theTable.setDefaultRenderer(Status.class, new StatusRenderer());
// comment out the two preceding lines and uncomment the following one if you want a more standard editor
// theTable.setDefaultEditor(Status.class, new DefaultCellEditor(new JComboBox(new Status[]Status.SINGLE, Status.MARRIED, Status.DIVORCED)));
        add(new JScrollPane(theTable), BorderLayout.CENTER);
        JToolBar toolBar = new JToolBar();
        toolBar.setFloatable(false);
        toolBar.add(new AbstractAction("Add new") 

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) 
                theTableModel.add(new TableEntry());
                packTable();
            
        );
        toolBar.add(new AbstractAction("Remove") 

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) 
                theTableModel.remove(theTable.getSelectedRow());
            
        );
        add(toolBar, BorderLayout.NORTH);
    

    private void packTable() 
        TableColumnModel columnModel = theTable.getColumnModel();
        int columnCount = theTable.getColumnCount();
        int rowCount = theTable.getRowCount();
        int[][] preferredHeights = new int[columnCount][rowCount];
        TableCellRenderer renderer;
        Component comp;
        for (int col = 0; col < columnCount; col++) 
            renderer = columnModel.getColumn(col).getCellRenderer();
            if (renderer == null) 
                renderer = theTable.getDefaultRenderer(theTableModel.getColumnClass(col));
            
            for (int row = 0; row < rowCount; row++) 
                comp = renderer.getTableCellRendererComponent(theTable, theTableModel.getValueAt(row, col), false, false, row, col);
                preferredHeights[col][row] = (int) comp.getPreferredSize().getHeight();
            
        
        for (int row = 0; row < rowCount; row++) 
            int pref = 0;
            for (int col = 0; col < columnCount; col++) 
                pref = Math.max(pref, preferredHeights[col][row]);
            
            theTable.setRowHeight(row, pref);
        
    

    public static void main(String[] args) 
        try 
            // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) 
                if (info.getName().equals("Nimbus")) 
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                
            
         catch (Exception e1) 
            e1.printStackTrace();
        
        final JFrame frame = new JFrame("TestRadioButtonRenderer");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(new TableTestPanel());
        SwingUtilities.invokeLater(new Runnable() 

            @Override
            public void run() 
                frame.setSize(400, 300);
                frame.setVisible(true);
            
        );
    

【讨论】:

【参考方案3】:

我知道这是旧帖子,但对于其他搜索者:我使用 jxtable() 并解决了这个问题 :)

【讨论】:

以上是关于jtable的问题的主要内容,如果未能解决你的问题,请参考以下文章

JTable - 拖放

JTable 中的动态搜索过滤器

找到 JTable 单元格并绘制它

合并 JTable 中的单元格

JTable - 拖动列以增加宽度

在 JTable 中禁用用户编辑 [重复]