Java 为什么忽略按钮逻辑?
我正在编写一个加密程序,它将接收常规单词并将它们转换为特定的“代码”。所有操作都已完成,但程序忽略了提交按钮代码。我该怎么做才能解决这个问题Java 为什么忽略按钮逻辑?,java,swing,jbutton,Java,Swing,Jbutton,我正在编写一个加密程序,它将接收常规单词并将它们转换为特定的“代码”。所有操作都已完成,但程序忽略了提交按钮代码。我该怎么做才能解决这个问题 import javax.swing.*; import java.io.*; import java.awt.event.*; import java.awt.*; public class decode extends JFrame { private JTextArea textaci; pri
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();
}
}
“但是程序忽略了提交按钮代码。”
定义“忽略”。这个按钮对我来说很好用。只需向代码中添加一些System.out.println(…)语句,即可查看代码的哪些部分正在执行
代码将始终通过第一个if条件,因为源始终是submit按钮
您需要重新组织逻辑,因为else条件将永远不会执行。我尝试了代码<代码>clrtoci在第一次测试后始终为false。然后我查看了textaci.getText(),它显然不是
null
。我注意到前面用ciphertext
填充了它,因此该字符串可能不是null
编辑:
另外,(int i=0;i>=cleartextl;i++)的应该是(int i=0;i
这使它在我的机器上工作
`JButton
实例的操作侦听器工作正常。您的循环逻辑有问题。也就是说,你在无限循环
for(int i = 0;i >= cleartextl; i++){
//do stuff
}
应按如下方式重构:
for(int i = 0;i < cleartextl; i++){
//do stuff
}
for(int i=0;i
另外,从代码的质量来看,我建议您阅读以下教程:
JFrame
的大小,您会注意到有一个主要错误。我唯一的猜测是它可能无限循环,特别是因为打印
从未执行过。看看我的答案。