Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用java在AbstractTableModel中显示数据?_Java_Database_Swing_Jframe_Abstracttablemodel - Fatal编程技术网

如何使用java在AbstractTableModel中显示数据?

如何使用java在AbstractTableModel中显示数据?,java,database,swing,jframe,abstracttablemodel,Java,Database,Swing,Jframe,Abstracttablemodel,我已经创建了一个AbstractTableModel,我想创建一个AbstractTableModel,以便在灰色框中使用dbquery显示数据库中的数据 这是我第一次这样做,我已经挣扎了很长时间,真的希望得到一些帮助!多谢各位 JButton btnSubmit = new JButton("Submit"); btnSubmit.addActionListener(new ActionListener() { public void actionPerformed(A

我已经创建了一个AbstractTableModel,我想创建一个AbstractTableModel,以便在灰色框中使用dbquery显示数据库中的数据

这是我第一次这样做,我已经挣扎了很长时间,真的希望得到一些帮助!多谢各位

JButton btnSubmit = new JButton("Submit");
    btnSubmit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            boolean conditionOK = false;

            if(chckbxr.isSelected()==false && chckbxr_1.isSelected()==false && chckbxr_2.isSelected()==false && chckbxr_3.isSelected()==false){
                JOptionPane.showMessageDialog(frame,"Please select client account");
            }
            else if(fromDate.getText().equals("")){
                JOptionPane.showMessageDialog(frame, "Please enter starting date");
            }
            else if(toDate.getText().equals("")){
                JOptionPane.showMessageDialog(frame, "Please enter end date");
            }
            else if(Integer.parseInt(fromDate.getText()) > Integer.parseInt(toDate.getText())){
                JOptionPane.showMessageDialog(frame, "End date is earlier than starting date");
            }
            else
            conditionOK = true;

            if(conditionOK==true){

                int fromYear = Integer.parseInt(fromDate.getText().substring(0, 4));
                int fromMonth = Integer.parseInt(fromDate.getText().substring(4,6))-1;
                int fromDay = Integer.parseInt(fromDate.getText().substring(6,8));
                int toYear = Integer.parseInt(toDate.getText().substring(0, 4));
                int toMonth = Integer.parseInt(toDate.getText().substring(4,6))-1;
                int toDay = Integer.parseInt(toDate.getText().substring(6,8));

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
                SimpleDateFormat sdf2 = new SimpleDateFormat("dd MMM yyyy");
                DateFormat formatter;
                formatter = new SimpleDateFormat("yyyy-MM-dd");

                Calendar convertedToDate = Calendar.getInstance();
                convertedToDate.set(toYear,toMonth,toDay);
                Calendar convertedFromDate =Calendar.getInstance();
                convertedFromDate.set(fromYear,fromMonth,fromDay);

                int MonthDifferenceCount = 1;
                //calculate months difference
                for ( MonthDifferenceCount=1; convertedFromDate.compareTo(convertedToDate) <0; MonthDifferenceCount++)
                {
                    convertedFromDate.add(Calendar.MONTH, 1);
                    convertedFromDate.set(convertedFromDate.DAY_OF_MONTH,convertedFromDate.getActualMaximum(Calendar.DAY_OF_MONTH));
                }

                convertedToDate.set(toYear,toMonth,toDay);
                convertedFromDate.set(fromYear,fromMonth,fromDay);


                //DateArray and PreDate Array are used to store date as date format. Shall be use for tradeDate and SetlDate
                Date preDateArray[] = new Date[MonthDifferenceCount];
                Date DateArray [] = new Date[MonthDifferenceCount];
                for (int i=0; i <MonthDifferenceCount; i++)
                {
                    convertedFromDate.add(Calendar.MONTH,-1);
                    convertedFromDate.set(convertedFromDate.DAY_OF_MONTH,convertedFromDate.getActualMaximum(Calendar.DAY_OF_MONTH));
                    preDateArray[i] = convertedFromDate.getTime();
                    try {
                        preDateArray[i] = (Date)formatter.parse(sdf.format(preDateArray[i]));
                    } catch (ParseException e1) {
                        e1.printStackTrace();
                    }  

                    convertedFromDate.add(Calendar.MONTH, 1);
                    convertedFromDate.set(convertedFromDate.DAY_OF_MONTH,convertedFromDate.getActualMaximum(Calendar.DAY_OF_MONTH));
                    DateArray[i] = convertedFromDate.getTime();
                    try {
                        DateArray[i] = (Date)formatter.parse(sdf.format(DateArray[i]));
                    } catch (ParseException e1) {
                        e1.printStackTrace();
                    }  
                    convertedFromDate.add(Calendar.MONTH, 1);   
                }

                summaryFromDate = sdf2.format(DateArray[0]);
                summaryToDate = sdf2.format(DateArray[DateArray.length-1]);

                String DateList[] = new String[MonthDifferenceCount];
                String PreDateList[] = new String[MonthDifferenceCount];
                for (int i=0; i<DateArray.length; i++)  
                {
                    DateList[i] = sdf1.format(DateArray[i]);
                    PreDateList[i] = sdf1.format(preDateArray[i]);
                }


                ArrayList<String> cltAccList = new ArrayList<String>();

                if(chckbxr.isSelected()==true){
                    cltAccList.add("10190R");
                }
                if(chckbxr_1.isSelected()==true){
                    cltAccList.add("10230R");
                }
                if(chckbxr_2.isSelected()==true){
                    cltAccList.add("10280R");
                }
                if(chckbxr_3.isSelected()==true){
                    cltAccList.add("10290R");
                }
            }
        }
    });
    btnSubmit.setBounds(37, 643, 89, 23);
    add(btnSubmit);
