Java – JTable column headings are not displayed, but ‘a’, ‘B’,
•
Java
I'm new to the Java GUI and I'm trying to make a table containing my socerteam score results
At first I used the defaulttablemodel, and there was no problem with my column name They performed well with JScrollPane Then I want to try to implement my own tablemodel, and I will never see my table column header again They are displayed as' a ',' B ',' g ', and I'm still using scrollpane I need this tablemodel because I plan to add something else with exactly the same structure
Anyone can help me and try to solve the problem
thank you
class MyTableModel extends AbstractTableModel{ private String[] titles; private Object[][] data; public MyTableModel(String [] t,Object [][] d){ this.titles = t; this.data = d; } public Object getValueAt(int row,int col){ return data[row][col]; } public int getColumnCount(){ return titles.length; } public int getRowCount(){ return data.length; } } public static void main(String[] args) { SwingUtilities.invokelater(new Runnable() { public void run() { createAndShowGUI(); } }); } public JPanel createContentPane(){ mainPanel = new JPanel(); mainPanel.setLayout(new BorderLayout(10,10)); String [] titles = {"Naam","Doelpunten","% Doelpunten","Assists","% Assists","","% Totaal"}; Object [][] data = new Object[spelers.size()][titles.length]; int counter = 0; spelers = getSpelersFromDB("all"); for (Iterator<Speler> iter = spelers.iterator(); iter.hasNext();){ Speler temp = iter.next(); data[counter][0] = temp.naam; data[counter][1] = temp.doelpunten; data[counter][2] = String.format("%3.1f %%",berekenPercentageDoelpunten(temp)); data[counter][3] = temp.assists; data[counter][4] = String.format("%3.1f %%",berekenPercentageAssists(temp)); data[counter][5] = ""; data[counter][6] = String.format("%3.1f %%",berekenTotaalPercentage(temp)); counter += 1; } JTable table = new JTable(new MyTableModel(titles,data)); JScrollPane scrollPane = new JScrollPane(table); scrollPane.setPreferredSize(new Dimension(500,500)); mainPanel.add(scrollPane,BorderLayout.CENTER); mainPanel.setOpaque(true); return mainPanel; } private static void createAndShowGUI(){ frame.setMinimumSize(new Dimension(700,300)); frame.setPreferredSize(new Dimension(700,500)); frame.setMaximumSize(new Dimension(800,800)); Voetbal demo = new Voetbal(); frame.setContentPane(demo.createContentPane()); frame.setJMenuBar(demo.createJMenuBar()); frame.setVisible(true); frame.pack(); frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE); }
Solution
Abstracttablemodel will always return 'a', 'B' As the column name (check the document), all you need to do is override the getcolumnname() method, for example:
public String getColumnName(int column) { return titles[column] }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码