简体   繁体   English

如何向JTable添加数据

[英]How to add data to JTable

I'm still a little new to Java and a complete noob to Gui's. 我对Java还是有点陌生​​,对Gui来说还是个菜鸟。 I can't for the life of me figure out how to add the data from my String array into the Jtable. 我一辈子都想不通如何将String数组中的数据添加到Jtable中。 I tried to read the docs on oracle but it was not making sense to me for my particular situation. 我试图阅读有关oracle的文档,但是对于我的特殊情况,这对我来说没有任何意义。 If you guys could please point me in the right direction I would appreciate it. 如果你们能请我指出正确的方向,我将不胜感激。 Also I'm retrieving my array data from a file. 另外,我正在从文件中检索数组数据。 Not sure if that makes a difference. 不知道这是否有所作为。

    public class TemplateGui extends JFrame {
    private JTable tableHotelSecurity, securityFlagsTable;
    private final ButtonGroup buttonGroup = new ButtonGroup();
    private JTextField textField;
    private static String [] sortedRoles_Flags,finalFlagsArr,finalHSArr;
    private static String finalFlags="",finalHS="",column;


    public TemplateGui(){

        super("Galaxy Template Generator V1.0");
        getContentPane().setForeground(new Color(0, 0, 0));
        getContentPane().setLayout(null);
        getContentPane().setBackground(new Color(51, 51, 51));

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPane.setBounds(10, 170, 189, 186);
        getContentPane().add(scrollPane);

        JScrollPane scrollPane_1 = new JScrollPane();
        scrollPane_1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPane_1.setBounds(222, 170, 372, 186);
        getContentPane().add(scrollPane_1);

        //radio buttons
        JRadioButton rdbtnNewRadioButton = new JRadioButton("Central User ");
        rdbtnNewRadioButton.setFont(new Font("Tahoma", Font.BOLD, 11));
        rdbtnNewRadioButton.setBackground(Color.WHITE);
        buttonGroup.add(rdbtnNewRadioButton);
        rdbtnNewRadioButton.setBounds(222, 75, 127, 36);
        getContentPane().add(rdbtnNewRadioButton);

        final JRadioButton rdbtnPropertyUser = new JRadioButton("Property User");
        rdbtnPropertyUser.setFont(new Font("Tahoma", Font.BOLD, 11));
        rdbtnPropertyUser.setBackground(Color.WHITE);
        buttonGroup.add(rdbtnPropertyUser);
        rdbtnPropertyUser.setBounds(222, 38, 127, 34);
        getContentPane().add(rdbtnPropertyUser);

        textField = new JTextField();
        textField.setFont(new Font("Tahoma", Font.BOLD, 18));
        textField.setBounds(10, 35, 53, 34);
        getContentPane().add(textField);
        textField.setColumns(10);

        JLabel lblHotelSecurity = new JLabel("Hotel Security (H S)");
        lblHotelSecurity.setHorizontalAlignment(SwingConstants.CENTER);
        lblHotelSecurity.setFont(new Font("Tahoma", Font.BOLD, 13));
        lblHotelSecurity.setBounds(10, 144, 189, 23);
        lblHotelSecurity.setBackground(new Color(204, 204, 204));
        lblHotelSecurity.setOpaque(true);
        getContentPane().add(lblHotelSecurity);

        JLabel label = new JLabel("Security Flags (S F)");
        label.setHorizontalAlignment(SwingConstants.CENTER);
        label.setFont(new Font("Tahoma", Font.BOLD, 13));
        label.setBounds(222, 144, 372, 23);
        label.setBackground(new Color(204, 204, 204));
        label.setOpaque(true);
        getContentPane().add(label);

        JLabel lblEnterTemplateCode = new JLabel("ENTER TEMPLATE CODE");
        lblEnterTemplateCode.setForeground(new Color(255, 255, 255));
        lblEnterTemplateCode.setFont(new Font("Tahoma", Font.BOLD, 14));
        lblEnterTemplateCode.setBounds(10, 9, 175, 23);
        getContentPane().add(lblEnterTemplateCode);

        JLabel lblSelectUserRole = new JLabel("SELECT USER ROLE LEVEL");
        lblSelectUserRole.setForeground(new Color(255, 255, 255));
        lblSelectUserRole.setFont(new Font("Tahoma", Font.BOLD, 14));
        lblSelectUserRole.setBounds(222, 13, 195, 14);
        getContentPane().add(lblSelectUserRole);

        //Submit button action
        Button button = new Button("Generate Template");
        button.setFont(new Font("Dialog", Font.BOLD, 12));
        button.setBackground(new Color(102, 255, 102));
        button.setForeground(Color.BLACK);
        button.setBounds(467, 83, 127, 41);
        getContentPane().add(button);
        button.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {

                Query excell = new Query();
                //get template text
                String template = textField.getText().toUpperCase();
                System.out.println(template);

                if(rdbtnPropertyUser.isSelected()){
                    try {
                    //property user was selected
                        excell.runProcess(1);
                        System.out.println("you selected Property user");
                    } catch (IOException e) {

                        System.out.println("Error occured on line 70 Interface Class");
                    }
                }
                else{
                    try {
                    //Central User was selected 
                        excell.runProcess(2);
                        System.out.println("you selected central user");
                    } catch (IOException e) {

                        System.out.println("Error occured on line 79 Interface Class");
                    }
                }

                System.out.println("NOW WERE HERE");
                //get static variables from Excel Query 
                for(int i = 0; i< Query.sortedGF.length; i++)
                {
                    if(Query.sortedGF[i].contains(template)){
                         sortedRoles_Flags  =Query.sortedGF[i].split(" ");
                         System.out.println("THIS RAN"+" :"+i); 
                         break;
                    }

                }
                System.out.println("NOW WERE HERE 103 " +Query.securityFlags.length);
                //add data to table
                int j=0;
                int sizeOfFlags = Query.securityFlags.length;
                System.out.println("Size Of the Flags is:"+" "+sizeOfFlags);
                System.out.println("Size Of the Flags is:"+" "+sortedRoles_Flags.length);

                //Add HS to FinalHS Variable only if Yes
                for(int i=0;i< sortedRoles_Flags.length-sizeOfFlags;i++)
                {
                    if(sortedRoles_Flags[i].matches("Y|y|Y\\?|\\?Y|y\\?|\\?y"))
                        {
                            System.out.println("Hotel security:"+" "+sortedRoles_Flags[i]+" HS Added: "+Query.hotelSecurity[i]);
                            finalHS += Query.hotelSecurity[i]+" ";
                            System.out.println("Hotel security:"+" "+finalHS);
                        }
                }

                //add Security Flags to Final Flags
                for(int i=(sortedRoles_Flags.length-sizeOfFlags);i< sortedRoles_Flags.length;i++)
                {                   
                        finalFlags += Query.securityFlags[j]+": "+ sortedRoles_Flags[i]+" + ";
                        j++;
                }

                //Leave open just incase they would prefer a text file for template in which case we just write it
                System.out.println(finalFlags);

                System.out.println(finalHS);

                //Convert to String Arrays in order to add to our JTable
                finalFlagsArr= finalFlags.split("\\+");
                finalHSArr = finalHS.split(" ");



            }
        });
        //content to be in the table 
                DefaultTableModel modelH = new DefaultTableModel();
                tableHotelSecurity = new JTable(modelH);
                scrollPane.setViewportView(tableHotelSecurity);

                DefaultTableModel modelS = new DefaultTableModel();
                securityFlagsTable = new JTable(modelS);
                scrollPane_1.setViewportView(securityFlagsTable);

    }

}

