简体   繁体   English

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

[英]Check state and Uncheck state of JCheckBox MenuItem ActinListner

I have WordWrap checkBox MenuItem.By default it is unchecked(false) state.When I run the program and click on New menuitem and write some text after I click on WordWrap menuItem,The WordWrap state in not changed for first two times.I want to change the state(checked) for first time only.I had tried that but not working. 我有WordWrap复选框MenuItem。默认情况下为unchecked(false)状态。当我运行该程序并单击New menuitem并在单击WordWrap menuItem之后写一些文本时,WordWrap状态在前两次没有更改。我第一次尝试更改状态(已检查)。 Here is code: 这是代码:

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                   

} }

In your WordWrapActionPerformed method, you're doing nothing but adding an ItemListener to do, this won't do much... 在您的WordWrapActionPerformed方法中,除了添加ItemListener ,您什么都没做,这不会做太多...

Instead, you should simply carry out the requirements of the event, for example... 相反,您应该只执行事件的要求,例如...

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();
}

Either that or change the listener on the menu item in the GUI properties to use a ItemListener instead of an ActionListener 要么在GUI属性中更改菜单项上的侦听器,以使用ItemListener而不是ActionListener

You'll probably also want to become farmiluar with Code Conventions for the Java Programming Language , it will make your code eaiser to read for others ;) 您可能还想成为Java编程语言的代码约定的惯用语 ,这将使您的代码更容易为他人阅读;)

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

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