我的DefaultTableModel没有显示?

时间:2014-07-24 09:16:25

标签: java mysql swing

我无法在我的框架内看到DefaultTableModel,请帮助..我在哪里做错了?

这是我的代码:

package phonebook;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;    
import java.awt.Font;    
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class MyProgram {

    private JFrame frame;
    private JTable table;
    private DefaultTableModel tableModel;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MyProgram window = new MyProgram();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public MyProgram() {
        initialize();
    }

    private void initialize() {

        tableModel=new DefaultTableModel();
        tableModel.addColumn("Name");
        tableModel.addColumn("Phone no.");
        tableModel.addColumn("City");
        tableModel.addColumn("Country");

        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        JMenuBar menuBar = new JMenuBar();
        menuBar.setBounds(0, 0, 434, 21);
        frame.getContentPane().add(menuBar);

        JMenu mnFile = new JMenu("File");
        menuBar.add(mnFile);

        JMenuItem mntmNew = new JMenuItem("New ");
        mnFile.add(mntmNew);

        JMenuItem mntmExit = new JMenuItem("Exit");
        mnFile.add(mntmExit);

        JMenu mnAbout = new JMenu("About");
        menuBar.add(mnAbout);

        JMenuItem mntmAbout = new JMenuItem("About");
        mnAbout.add(mntmAbout);

        JLabel lblNewLabel = new JLabel("Welcome to Phonebook diary by Rajendra arora");
        lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 18));
        lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
        lblNewLabel.setBounds(0, 21, 434, 50);

        frame.getContentPane().add(lblNewLabel);
        frame.add(new JScrollPane(table), BorderLayout.CENTER);

        table = new JTable(tableModel);
        table.setBounds(10, 260, 414, -189);
        frame.getContentPane().add(table);
    }
}

1 个答案:

答案 0 :(得分:4)

  1. setLayout(null); null布局总会回来咬你
  2. frame.add(new JScrollPane(table), BorderLayout.CENTER);这会在使用null布局时导致问题,因为组件的默认大小为0x0。此外,在调用此时,tablenull
  3. table.setBounds(10, 260, 414, -189)组件的大小不能为
  4. 不要在框架中添加菜单栏,而是使用setJMenuBar
  5. 如前所述,请使用适当的layout managers

    如果您找不到满足您需求的单一布局管理器,请不要害怕在多个容器中使用多个布局来构建您想要的效果