JButton btnSubmit=新JButton(“提交”);
btnSubmit.addActionListener(新ActionListener(){
已执行的公共无效操作(操作事件e){
布尔条件OK=false;
如果(chckbxr.isSelected()==false&&chckbxr_1.isSelected()==false&&chckbxr_2.isSelected()==false&&chckbxr_3.isSelected()==false){
showMessageDialog(框架“请选择客户帐户”);
}
else if(fromDate.getText().equals(“”){
showMessageDialog(框架“请输入开始日期”);
}
else if(toDate.getText().equals(“”){
showMessageDialog(框架“请输入结束日期”);
}
else if(Integer.parseInt(fromDate.getText())>Integer.parseInt(toDate.getText()){
showMessageDialog(框架,“结束日期早于开始日期”);
}
其他的
conditionOK=true;
if(conditionOK==true){
int fromYear=Integer.parseInt(fromDate.getText().substring(0,4));
int fromMonth=Integer.parseInt(fromDate.getText().substring(4,6))-1;
int fromDay=Integer.parseInt(fromDate.getText().substring(6,8));
int toYear=Integer.parseInt(toDate.getText().substring(0,4));
inttomonth=Integer.parseInt(toDate.getText().substring(4,6))-1;
inttoday=Integer.parseInt(toDate.getText().substring(6,8));
SimpleDataFormat sdf=新SimpleDataFormat(“yyyy-MM-dd”);
SimpleDataFormat sdf1=新的SimpleDataFormat(“yyyyMMdd”);
SimpleDataFormat sdf2=新的SimpleDataFormat(“dd MMM yyyy”);
数据格式格式化程序;
格式化程序=新的SimpleDataFormat(“yyyy-MM-dd”);
Calendar convertedToDate=Calendar.getInstance();
convertedToDate.set(今年、明天、今天);
Calendar convertedFromDate=Calendar.getInstance();
convertedFromDate.set(fromYear、fromMonth、fromDay);
int MonthDifferenceCount=1;
//计算月差

对于(MonthDifferenceCount=1;convertedFromDate.compareTo(convertedToDate)默认情况下,您的
数组将初始化为一对
null
条目

Object[] value = new Object[2];
请尝试以下方法:

for (int i = 0; i < 50; i++) {
    Object[] value = new Object[]{"Name" + i, Math.random() < .5 ? "M" : "F"};
    data.add(value);
}
for(int i=0;i<50;i++){
Object[]value=new Object[]{“Name”+i,Math.random()<.5?“M”:“F”};
数据增值;
}

我附上一个完整的情况示例:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

/**
 * Example class to learn how to use AbstractTableModel
 * 
 * @author Moreno
 *
 */
public class Example extends JFrame {

    private static final long serialVersionUID = 1L; // default serialVersionUID

    /**
     * Example class, is a JFrame
     * 
     */
    public Example() {
        super("Example");

        TableModelCustom myModel = new TableModelCustom();  //Create my table model
        JTable table = new JTable(myModel);                 //Create JTable
        table.setPreferredScrollableViewportSize(new Dimension(480, 70));   //Prefered size scroll

        JScrollPane scrollPane = new JScrollPane(table);    //Create scroll with table

        JButton button = new JButton("Click me");           //Create JButton
        JButton button2 = new JButton("Click me2");         //Create JButton2
        button.addActionListener(new ActionListener() {     //Listener onClick...

            @Override
            public void actionPerformed(ActionEvent e) {
                //Change data
                Object[][] data = { { "Rick", "Mourt", "Main Street", 55, true} };

                //Send data to the model
                myModel.setData(data);
            }
        });

        button2.addActionListener(new ActionListener() {        //Listener onClick...

            @Override
            public void actionPerformed(ActionEvent e) {
                //Change data
                Object[][] data = { { "Thomas", "Mourt", "Main Street 50", 55, true },
                        { "Rich", "Fua", "Main Street 2", 25, false }, 
                        { "Alan", "Poe", "Main Street 3", 12, true } };

                //Send data to the model
                myModel.setData(data);
            }
        });

        //Add components to the window
        add(button, BorderLayout.NORTH);        //Add first button
        add(scrollPane, BorderLayout.CENTER);   //Add scroll pane
        add(button2, BorderLayout.SOUTH);       //Add first button


        pack();
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    /**
     * Model
     * 
     * @author Moreno
     *
     * @see AbstractTableModel
     */
    class TableModelCustom extends AbstractTableModel {
        private static final long serialVersionUID = 1L;

        // Columns
        private String[] columnNames = { "Name", "Surname", "Direction", "Age", "Sport" };
        // Data
        private Object[][] data = { { "Peter", "Serry", "Rue....", 5, false },
                { "Paul", "Hey", "XXX", 13, true },
                { "Patriks", "--", "XXX", 26, false },
                { "Alice", "Hall", "XXX", 24, true },
                { "Mary", "Houstong", "XXX", 12, false } };

        /**
         * This method receives the new data vector, and update the table
         * 
         * @param data
         *            with new values
         */
        public void setData(Object[][] data) {
            this.data = data;       //Save data..
            fireTableDataChanged(); //Update table
        }

        public int getColumnCount() {
            return columnNames.length;
        }

        public int getRowCount() {
            return data.length;
        }

        public String getColumnName(int col) {
            return columnNames[col];
        }

        public Object getValueAt(int row, int col) {
            return data[row][col];
        }

        public void setValueAt(Object value, int row, int col) {
            data[row][col] = value;
            fireTableCellUpdated(row, col);

        }


    }

    public static void main(String[] args) {
        new Example();  //Create the window
    }
}

请根据您的需要调整它

Oracle教程中的工作代码示例-如何使用表,或ResultSetTableModel,或TableFromDatabase,投票关闭为什么不发布您编写的代码?到目前为止,如果您能获得一些代码,我们将不胜感激support@kaya我已经编辑了我的帖子,基本上我想做的就是显示那些在一段时间内完成。我已经有了生成数据的sql查询。我现在面临的问题是创建一个表并在JFrame中显示它。感谢您的回复:)这是您的实际代码?如果我理解正确,您还没有开始实现Tablemodel?@kaya嗨,我刚刚完成Tablemodel,很抱歉给您带来不便!
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

/**
 * Example class to learn how to use AbstractTableModel
 * 
 * @author Moreno
 *
 */
public class Example extends JFrame {

    private static final long serialVersionUID = 1L; // default serialVersionUID

    /**
     * Example class, is a JFrame
     * 
     */
    public Example() {
        super("Example");

        TableModelCustom myModel = new TableModelCustom();  //Create my table model
        JTable table = new JTable(myModel);                 //Create JTable
        table.setPreferredScrollableViewportSize(new Dimension(480, 70));   //Prefered size scroll

        JScrollPane scrollPane = new JScrollPane(table);    //Create scroll with table

        JButton button = new JButton("Click me");           //Create JButton
        JButton button2 = new JButton("Click me2");         //Create JButton2
        button.addActionListener(new ActionListener() {     //Listener onClick...

            @Override
            public void actionPerformed(ActionEvent e) {
                //Change data
                Object[][] data = { { "Rick", "Mourt", "Main Street", 55, true} };

                //Send data to the model
                myModel.setData(data);
            }
        });

        button2.addActionListener(new ActionListener() {        //Listener onClick...

            @Override
            public void actionPerformed(ActionEvent e) {
                //Change data
                Object[][] data = { { "Thomas", "Mourt", "Main Street 50", 55, true },
                        { "Rich", "Fua", "Main Street 2", 25, false }, 
                        { "Alan", "Poe", "Main Street 3", 12, true } };

                //Send data to the model
                myModel.setData(data);
            }
        });

        //Add components to the window
        add(button, BorderLayout.NORTH);        //Add first button
        add(scrollPane, BorderLayout.CENTER);   //Add scroll pane
        add(button2, BorderLayout.SOUTH);       //Add first button


        pack();
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    /**
     * Model
     * 
     * @author Moreno
     *
     * @see AbstractTableModel
     */
    class TableModelCustom extends AbstractTableModel {
        private static final long serialVersionUID = 1L;

        // Columns
        private String[] columnNames = { "Name", "Surname", "Direction", "Age", "Sport" };
        // Data
        private Object[][] data = { { "Peter", "Serry", "Rue....", 5, false },
                { "Paul", "Hey", "XXX", 13, true },
                { "Patriks", "--", "XXX", 26, false },
                { "Alice", "Hall", "XXX", 24, true },
                { "Mary", "Houstong", "XXX", 12, false } };

        /**
         * This method receives the new data vector, and update the table
         * 
         * @param data
         *            with new values
         */
        public void setData(Object[][] data) {
            this.data = data;       //Save data..
            fireTableDataChanged(); //Update table
        }

        public int getColumnCount() {
            return columnNames.length;
        }

        public int getRowCount() {
            return data.length;
        }

        public String getColumnName(int col) {
            return columnNames[col];
        }

        public Object getValueAt(int row, int col) {
            return data[row][col];
        }

        public void setValueAt(Object value, int row, int col) {
            data[row][col] = value;
            fireTableCellUpdated(row, col);

        }


    }

    public static void main(String[] args) {
        new Example();  //Create the window
    }
}