java - JCheckBox MenuItem ActinListner 的检查状态和取消检查状态

标签 java swing awt jtextarea

我有 WordWrap 复选框菜单项。默认情况下,它处于未选中(假)状态。当我运行程序并单击“新建菜单项”并在单击“WordWrap 菜单项”后编写一些文本时,前两次 WordWrap 状态未更改。我只想第一次更改状态(选中)。我已经尝试过,但不起作用。 这是代码:

public class CheckBoxMenuItem extends javax.swing.JFrame {

int i=0;
JTextArea textArea;
JScrollPane scrollpane;
public CheckBoxMenuItem() {
    initComponents();
    WordWrap.setSelected(false);
}

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    tabbedPane = new javax.swing.JTabbedPane();
    jMenuBar1 = new javax.swing.JMenuBar();
    jMenu1 = new javax.swing.JMenu();
    Create = new javax.swing.JMenuItem();
    WordWrap = new javax.swing.JCheckBoxMenuItem();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jMenu1.setText("File");

    Create.setText("Create");
    Create.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            CreateActionPerformed(evt);
        }
    });
    jMenu1.add(Create);

    WordWrap.setSelected(true);
    WordWrap.setText("WordWrap");
    WordWrap.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            WordWrapActionPerformed(evt);
        }
    });
    jMenu1.add(WordWrap);

    jMenuBar1.add(jMenu1);

    setJMenuBar(jMenuBar1);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(tabbedPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(tabbedPane, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 279, Short.MAX_VALUE)
    );

    pack();
}// </editor-fold>                        

private void CreateActionPerformed(java.awt.event.ActionEvent evt) {                                       
   final JInternalFrame internalFrame = new JInternalFrame("");
    i++;
    internalFrame.setName("Document"+i);
    internalFrame.setClosable(true);
    internalFrame.setAutoscrolls(true);
    textArea=new JTextArea();
    textArea.setFont(new java.awt.Font("Miriam Fixed", 0, 13));
    scrollpane=new JScrollPane(textArea);
    internalFrame.add(scrollpane);
    tabbedPane.add(internalFrame);
    internalFrame.setSize(internalFrame.getMaximumSize());
    internalFrame.pack();
    internalFrame.setVisible(true);
}                                      

private void WordWrapActionPerformed(java.awt.event.ActionEvent evt) {                                         
    WordWrap.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent ie) {
           AbstractButton button = (AbstractButton) ie.getItem();
           if(button.isSelected()){
              textArea.setLineWrap(true);
              scrollpane.validate(); 
           }
           else
           {
             textArea.setLineWrap(false);
             scrollpane.validate();  
           }
        }
    });
}                                        

public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(CheckBoxMenuItem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(CheckBoxMenuItem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(CheckBoxMenuItem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(CheckBoxMenuItem.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            new CheckBoxMenuItem().setVisible(true);
        }
    });
}
// Variables declaration - do not modify                     
private javax.swing.JMenuItem Create;
private javax.swing.JCheckBoxMenuItem WordWrap;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JTabbedPane tabbedPane;
// End of variables declaration                   

}

最佳答案

在您的 WordWrapActionPerformed 方法中,您除了添加一个 ItemListener 之外什么也没做,这不会做太多事情...

相反,您应该简单地执行 Activity 的要求,例如......

private void WordWrapActionPerformed(java.awt.event.ActionEvent evt) {
    AbstractButton button = (AbstractButton) evt.getSource();
    if (button.isSelected()) {
        textArea.setLineWrap(true);
    } else {
        textArea.setLineWrap(false);
    }
    textArea.revalidate();
}

或者更改 GUI 属性中菜单项上的监听器以使用 ItemListener 而不是 ActionListener

您可能还想成为 Code Conventions for the Java Programming Language 的farmiluar ,这将使您的代码更容易被其他人阅读;)

关于java - JCheckBox MenuItem ActinListner 的检查状态和取消检查状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24135414/

相关文章:

java - 打印不带括号和逗号的数组

java - 如何在 persistence.xml 文件中包含外部实体

java - GridBagLayout 读取组件

java - 在面板之间交换

java - AWT 框架不处理事件

java - Container 类中 Paint(Graphics g) 方法中 Graphics g 的值

java - 从方法返回二维数组

java - GAE/GWT java 应用程序中的 OAuth2 token 无效

java - JComboBox 的圆角

java - Android中有没有像java.awt.Robot这样的类?