我的要求是在网格中显示StockQuote符号(流数据)。
为此,我选择了JTable
。
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
public class Preethi {
protected void initUI() {
final Random random = new Random();
final DefaultTableModel model = new DefaultTableModel(new String[] { "Id", "Name", "Desg", "Sal" }, 0);
final JTable table = new JTable(model);
table.setFillsViewportHeight(true);
JFrame frame = new JFrame(Preethi.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollpane = new JScrollPane(table);
frame.add(scrollpane, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
Random ran = new Random(12);
ran.nextFloat();
String str = new String("sss");
String[] socrates = {str, str, str };
model.addRow(socrates);
System.out.println(model.getRowCount());
System.out.println(model.getColumnCount());
model.setValueAt(new Object[]{"ewqeq","rtgre","gfdgd","mbmnb"}, 1, 4);
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Preethi().initUI();
}
});
}
}
答案 0 :(得分:1)
答案 1 :(得分:1)
model.setValueAt(new Object[]{"ewqeq","rtgre","gfdgd","mbmnb"}, 1, 4);
第一行不存在,因此您将获得ArrayIndexOutOfBoundsException.
因此,正如MadProgrammer建议使用addRow(..)方法并将您的对象传递给它。
示例:强>
model.addRow(new Object[]{"ewqeq","rtgre","gfdgd","mbmnb"});
<强>更新强>
您只定义了4列,因此索引将是0到3.但是您在setValueAt
方法中给出了4。所以问题仍然存在。将其更改为3。