当前位置: 首页 > 面试题库 >

试图让排序器位置在表刷新后保留

东郭京
2023-03-14
问题内容

我有以下方法:

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);

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

我曾尝试过使用get 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)

问题答案:

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

  1. getSortKeys()
  2. 刷新TableModel
  3. setSortKeys(…)

编辑:

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();
            }
        });
    }
}


 类似资料:
  • 我有一个具有2个视图\控制器的应用程序: 谢谢你。

  • 在我的应用程序中,我在回收器视图中显示了一个按钮列表,借助ItemTouchHelper.SimpleCallback,onMove函数,我可以重新排序按钮,但重新排序后位置不会更新。例如:-(如果我将按钮1从0位置拖到1位置,那么按钮1应该显示它的新位置是1,但它显示的是旧位置,即0)是否有任何东西在改变,以便我可以访问它并了解按钮的新位置。如有任何帮助,不胜感激。

  • 问题内容: 有人可以告诉我我在做什么错吗?我需要在一段时间后刷新页面,但是它会刷新到页面顶部,我需要不更改页面位置!所以这是我现在无法使用的,是meta标签吗?这是我所没有的仍然不刷新必须做错了什么吗? 这是我本来的… 阅读了一些初始答案后,我将其更改为… 问题答案: 更新 您可以使用下面提到的方法代替下面的强制技巧。 将HTML替换为:

  • 我尝试使用localStorage保存输入元素的位置。我保存了输入元素的位置,在重新加载页面后,我可以访问它,但在刷新页面后,它始终处于默认位置。(值真/假) HTML: JS: 明确地说,我正在创建chrome扩展(选项页)。 编辑:

  • 我正在使用php和javascript进行网络编程,这是我想问的一个一般性问题,通常在页面刷新时,文本区域或输入中的所有内容都会被删除; 是否有办法保留用户输入、键入的字符或复选框?不保存到会话中?还是我真的需要保存它?非常感谢。 (我不是说表单提交导致重新加载,但只是简单地键入文本区域,然后按下刷新按钮。)

  • 问题内容: 我在SO上看到了很多与此问题有关的问题,但都与我的情况无关。除了进行基本的CRUD操作外,我与SQL专家们无二。因此,我对此非常执着。 我有一张表。 在哪里; myTable始终总有10行。 因此,首先,假设myTable具有以下数据: 预期的功能应如下所示; 插入新 当插入新项目时,用户应该能够将其插入到他/她想要的任何位置。现在,我仅设法通过删除OrderPosition = 10