创建程序以查找字符串

时间:2016-07-28 18:10:36

标签: java swing

我创建了一个查找字符串长度的程序。

这是我的代码:

    JTInputString = JTextfild ( For input )
    JLResult = Jlabel ( For Show Lenght )



    /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package UIs;

/**
 *
 * @author Mr-Enginner
 */
public class String extends javax.swing.JFrame {

    /**
     * Creates new form String
     */
    public String() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    public static void main(java.lang.String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new String().setVisible(true);
            }
        });
    }
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        JTInputString = new javax.swing.JTextField();
        JBCalculate = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        JLResult = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        JBCalculate.setText("محاسبه طول رشته");
        JBCalculate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JBCalculateActionPerformed(evt);
            }
        });

        jLabel1.setText("طول رشته :");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(JTInputString)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addGap(134, 134, 134)
                .addComponent(JBCalculate)
                .addContainerGap(147, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(JLResult)
                .addGap(104, 104, 104)
                .addComponent(jLabel1)
                .addGap(43, 43, 43))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(45, 45, 45)
                .addComponent(JTInputString, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(JBCalculate)
                .addGap(39, 39, 39)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(JLResult))
                .addContainerGap(115, Short.MAX_VALUE))
        );

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

    private void JBCalculateActionPerformed(java.awt.event.ActionEvent evt) {                                            
        Lenght();
        Clearform();
    }                                           

    /**
     * @param args the command line arguments
     */
    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(String.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(String.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(String.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(String.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new String().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton JBCalculate;
    private javax.swing.JLabel JLResult;
    private javax.swing.JTextField JTInputString;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration                   

public void Lenght(){
        String Str=JTInputString.getText();
        int str=Str.length();
       JLResult.setText(""+str);
}
public void Clearform(){
    JTInputString.setText("");
    JLResult.setText("");
}



}

我正在使用此代码。但没有显示任何东西:

java.lang.String Str = JTInputString.getText();
int str = Str.length();
JLResult.setText("" + str);

但它并没有让我知道JLResult

有什么问题?

错误

  

线程“AWT-EventQueue-0”中的异常java.lang.RuntimeException:无法编译的源代码 - 不兼容的类型:java.lang.String无法转换为UIs.String       在UIs.String.Lenght(String.java:137)       在UIs.String.JBCalculateActionPerformed(String.java:90)       在UIs.String.access $ 000(String.java:12)       在UIs.String $ 2.actionPerformed(String.java:47)       在javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)       在javax.swing.AbstractButton $ Handler.actionPerformed(AbstractButton.java:2348)       在javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)       在javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)       在javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)       at java.awt.Component.processMouseEvent(Component.java:6533)       在javax.swing.JComponent.processMouseEvent(JComponent.java:3324)       at java.awt.Component.processEvent(Component.java:6298)       at java.awt.Container.processEvent(Container.java:2236)       at java.awt.Component.dispatchEventImpl(Component.java:4889)       at java.awt.Container.dispatchEventImpl(Container.java:2294)       at java.awt.Component.dispatchEvent(Component.java:4711)       at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)       at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)       at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)       at java.awt.Container.dispatchEventImpl(Container.java:2280)       at java.awt.Window.dispatchEventImpl(Window.java:2746)       at java.awt.Component.dispatchEvent(Component.java:4711)       at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)       at java.awt.EventQueue.access $ 500(EventQueue.java:97)       at java.awt.EventQueue $ 3.run(EventQueue.java:709)       at java.awt.EventQueue $ 3.run(EventQueue.java:703)       at java.security.AccessController.doPrivileged(Native Method)       at java.security.ProtectionDomain $ JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)       at java.security.ProtectionDomain $ JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)       at java.awt.EventQueue $ 4.run(EventQueue.java:731)       at java.awt.EventQueue $ 4.run(EventQueue.java:729)       at java.security.AccessController.doPrivileged(Native Method)       at java.security.ProtectionDomain $ JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)       at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)       at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)       at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)       at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)       at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)       at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)       在java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

2 个答案:

答案 0 :(得分:2)

您正在设置标签的文本,然后立即将其清除。

private void JBCalculateActionPerformed(java.awt.event.ActionEvent evt) {
    Lenght();
    Clearform(); // <-- Remove this line
}

可替换地:

public void Clearform() {
    JTInputString.setText("");
    JLResult.setText("");    // <-- Remove this line
}

答案 1 :(得分:1)

这里的答案是更恰当地命名你的课程。您在java.lang.String和您的JFrame UIs.String之间存在命名冲突。

调用主框架TestFrame或对应用程序更有意义的内容,以避免命名冲突。

另外,请确保您的变量名称都以小写字母开头。你现在让变量看起来像是类。如果您不遵循标准的Java编码标准和惯例,您将在以后遇到很多问题。

Google Java标准与其他标准一样好。我建议你check them out

修改

这个答案是针对您发布的问题,包括无法编译的堆栈跟踪。

有关Clearform()方法的后续问题,因为它清除了控件的值。关于Clearform()的问题应该是对当前问题的另一个问题。