简体   繁体   English

基于JComboBox值的Java JButton.setVisible

[英]Java JButton.setVisible based on JComboBox value

Ok, I'm stymied. 好吧,我受阻了。 I know I'm a Java noob, and I've done something stupid, but I hate to run to StackOverflow every time I'm stumped. 我知道我是Java新手,并且做过一些愚蠢的事情,但是我讨厌每次遇到麻烦时都要运行StackOverflow。 Anyway, here goes: 无论如何,这里是这样:

I'm building a simple little app with a form. 我正在用表单构建一个简单的小应用程序。 Fill out the form and it calculates some values for you. 填写表格,它会为您计算一些值。 I have a JComboBox that sets some default values in a series of JTextField's. 我有一个JComboBox,它在一系列JTextField中设置一些默认值。 There are a couple of buttons (that at this point, don't do anything) that I want to either be visible or hidden based on the value in the JComboBox. 根据JComboBox中的值,有几个按钮(此时不执行任何操作)是可见的还是隐藏的。 No biggie, right? 没关系,对吗?

Currently, I'm able to see and manipulate the JTextField's in the JComboBox's actionPerformed() method. 目前,我可以在JComboBox的actionPerformed()方法中查看和操作JTextField。 But if I try to do change the setVisible(true) on a JButton, I get a NullPointerException. 但是,如果我尝试在JButton上更改setVisible(true),则会收到NullPointerException。

I'll post some code, but not all of it. 我将发布一些代码,但不是全部。 I've been doing this in Eclipse Kepler with WindowBuilder (I know, I know...) so the code is fairly massive. 我一直在使用WindowsBuilder在Eclipse Kepler中进行此操作(我知道,我知道...),因此代码相当庞大。

Here's where one of the JTextFields and the JButton are defined: 这是定义JTextField和JButton之一的地方:

    txtAC = new JTextField();
    txtAC.setFont(new Font("Tahoma", Font.BOLD, 12));
    txtAC.setHorizontalAlignment(SwingConstants.CENTER);
    txtAC.setToolTipText("Enter the percentage of facility electric usage resulting from air conditioning.");
    txtAC.setForeground(new Color(0, 102, 204));
    txtAC.setBounds(143, 180, 53, 20);
    contentPane.add(txtAC);
    txtAC.setColumns(10);

    JButton btnAdd = new JButton("Add");
    btnAdd.setToolTipText("Click the Add button to include the custom facility type to the Facility Type dropdown list.");
    btnAdd.setBounds(573, 60, 89, 20);
    btnAdd.setVisible(false);
    contentPane.add(btnAdd);

Here's the actionPerformed method on the JComboBox: 这是JComboBox上的actionPerformed方法:

    final JComboBox cboFacilityType = new JComboBox();
    cboFacilityType.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            if (isInitCBO)
                return;

            String sql = "SELECT * FROM tblDefaultIndustry WHERE INDUSTRY = '" + cboFacilityType.getSelectedItem() +"'";


            try
            {
                rs = stmt.executeQuery(sql);
                while (rs.next())
                {
                    txtLighting.setText("");
                    txtAC.setText("");
                    txtRefrig.setText("");
                    txtEquip.setText("");
                    txtResistive.setText("");

                    if (rs.getString("INDUSTRY").equals("<User Defined>"))
                    {
                        usageFieldsEditable(true);
                        btnAdd.setVisible(true);
                        txtLighting.requestFocusInWindow();
                    }else{
                        txtLighting.setText(Integer.toString(rs.getInt(2)));
                        txtAC.setText(Integer.toString(rs.getInt(3)));
                        txtRefrig.setText(Integer.toString(rs.getInt(4)));
                        txtEquip.setText(Integer.toString(rs.getInt(5)));
                        txtResistive.setText(Integer.toString(rs.getInt(6)));
                        usageFieldsEditable(false);
                        btnAdd.setVisible(false);

                    }
                }
            }catch (SQLException e1)
            {
                e1.printStackTrace();
            }

        }

        private void usageFieldsEditable(boolean b) {
            // TODO Auto-generated method stub
            txtLighting.setEditable(b);
            txtAC.setEditable(b);
            txtRefrig.setEditable(b);
            txtEquip.setEditable(b);
            txtResistive.setEditable(b);
        }
    });

At first, the btnAdd acted like it didn't have any variable associated with it. 最初,btnAdd的行为就像它没有任何关联的变量。 I noticed that WindowBuilder had created private variables for the JTextFields but not the JButton. 我注意到WindowBuilder为JTextField创建了私有变量,但没有为JButton创建私有变量。 So I added one to see if that would work. 因此,我添加了一个以查看是否可行。 No dice. 没有骰子。 Didn't make sense anyway. 反正没道理。

Hopefully you have enough to go on here. 希望您有足够的机会继续进行下去。 It just doesn't make sense that the actionPerformed() method can see and manipulate a JTextField but not a button. actionPerformed()方法可以看到和操作JTextField而不是按钮是没有意义的。 They are in the same Panel and everything. 它们在同一小组中,并且在所有内容中。

Thanks for your sage wisdom. 感谢您的圣人智慧。

It definitely makes sense to have a field for the button, since the actionPerformed() method needs to access the button to meke it visible or hidden. 绝对有必要为按钮添加一个字段,因为actionPerformed()方法需要访问按钮才能使按钮可见或隐藏。 But you get a NullPointerException, which means that the btnAdd field is not initialized. 但是您会收到NullPointerException,这意味着btnAdd字段未初始化。 And indeed, instead of doing 实际上,与其做

this.btnAdd = new JButton("Add");

or simply 或简单地

btnAdd = new JButton("Add");

which would initialize the btnAdd field, you're doing 这将初始化btnAdd字段,您正在执行

JButton btnAdd = new JButton("Add");

That declares and initializes a local variable, which happens to have the same name as the btnAdd field, leaving this field uninitialized. 这将声明并初始化一个局部变量,该变量恰好与btnAdd字段具有相同的名称,而此字段未初始化。

Side notes: you should learn using layout managers instead of hard-coding bounds of components, making your app ugly on machines with different settings from yours. 旁注:您应该学习使用布局管理器,而不是对组件的边界进行硬编码,从而使应用程序在设置与您的设置不同的机器上很难看。 And you should also try not mixing data access code, using JDBC, with UI code. 而且,您还应该尝试不要将使用JDBC的数据访问代码与UI代码混合在一起。 Delegate the data access to another object. 将数据访问委托给另一个对象。

You have initialize JButton as 您已将JButton初始化为

JButton btnAdd = new JButton("Add");

which is local initialization of button variable and when you are trying to use the object of JButton it goes out of scope. 这是按钮变量的local initialization ,当您尝试使用JButton对象时,它超出了范围。

try this 尝试这个

Declare the JButton btnAdd; 声明JButton btnAdd; and then initialize this reference of button with 然后使用

btnAdd = new JButton("Add");

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

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