尝试在表刷新后让分拣机位置保留

时间:2016-01-01 23:38:18

标签: java model jtable refresh tablerowsorter

我有以下方法:

private void passStingR(StringBuilder retVal) throws BadLocationException {

int scrollPositionR = scrollR.getVerticalScrollBar().getValue();//get value of scroll position stores in javas memory

windowR.remove(scrollR);
tableR.getModel();
modelR.setRowCount(0);

Document docR = null;
try {
docR = loadXMLFromString(retVal.toString());//pull in the XML data into a new doc
} catch (Exception ex) {
Logger.getLogger(remit.class.getName()).log(Level.SEVERE, null, ex);
}

populate1R(docR);


tableR.getTableHeader().setReorderingAllowed(false);//prevent user from changing column order now at refresh level   

SimpleDateFormat time_formatterR = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String current_time_strR = time_formatterR.format(System.currentTimeMillis());

updatetFieldR.setText(current_time_strR);

scrollR.remove(tableR);
tableR = new JTable(modelR)
{
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component c = super.prepareRenderer(renderer, row, column);

Font myFont = new Font("Arial",Font.PLAIN,10);
Font myFont1 = new Font("Arial", Font.BOLD,10);
 if (!isRowSelected(row)) {
                    if (tableR.getColumnCount() >= 0) {
                              String type = (String) getModel().getValueAt(row, 11);
                        c.setBackground("0.0".equals(type) ? Color.RED : Color.WHITE);
                        c.setForeground("0.0".equals(type) ? Color.WHITE : Color.BLACK);
                        c.setFont("0.0".equals(type) ? myFont1: myFont);

                    }

 }  



 return c;



};
};



TableColumn column = null;
    for (int i = 0; i < 18; i++) {
        column = tableR.getColumnModel().getColumn(i);
          if (i == 0) {
            column.setPreferredWidth(70); //sport column is bigger
          }
            if (i == 1) {
            column.setPreferredWidth(500); //sport column is bigger
             } 
                if (i == 7) {
            column.setPreferredWidth(30); //sport column is bigger
             }
               if (i == 8) {
            column.setPreferredWidth(20); //sport column is bigger
             }
                   if (i == 9) {
            column.setPreferredWidth(25); //sport column is bigger
             }
             if (i == 14) {
            column.setPreferredWidth(500); //sport column is bigger
             }
               if (i == 15) {
            column.setPreferredWidth(10); //sport column is bigger
             }
               if (i == 16) {
            column.setPreferredWidth(20); //sport column is bigger
             }

    }

 tableR.getTableHeader().setReorderingAllowed(false);//prevent the user from sorting the columns at intialise GUI stage even though the user cannnot change this      

 RowSorter<TableModel> sorter = new TableRowSorter<>(modelR);//creating a new sorter here from my modelR

tableR.setRowSorter(sorter);//set the sorter positon

scrollR = new JScrollPane(tableR);      
windowR.add(scrollR);

windowR.validate();

scrollR.getVerticalScrollBar().setValue(scrollPositionR);


    }

然后我在上面的代码中创建了一个分类器,如下面的

RowSorter<TableModel> sorter = new TableRowSorter<>(modelR);//creating a new sorter here from my modelR

tableR.setRowSorter(sorter);//set the sorter positon

这允许我对特定列进行排序并对列进行排序。 然而,一旦刷新,分拣机就会重置: 刷新过程是:

public void actionPerformed(ActionEvent e) {
Object source = e.getSource();

String stringfromDateR =  tffromDateR.getText();
String stringtoDateR =  tftoDateR.getText();

if(source == buttonR){
  if(timerR != null) {
      System.out.print("cancel");
      timerR.cancel();

    } 
//  System.out.print("cancel1bbbbb");
timerR = new Timer();    
//auto refresh begins
int delayR = 0; //0 seconds startup delay
int periodR = 7000; //x seconds between refreshes
timerR.scheduleAtFixedRate(new TimerTask() 


{    

public void run() {

try {
    getdataR(stringfromDateR,stringtoDateR);
 } catch (IOException | BadLocationException ex) {
 Logger.getLogger(JavaApplication63.class.getName()).log(Level.SEVERE, null, ex);           

}



      }
  }, delayR, periodR);    
} 

if(source == buttonR1){


 if(timerR != null) {
        timerR.cancel();
    }
modelR.setRowCount(0);
} 


    }