Follow this tutorial: http://docs.oracle.com/javase/tutorial/uiswing/components/table.html 遵循本教程: http : //docs.oracle.com/javase/tutorial/uiswing/components/table.html

The main idea is, that swing is built on the principles of MVC architecture. 主要思想是,摇摆基于MVC架构的原理。 What that means for you is that the component that is responsible for displaying the table (JTable), and the component that knows what is in the table (TableModel) are separated. 对您而言,这意味着负责显示表的组件(JTable)和知道表中内容的组件(TableModel)是分开的。 You somehow need to pass the model to the table. 您需要以某种方式将模型传递给表。 You can either use the DefaultTableModel, which is what you did, or define your own model that implements the interface TableModel. 您可以使用您所做的DefaultTableModel,也可以定义自己的实现TableModel接口的模型。 For the first, you need to pass in an array to the constructor of DefaultTableModel. 首先,您需要将数组传递给DefaultTableModel的构造函数。 For the latter you need to implement methods that - among others - query data at certain positions, but this is worth considering only if the out of the box stuff does not do it for you. 对于后者,您需要实现一些方法,其中包括在某些位置查询数据的方法,但是仅当开箱即用的东西对您不利时才值得考虑。

On a side note about error messages: if you are serious about programming, don't get used to bad patterns. 关于错误消息的附带说明:如果您认真对待编程,请不要习惯不良的模式。 They might seem easier now, but they are ill-advised for a reason. 它们现在看起来似乎更容易,但是出于某种原因,它们是不明智的。 They usually don't scale well from a hello-world size project to a full blown project developed by multiple people. 他们通常不能很好地从一个大型的项目扩展到由多个人开发的完整项目。 Stacktrace is your friend. Stacktrace是您的朋友。 Use a logger instead of sysout. 使用记录器而不是sysout。 It will be easier for you in the long run if you get used to good practices now. 如果您现在习惯了良好的做法,从长远来看,这将对您来说更加容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM