Кнопка логики игнорируется - почему? - PullRequest
0 голосов
/ 02 сентября 2011

Я пишу программу шифрования, которая будет принимать обычные слова и преобразовывать их в определенный «код». Все сделано, но программа игнорирует код кнопки отправки. Что я должен сделать, чтобы это исправить?

    import javax.swing.*;
    import java.io.*;
    import java.awt.event.*;
    import java.awt.*;
    public class decode extends JFrame {
    private JTextArea textaci;
    private JTextArea textaclr;
    private JLabel lclear;
    private JLabel lcipher;
    private JButton bsubmit;
    private String cleartext;
    private String ciphertext;
    private boolean clrtoci; 


    public decode(){
        super();
        setTitle("Decoder");
        setSize(300,200);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridBagLayout());
        GridBagConstraints c =new GridBagConstraints();
        c.fill=GridBagConstraints.VERTICAL;
        c.weightx=0.5;
        textaci=new JTextArea();
        textaclr=new JTextArea();
        lclear=new JLabel("cleartext:");
        lcipher=new JLabel("ciphertext:");
        bsubmit=new JButton("Submit");
        bsubmit.setActionCommand("enable");
        textaci.setEditable(true);
        textaci.setLineWrap(true);
        textaclr.setEditable(true);
        textaclr.setLineWrap(true);
        textaci.setText(ciphertext);
        c.gridx=0;
        c.gridy=0;
        add(lclear);
        c.gridx=1;
        c.gridy=0;
        add(textaclr);

        c.gridx=0;
        c.gridy=2;
        add(lcipher);
        c.gridx=3;
        c.gridy=4;
        add(textaci);
        add(bsubmit);



    //----------------------------------------------------------------------------\\
        TextFieldHandler hand=new TextFieldHandler();
        bsubmit.addActionListener(hand);
        setVisible(true);
    }
    public class TextFieldHandler implements ActionListener{
        public void actionPerformed(ActionEvent event){
        if(event.getSource()==bsubmit){
            cleartext=textaclr.getText();
            int cleartextl=cleartext.length();
             if(textaci.getText()==null){
            clrtoci=true;
        }
        else{
            clrtoci=false;
        }
             if(clrtoci==true){//if it's cleartext to ciphertext
                 for(int i=0;i>=cleartextl;i++){
                     if(cleartext.contains("a")){
                         ciphertext="3";
                     }
                     if(cleartext.contains("b")){
                         ciphertext="b";
                     }
                     //and so on and on to the rest of the alphabet
                                      }//end of for statement
                 textaci.setText(ciphertext);
                 setVisible(true);
                 System.out.print(ciphertext);
             }//if it's cleartext to ciphertext

        }//bsubmit logic
    }//end of event
        }//end of ActionListener


    public static void main(String[] args){
        new decode();
    }
}

Ответы [ 3 ]

6 голосов
/ 02 сентября 2011

"but the program is ignoring the submit button code."

Определить "игнорировать". Кнопка отлично работает для меня. Просто добавьте несколько операторов System.out.println (...) в код, чтобы увидеть, какие части кода выполняются.

Код всегда будет проходить через первое условие if, поскольку источником всегда будет кнопка отправки.

Вам необходимо реорганизовать логику, поскольку условие else никогда не будет выполнено.

2 голосов
/ 02 сентября 2011

Слушатель действия для экземпляра JButton работает просто отлично. Есть проблема с вашей логикой цикла. То есть вы бесконечно зацикливаетесь.

for(int i = 0;i >= cleartextl; i++){
    //do stuff
}

Это следует изменить следующим образом:

for(int i = 0;i < cleartextl; i++){
    //do stuff
}

Также, судя по качеству вашего кода, я рекомендую прочитать следующие уроки:

1 голос
/ 02 сентября 2011

Я попробовал код. clrtoci всегда ложно после первого теста. Затем я посмотрел на textaci.getText (), который явно не был null. Я отмечаю, что вы заполняете его ciphertext ранее, поэтому возможно, что эта строка не null.

Edit: Также for (int i = 0; i >= cleartextl; i++) должно быть for (int i = 0; i < cleartextl; i++) Это заставляет его работать на моей машине.

`

...