然后

private void getdataR(String stringfromDateR,String stringtoDateR) throws IOException, BadLocationException {

StringBuilder retVal = new StringBuilder();
URL oracle = new URL("XXXXXXXXXXXXXXXXXXXXX" );
BufferedReader in = new BufferedReader(new InputStreamReader(oracle.openStream()));

String newLine = "\n";
String inputLine;
while ((inputLine = in.readLine()) != null) {
            System.out.println(inputLine);
retVal.append(inputLine).append(newLine);

}

in.close();

passStingR(retVal);

    }

如何在刷新完成后让分拣机保留。我不确定是否设置

modelR.setRowCount(0); 

导致分拣机失去分拣机位置。

我确实尝试过获取sortkeys,但这不起作用,我也进行了实验 在刷新之前发生了

RowSorter<? extends TableModel> tablesorterpos = tableR.getRowSorter();

然后应用

tableR.setRowSorter(tablesorterpos);
刷新后

但这没有用

这就是我试过的

private void passStingR(StringBuilder retVal) throws BadLocationException {
 RowSorter<TableModel> sorter = new TableRowSorter<>(modelR);//creating a new sorter here from my modelR
List<? extends SortKey> sorterR = sorter.getSortKeys();
int scrollPositionR = scrollR.getVerticalScrollBar().getValue();//get value of scroll position stores in javas memory

windowR.remove(scrollR);
tableR.getModel();
modelR.setRowCount(0);

Document docR = null;
try {
docR = loadXMLFromString(retVal.toString());//pull in the XML data into a new doc
} catch (Exception ex) {
Logger.getLogger(remit.class.getName()).log(Level.SEVERE, null, ex);
}

populate1R(docR);


tableR.getTableHeader().setReorderingAllowed(false);//prevent user from changing column order now at refresh level   

SimpleDateFormat time_formatterR = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String current_time_strR = time_formatterR.format(System.currentTimeMillis());

updatetFieldR.setText(current_time_strR);

scrollR.remove(tableR);
tableR = new JTable(modelR)
{
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component c = super.prepareRenderer(renderer, row, column);

Font myFont = new Font("Arial",Font.PLAIN,10);
Font myFont1 = new Font("Arial", Font.BOLD,10);
 if (!isRowSelected(row)) {
                    if (tableR.getColumnCount() >= 0) {
                              String type = (String) getModel().getValueAt(row, 11);
                        c.setBackground("0.0".equals(type) ? Color.RED : Color.WHITE);
                        c.setForeground("0.0".equals(type) ? Color.WHITE : Color.BLACK);
                        c.setFont("0.0".equals(type) ? myFont1: myFont);

                    }

 }  



 return c;



};
};



TableColumn column = null;
    for (int i = 0; i < 18; i++) {
        column = tableR.getColumnModel().getColumn(i);
          if (i == 0) {
            column.setPreferredWidth(70); //sport column is bigger
          }
            if (i == 1) {
            column.setPreferredWidth(500); //sport column is bigger
             } 
                if (i == 7) {
            column.setPreferredWidth(30); //sport column is bigger
             }
               if (i == 8) {
            column.setPreferredWidth(20); //sport column is bigger
             }
                   if (i == 9) {
            column.setPreferredWidth(25); //sport column is bigger
             }
             if (i == 14) {
            column.setPreferredWidth(500); //sport column is bigger
             }
               if (i == 15) {
            column.setPreferredWidth(10); //sport column is bigger
             }
               if (i == 16) {
            column.setPreferredWidth(20); //sport column is bigger
             }

    }

 tableR.getTableHeader().setReorderingAllowed(false);//prevent the user from sorting the columns at intialise GUI stage even though the user cannnot change this      


sorter.setSortKeys(sorterR);
tableR.setRowSorter(sorter);//set the sorter positon


scrollR = new JScrollPane(tableR);      
windowR.add(scrollR);

