[英]How to add new rows at top of the JTable and Change the color of newly inserted rows in Java?
I am working on project in which in one module I have to show the data in a data grid (for which I am using JTable). 我正在做一个项目,在这个项目中,我必须在一个模块中将数据显示在数据网格中(我正在使用JTable)。 The problem is that, when I insert the Data in JTable, it gets populated at the bottom of the table, and I want to show the new rows at the top of the table. 问题是,当我在JTable中插入数据时,它会填充在表的底部,并且我想在表的顶部显示新的行。 Please guide me to achieve this task, any help will be appreciated. 请指导我完成这项任务,我们将不胜感激。 I am using NetBeans for the development. 我正在使用NetBeans进行开发。
Here is my code to populate the data: 这是我的数据填充代码:
public void run() {
try {
FileWriter out = new FileWriter("test.txt");
BufferedWriter bufWriter = new BufferedWriter(out);
int nb = input.readInt();
System.out.println("Read Length"+ nb);
byte[] digit = new byte[nb];
System.out.println("Writing.......");
for(int i = 0; i < nb; i++)
digit[i] = input.readByte();
String st = new String(digit);
bufWriter.append(st);
bufWriter.close();
out.close();
System.out.println ("receive from : " +
clientSocket.getInetAddress() + ":" +
clientSocket.getPort() + " message - " + st);
DefaultTableModel table = (DefaultTableModel)_table.getModel();
File file = new File("test.txt");
Scanner f = new Scanner(file);
String line = null;
String[] str = null;
while(f.hasNext()){
line = f.nextLine().replace('|', ',');
str = line.split(",");
table.addRow(str);
_table.setBackground(Color.red);
}
output.writeInt(st.length());
output.writeBytes(st);
}
catch(EOFException e) {
System.out.println("EOF:"+e.getMessage()); }
catch(IOException e) {
System.out.println("IO:"+e.getMessage());}
finally {
try {
clientSocket.close();
}
catch (IOException e){/*close failed*/}
}
}
Thanks in advance. 提前致谢。
The problem is that, when I insert the Data in JTable, it gets populated at the bottom of the table, and I want to show the new rows at the top of the table 问题是,当我在JTable中插入数据时,它会填充在表的底部,并且我想在表的顶部显示新的行。
table.addRow(str);
Well actually you are not inserting a row, you are adding a row. 好吧,实际上您不是在插入一行,而是在添加一行。 Try reading the DefaultTableModel
API for a method that will allow you to "insert" a row at a specified location in the model, which in your case would be row 0. 尝试阅读DefaultTableModel
API,了解一种方法,该方法将允许您在模型的指定位置“插入”一行,在您的情况下为0行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.