конвертация jtable

330
10 октября 2017, 02:30

Нужно в третьей колонке поменять тип данных на числа и сделать сортировку. Выдает в консоли:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Cannot format given Object as a Number
    at java.text.DecimalFormat.format(Unknown Source)
    at java.text.Format.format(Unknown Source)
    at UTP171.CountryTable$1.toString(CountryTable.java:74)
    at javax.swing.table.TableRowSorter$TableRowSorterModelWrapper.getStringValueAt(Unknown Source)
    at javax.swing.DefaultRowSorter.compare(Unknown Source)
    at javax.swing.DefaultRowSorter.access$100(Unknown Source)
    at javax.swing.DefaultRowSorter$Row.compareTo(Unknown Source)
    at javax.swing.DefaultRowSorter$Row.compareTo(Unknown Source)
    at java.util.ComparableTimSort.countRunAndMakeAscending(Unknown Source)
    at java.util.ComparableTimSort.sort(Unknown Source)
    at java.util.Arrays.sort(Unknown Source)
    at javax.swing.DefaultRowSorter.sort(Unknown Source)
    at javax.swing.DefaultRowSorter.setSortKeys(Unknown Source)
    at javax.swing.DefaultRowSorter.toggleSortOrder(Unknown Source)
    at javax.swing.plaf.basic.BasicTableHeaderUI$MouseInputHandler.mouseClicked(Unknown Source)
    at java.awt.AWTEventMulticaster.mouseClicked(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$500(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)`

Код в файле main

import javax.swing.*;
public class Main {
  private JTable ctab;
  public void createTable(String countriesFileName) throws Exception {
    ctab = new CountryTable(countriesFileName).create();
  }
  public void showGui() {
    SwingUtilities.invokeLater( new Runnable() {
      public void run() {
        JFrame f = new JFrame("Countries table");
        f.add( new JScrollPane(ctab) );
        f.pack();
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        f.setVisible(true);
      }
    });
  }
  public static void main(String[] args)  {
    Main main = new Main();
    try {
      main.createTable("data/countries.txt");
      main.showGui();
    } catch(Exception exc) {
      JOptionPane.showMessageDialog(null, "Table creation failed, " + exc);
    }
  }
}

код в другом классе

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.DecimalFormat;

import javax.swing.JTable;
import javax.swing.RowSorter;
import javax.swing.table.*;

public class CountryTable {
    static String[] columnNames = new String[3];
    static Object [][] dane = new Object[10][4];

    public CountryTable(String countriesFileName) throws IOException {
        readFile(countriesFileName);
    }
    static  void readFile(String countriesFileName) throws IOException {
        FileReader fr = new FileReader(new File(countriesFileName));
        BufferedReader br = new BufferedReader(fr);
        String line;
        for ( int i = 0; i< 10; i++) {
            if ((line = br.readLine())!= null) {        
                if (i == 0) {
                columnNames = line.split("<TAB>");
                }
                if (i > 0 & i< 10) {
                    dane[i-1] = line.split("<TAB>");
                }
            }
        }
        br.close();
        fr.close();
    }

    JTable create() {
        //System.out.println(dane[0][0]);
        //@SuppressWarnings("serial")
        TableModel model = new DefaultTableModel(dane, columnNames)
        /* {
        public Class<?> getColumnClass(int column) {
            Class<?> returnValue;
            if ((column >= 0) && (column < getColumnCount())) {
              returnValue = getValueAt(0, column).getClass();
            } else {
              returnValue = Object.class;
            }
            return returnValue;
          }
        }*/;
        //System.out.println( columnNames[0]);
        JTable table = new JTable(model);
        RowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
        table.setRowSorter(sorter);
        TableRowSorter<? extends TableModel> tsorter = 
                  (TableRowSorter<? extends TableModel>) table.getRowSorter();
        final DecimalFormat df = new DecimalFormat("000000");
        tsorter.setStringConverter( new TableStringConverter() {
          @Override
          public  String toString(TableModel model, int row, int col) {
            Object elt = model.getValueAt(row, col);
            if (col == 2) {
                return df.format(elt);
            }
            else return elt.toString(); 
          }
        });
        return table;
    }

    public static void main(String[] args) throws IOException {
        readFile("data/countries.txt");
    }
}
READ ALSO
Почему throws не обрабатывается?

Почему throws не обрабатывается?

Есть следующий код:

189
Как cменить JPanel на лету?

Как cменить JPanel на лету?

Делаю простенькую игру на JavaПредставление следующее: Имеется JFrame mainFrame;, на нём JPanel menuPanel;, на котором JButton btnToGame;

400
Ошибки в JFormDesigner плагине

Ошибки в JFormDesigner плагине

Установил в Inteliji Idea плагин jFormDesigner и при запуске созданной формы высвечивает ошибки:

214