我需要从scores.dat
文件中读取数据并将其弹出到一个JTable
,这里有更多信息:
Scores.dat
好像Team Name Score1 Score2 Red John 55 7 Blue Michael 33 6 Green Burrs 55 5
位置 =
C:\Documents\scores.dat
第一行是列名。所以需要将列名弹出到表的第一行。
Scores.dat
是动态的,通过用户操作添加/删除行。另外,我需要表格下方的“Top Scorer”按钮,单击该按钮时会突出显示得分最高的行。
这是我的代码:
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
/**
*
* @author singh_000
*/
public class SampleJTableDemo extends JFrame implements ActionListener {
/**
* Creates new form OrderMateRequestForm
*/
public SampleJTableDemo() {
initComponents();
}
private void initComponents() {
//headers for the table
String[] columns = new String[]{
"Team", "Name", "Score1", "Score2"//Todo: pop names from 1st row from scores.dat
};
//actual data for the table in a 2d array
Object[][] data = new Object[][]{
{"Red", "John", 40.0, 7},
{"Blue", "Rambo", 70.0, 6},
{"Gree", "Zorro", 60.0, 7},
{"Black", "Curran", 70.0, 5},};
final Class[] columnClass = new Class[]{
String.class, String.class, Double.class, Integer.class
};
//create table model with data
DefaultTableModel model = new DefaultTableModel(data, columns) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return columnClass[columnIndex];
}
};
JTable table = new JTable(model);
Container contentPane = this.getContentPane();
contentPane.setLayout(new FlowLayout());
// contentPane.add(table);
JScrollPane scrollPane = new JScrollPane(table);
contentPane.add(scrollPane);
JSeparator separator = new JSeparator();
separator.setVisible(true);
contentPane.add(separator);
//add the table to the frame
// this.add(new JScrollPane(table));
//ToDO: Add buton for top scorer
JButton button = new JButton("Top Scorer");
button.setVisible(true);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
}
});
this.setTitle("Score-List");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new SampleJTableDemo();
}
});
}
@Override
public void actionPerformed(ActionEvent e) {
}
}