使用Dialog的易错点

container和panel在actionListener的添加顺序上有区别

  • panel的添加位置没什么限制

  • 而container在添加监听事件时必须添加在container.add()之前,否则会无效

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class checkPage extends JDialog implements ActionListener {
    public static JTable table=new JTable();
    public checkPage(JFrame frame)
    {
        super(frame,"购买查询页面",true);
        setBounds(50,50,500, 550);
        setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
        setLayout(new FlowLayout());

        Container container=getContentPane();  //创建一个容器

        fillTable(table);
        JScrollPane scroll=new JScrollPane(table);
        container.add(scroll);
        JButton jb=new JButton("仔细查询");
        jb.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new carefulCheckPage(frame);
            }
        });
        container.add(jb);
        container.validate();

        setVisible(true);
        validate();

    }

    public static void fillTable(JTable table)
    {
        DefaultTableModel tableModel=(DefaultTableModel) table.getModel();    //获得表格模型
        tableModel.setRowCount(0);    //清空表格中的数据
        tableModel.setColumnIdentifiers(new Object[]{"ID","商品名称","商品单价","商品数量"});    //设置表头
        tableModel.addRow(new Object[]{"001","pencil","13.3","10"});    //增加列
        table.setRowHeight(30);
        table.setModel(tableModel);
    }

    @Override
    public void actionPerformed(ActionEvent e) {

    }
}

你可能感兴趣的:(java)