JTable没有出现 - 包含addRow

时间:2015-03-06 18:26:05

标签: java swing

代码运行没有错误,但JTable没有出现。

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import java.awt.Dimension;

public class CreateTable {

    public static void main(String[] args) { 
        //init table
        DefaultTableModel model = new DefaultTableModel();
        JTable table = new JTable(model);
        model.addColumn("col1");
        model.addColumn("col2");
        model.addColumn("col3");
        model.addColumn("col4");  

        for (int i=1;i<=100;i++){
           model.addRow(new Object[]{i,1,2,3});  //output jtable row
        }

        table.setPreferredScrollableViewportSize(new Dimension(500,50));
        table.setFillsViewportHeight(true);
        table.setSize(600, 200);
        table.setVisible(true);  
    }
}

2 个答案:

答案 0 :(得分:2)

您可以看到教程或示例(http://docs.oracle.com/javase/tutorial/uiswing/examples/components/

public static void main(String[] args) {
    //init frame - main component
    JFrame frame = new JFrame("SimpleTableDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Create and set up the content pane.
    JPanel panel = new JPanel();
    frame.setContentPane(panel);

    DefaultTableModel model = new DefaultTableModel();
    JTable table = new JTable(model);
    model.addColumn("col1");
    model.addColumn("col2");
    model.addColumn("col3");
    model.addColumn("col4");

    for (int i=1;i<=100;i++){
        model.addRow(new Object[]{i,1,2,3});  //output jtable row
    }
    table.setSize(600, 200);
    JScrollPane scrollPane = new JScrollPane(table);
    panel.add(scrollPane);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
}

答案 1 :(得分:2)

对于GUI,您需要一个&#34; Frame&#34;这基本上是一个窗口。然后,您可以向框架添加内容,即显示组件的方式。

import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class CreateTable {

public static void main(String[] args) { 
    //Create Frame
    JFrame myFrame = new JFrame("Testing");
    //Create panel
    JPanel myPanel = new JPanel();
    //init table
    DefaultTableModel model = new DefaultTableModel();
    JTable table = new JTable(model);
    model.addColumn("col1");
    model.addColumn("col2");
    model.addColumn("col3");
    model.addColumn("col4");  

    for (int i=1;i<=100;i++){
       model.addRow(new Object[]{i,1,2,3});  //output jtable row
    }

    table.setPreferredScrollableViewportSize(new Dimension(500,50));
    table.setFillsViewportHeight(true);
    table.setSize(600, 200);
    table.setVisible(true);  

    //Add table to the panel
    myPanel.add(table);
    //Add panel to frame
    myFrame.getContentPane().add(myPanel);
    //Set size of the frame in px
    myFrame.setSize(400,300);
    //Set frame to visible
    myFrame.setVisible(true);
    }
}