如何将JTable的列数据类型定义为与MySQL数据库相同?

huangapple go评论39阅读模式
英文:

How to define the JTable's Column's data type the same as MySql database?

问题

我已在Netbeans中创建了一个图形界面,其中我在FORM JFrame中插入了一个JTable。我有一个MySQL数据库,其列如下:

Id:整数

Name:字符串

Active:布尔值

然而,当我使用:jTable.setModel(DbUtils.resultSetToTableModel())(RS2XML.jar库的方法)时,JTable被填充为全部字符串。

我如何使JTable以与数据库相同的数据类型填充(整数、字符串和布尔值)?

英文:

I have created a graphical interface in Netbeans where I inserted a JTable inside a FORM JFrame. I have a MySql database and it's columns are:

Id: Integer

Name: String

Active: Boolean

However, when I use: jTable.setModel (DbUtils.resultSetToTableModel ()) (method of the library RS2XML.jar), the JTable is filled all as String.

How do I make JTable filled with the correct data types just like the database (Integer, String and Boolean)?

答案1

得分: 0

The JTable is filled all as String.

表格中的所有内容都是字符串。

The model should contain data of the proper type. The problem is you have not defined what the data type should be for each column, so by default it is treated as Object and the default renderer will just invoke the toString() method on the object.

模型应包含正确类型的数据。问题在于您没有定义每列的数据类型,因此默认情况下它被视为Object,默认渲染器只会调用对象的toString()方法。

You can override the getColumnClass(...) method of the JTable.

您可以重写JTablegetColumnClass(...)方法。

Something like:

类似于:

JTable table = new JTable(model)
{
    //  Returning the Class of each column will allow different
    //  renderers and editors to be used based on Class

    @Override
    public Class getColumnClass(int column)
    {
        for (int row = 0; row < getRowCount(); row++)
        {
            Object o = getValueAt(row, column);

            if (o != null)
                return o.getClass();
        }

        return Object.class;
    }
};
英文:

> the JTable is filled all as String.

The model should contain data of the proper type. The problem is you have mot defined what the data type should be for each column, so by default it is treated as Object and the default renderer will just invoke the toString() method on the object.

You can override the getColumnClass(...) method of the JTable.

Something like:

JTable table = new JTable(model)
{
	//  Returning the Class of each column will allow different
	//  renderers and editors to be used based on Class

	@Override
	public Class getColumnClass(int column)
	{
		for (int row = 0; row &lt; getRowCount(); row++)
		{
			Object o = getValueAt(row, column);

			if (o != null)
				return o.getClass();
		}

		return Object.class;
	}
};

huangapple
  • 本文由 发表于 2020年7月30日 09:46:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/63164947.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定