【问题标题】:Setting JTextField visible on JRadioButton Click设置 JTextField 在 JRadioButton Click 上可见
【发布时间】:2015-11-30 10:08:02
【问题描述】:

我正在 Netbeans 中创建一个 GUI,我想设置一个文本字段以在选择单选按钮时显示。由于某种原因,检测到单选按钮单击,但文本字段在选择时未出现。有关如何处理此问题的任何建议?我的代码粘贴在下面。文本字段名为 newContainerNameInput,单选按钮为 newContainerRadioButton:

    containersButtonGroup.add(newContainerRadioButton);
    newContainerRadioButton.setText("Create a new container");
    newContainerRadioButton.addItemListener(new java.awt.event.ItemListener() {
        public void itemStateChanged(java.awt.event.ItemEvent evt) {
            newContainerRadioButtonItemStateChanged(evt);
        }
    });
    newContainerRadioButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            newContainerRadioButtonActionPerformed(evt);
        }
    });

    newContainerNameInput.setText("Enter new container name here");
    newContainerNameInput.setVisible(false);

private void newContainerRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                        
    System.out.println("test");
    newContainerNameInput.setVisible(true);
}  

【问题讨论】:

  • 你的私有方法运行了吗?你的代码的其余部分看起来如何?另外:为什么将事件作为参数传递给私有方法?
  • @Stultuske 是的,私有方法在我运行调试器时运行。 Netbeans 实际上会自动生成该代码,因此我无法编辑实际的 actionPerformed 方法,我只能编辑 newContainerRadioButtonActionPerformed 中的内容。
  • newContainerNameInput已添加到您的布局中,对吗?分享一些关于如何在视图中添加文本和按钮的代码?
  • 是的,我有 newContainerNameInput = new javax.swing.JTextField();然后 .addComponent(newContainerNameInput, javax.swing.GroupLayout.PREFERRED_SIZE, 291, javax.swing.GroupLayout.PREFERRED_SIZE)) 当我创建一个新的 GroupLayout
  • 当你选择正确的RadioButton时,你有控制台输出吗..?这意味着"test"这个词正在打印..?

标签: java swing user-interface netbeans


【解决方案1】:

替换RadioButtonActionListener中的以下代码

private void newContainerRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                        
  System.out.println("test");
  newContainerNameInput.setVisible(true);
  revalidate();
} 

revalidate() 正在做两件事。首先是invalidate()validate()。通过这样做,您的组件将被标记为无效并再次验证。这意味着再次布局。有关更多信息,请参阅javadoc

【讨论】:

  • 谢谢!这很有效,感谢您的解释!
猜你喜欢
  • 1970-01-01
  • 2012-12-14
  • 2010-11-19
  • 2013-09-25
  • 1970-01-01
  • 2017-09-26
  • 1970-01-01
  • 1970-01-01
  • 2019-11-09
相关资源
最近更新 更多