windowR.validate();

scrollR.getVerticalScrollBar().setValue(scrollPositionR);


    }

我收到此错误:

at javax.swing.DefaultRowSorter.rowsDeleted(DefaultRowSorter.java:880)
at javax.swing.JTable.notifySorter(JTable.java:4276)
at javax.swing.JTable.sortedTableChanged(JTable.java:4120)
at javax.swing.JTable.tableChanged(JTable.java:4397)
at javax.swing.table.AbstractTableModel.fireTableChanged(AbstractTableModel.java:296)
at javax.swing.table.AbstractTableModel.fireTableRowsDeleted(AbstractTableModel.java:261)
at javax.swing.table.DefaultTableModel.setNumRows(DefaultTableModel.java:321)
at javax.swing.table.DefaultTableModel.setRowCount(DefaultTableModel.java:339)
at javaapplication63.remit.passStingR(remit.java:238)
at javaapplication63.remit.getdataR(remit.java:227)
at javaapplication63.remit.access$000(remit.java:60)
    at javaapplication63.remit$1.run(remit.java:187)
    at java.util.TimerThread.mainLoop(Timer.java:555)
    at java.util.TimerThread.run(Timer.java:505)

1 个答案:

答案 0 :(得分:2)

您可以从DefaultRowSorter获取当前排序键。所以基本的逻辑是:

  1. getSortKeys()
  2. 刷新TableModel
  3. setSortKeys(...)
  4. 编辑:

    import java.awt.*;
    import java.awt.event.*;
    import java.util.List;
    import javax.swing.*;
    import javax.swing.table.*;
    
    public class TableSortSSCCE extends JPanel
    {
        private String[] columnNames = {"First Name",
                                        "Last Name",
                                        "Sport",
                                        "# of Years",
                                        "Vegetarian"};
    
        private Object[][] data =
        {
            {"Kathy", "Smith", "Snowboarding", new Integer(5), new Boolean(false)},
            {"John", "Doe", "Rowing", new Integer(3), new Boolean(true)},
            {"Sue", "Black", "Knitting", new Integer(2), new Boolean(false)},
            {"Jane", "White", "Speed reading", new Integer(20), new Boolean(true)},
            {"Joe", "Brown", "Pool", new Integer(10), new Boolean(false)}
        };
    
        private JTable table;
    
    
        public TableSortSSCCE()
        {
            super(new BorderLayout());
    
            DefaultTableModel model = new DefaultTableModel(data, columnNames);
            table = new JTable(model);
            table.setPreferredScrollableViewportSize( table.getPreferredSize() );
            table.setAutoCreateRowSorter(true);
    
            JScrollPane scrollPane = new JScrollPane(table);
            add(scrollPane, BorderLayout.CENTER);
    
            JButton clear = new JButton("Clear Table");
            clear.addActionListener( new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent e)
                {
                    DefaultTableModel model = (DefaultTableModel)table.getModel();
                    model.setRowCount(0);
                }
            });
            add(clear, BorderLayout.NORTH);
    
    
            JButton reload = new JButton("Reload Table");
            reload.addActionListener( new ActionListener()
            {
                @Override
                public void actionPerformed(ActionEvent e)
                {
                    TableRowSorter sorter = (TableRowSorter)table.getRowSorter();
                    List<? extends RowSorter.SortKey> sortKeys = sorter.getSortKeys();
    
                    DefaultTableModel model = new DefaultTableModel(data, columnNames);
                    table.setModel(model);
                    table.setAutoCreateRowSorter( true );
    
                    sorter = (TableRowSorter)table.getRowSorter();
                    sorter.setSortKeys( sortKeys );
                }
            });
            add(reload, BorderLayout.SOUTH);
        }
    
        private static void createAndShowGUI()
        {
            JFrame frame = new JFrame("TableSortSSCCE");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            TableSortSSCCE newContentPane = new TableSortSSCCE();
            frame.setContentPane(newContentPane);
            frame.pack();
            frame.setLocationByPlatform(true);
            frame.setVisible(true);
        }
    
        public static void main(String[] args)
        {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
                }
            });
        }
    }