简体   繁体   English

不断更新和更改JLabel中的文本

[英]Constantly updating and changing text in a JLabel

So I'm new to Java and learning to use Swing, and I'm currently working on a project that's assigned to me by my lecturer. 因此,我是Java的新手,正在学习使用Swing,并且我目前正在从事一个由讲师分配给我的项目。 It's some stupid version of some kind of bruteforcer that tries to guess a word typed by the user. 它是某种蛮力软件的愚蠢版本,试图猜测用户键入的单词。

Instead of printing all the guessed words, I want to have them shown in a JLabel that's on my UI. 我不想打印所有猜出的单词,而是希望将它们显示在UI上的JLabel中。 (This would constantly spam different combinations.) (这将不断向不同组合发送垃圾邮件。)

But the problem is: It only shows a guessed word after my program has finished running (so it found the word). 但是问题是:在我的程序完成运行后,它仅显示一个猜测的单词(因此它找到了单词)。

I've searched around and looked for an update method, but I can't seem to find where to actually use testField.setVisible(true); 我四处搜寻并寻找一种更新方法,但是我似乎找不到在哪里实际使用testField.setVisible(true); .

Program code: 程序代码:

package gui;
import static com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type.Int;
import java.util.Random; 
import java.util.Arrays;
import java.util.*;

public class bruteforcePanel extends javax.swing.JPanel {

    String[] Alphabet = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
    //String[] Alphabet = {"a"};
    boolean startGuessing = false;
    String pass;
    String[] word;
    String[] javaStuff;
    List<String> guessedWord = new ArrayList<String>();
    int amountOfGuesses;
    String labelGuess;

    private void startBruteforce(java.awt.event.ActionEvent evt) {                                 

        pass = textBoxPassword.getText();
        //this.testField.setText(pass);
        word = pass.split("");
        //System.out.println(Arrays.toString(word));
        startGuessing = true;
        while(startGuessing == true) {
            for (String i : word) {
                Random r=new Random();
                int randomNumber=r. nextInt(Alphabet. length);
                String chosenLetter = Alphabet[randomNumber];
                guessedWord.add(chosenLetter);
            }
            System.out.println(guessedWord);
            labelGuess = String.join("", guessedWord);
            this.testField.setText(labelGuess);
            if (guessedWord.equals(Arrays.asList(word))) {
                startGuessing = false;
                System.out.println(amountOfGuesses);
            } else {
               guessedWord.clear(); 
               amountOfGuesses += 1;
            }

        }
    }                                

    // Variables declaration - do not modify                     
    private javax.swing.JButton bruteforceButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel testField;
    private javax.swing.JTextField textBoxPassword;
    // End of variables declaration                   
}

Code from JPanel : (comes before the private void startBruteforce(java.awt.event.ActionEvent evt) {} ) 来自JPanel代码:(出现在private void startBruteforce(java.awt.event.ActionEvent evt) {}

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

        jPanel1 = new javax.swing.JPanel();
        textBoxPassword = new javax.swing.JTextField();
        bruteforceButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        testField = new javax.swing.JLabel();

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 146, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 205, Short.MAX_VALUE)
        );

        bruteforceButton.setText("Bruteforce");
        bruteforceButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                startBruteforce(evt);
            }
        });

        jLabel1.setText("Word:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(151, 151, 151)
                        .addComponent(bruteforceButton))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(15, 15, 15)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(testField)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(95, Short.MAX_VALUE)
                .addComponent(textBoxPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(90, 90, 90))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addComponent(textBoxPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(36, 36, 36)
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(bruteforceButton)
                        .addGap(9, 9, 9)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(testField))
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
        );
    }// </editor-fold> 

So like I said, I want my results to "spam" in the label. 因此,就像我说的那样,我希望我的结果在标签中“发送垃圾邮件”。

  1. You don't want to use a JLabel for this task but a JTextArea instead 您不想为此任务使用JLabel ,而是使用JTextArea
  2. You need to stop using bad words (even in the code) 您需要停止使用坏词(即使在代码中也是如此)
  3. Follow Java naming conventions and use them consistently. 遵循Java命名约定并一致地使用它们。
    • firstWordLowerCaseVariable
    • firstWordLowerCaseMethod()
    • FirstWordUpperCaseClass
    • ALL_WORDS_UPPER_CASE_CONSTANT
  4. For your UI to update after a new result is done, you're going to need a Swing Timer , for example: Creating an animated 4x4 grid in Java and jLabel won't show 为了在完成新结果后更新UI,您将需要一个Swing Timer ,例如: 用Java创建动画4x4网格,并且jLabel将不会显示
  5. And you'll need to call JPanel#revalidate() and JPanel#repaint() methods (in that order) inside the ActionListener of the Timer and you'll probably need to wrap the JTextArea inside a JScrollPane as well. 而且,您将需要在TimerActionListener中调用JPanel#revalidate()JPanel#repaint()方法( ActionListener顺序),并且可能还需要将JTextArea包装在JScrollPane中。

    And you need to use a Swing Timer and not a while or any other kind of loop, as they block the EDT preventing it from updating until the loop is done. 而且,您需要使用Swing Timer而不是while或任何其他类型的循环,因为它们会阻塞EDT,从而阻止其在循环完成之前进行更新。

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

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