Search code examples
javaswingjframejscrollpanejtextarea

Is there a specific way for introducing a 'setText()' JTextArea method when using the NetBeans GUI Builder?


As a school project I've been asked to make a simple text-based RPG in an object-oriented manner and using a GUI. I recently discovered that the NetBeans IDE 12.1 features a helpful GUI builder, which helped me generate the basic JFrame and layout.

The window has a JScrollPane enabled JTextArea, a JTextField and two additional JTextAreas. The code looks like as follows:


    /**
     * Creates new form GUI
     */
    public BackupGUI() {
        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")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        scrollPrompt = new javax.swing.JScrollPane();
        storyPrompt = new javax.swing.JTextArea();
        commandLine = new javax.swing.JTextField();
        nullScrollPane = new javax.swing.JScrollPane();
        enemyInfo = new javax.swing.JTextArea();
        nullScrollPane1 = new javax.swing.JScrollPane();
        playerInfo = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(0, 0, 0));
        setUndecorated(true);

        scrollPrompt.setBackground(new java.awt.Color(51, 51, 51));
        scrollPrompt.setBorder(null);
        scrollPrompt.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        scrollPrompt.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPrompt.setViewportBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        scrollPrompt.setAutoscrolls(true);

        storyPrompt.setEditable(false);
        storyPrompt.setBackground(new java.awt.Color(51, 51, 51));
        storyPrompt.setColumns(20);
        storyPrompt.setFont(new java.awt.Font("Arial", 0, 24)); // NOI18N
        storyPrompt.setForeground(new java.awt.Color(153, 153, 153));
        storyPrompt.setLineWrap(true);
        storyPrompt.setRows(5);
        storyPrompt.setWrapStyleWord(true);
        storyPrompt.setBorder(null);
        storyPrompt.setCaretColor(new java.awt.Color(102, 102, 102));
        storyPrompt.setSelectedTextColor(new java.awt.Color(51, 51, 51));
        storyPrompt.setSelectionColor(new java.awt.Color(153, 153, 153));
        scrollPrompt.setViewportView(storyPrompt);

        commandLine.setBackground(new java.awt.Color(72, 72, 72));
        commandLine.setFont(new java.awt.Font("Yu Gothic UI Light", 0, 18)); // NOI18N
        commandLine.setText(">>> ");
        commandLine.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        commandLine.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                commandLineActionPerformed(evt);
            }
        });
        commandLine.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                commandLineKeyPressed(evt);
            }
        });

        nullScrollPane.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        nullScrollPane.setToolTipText("");
        nullScrollPane.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);

        enemyInfo.setBackground(new java.awt.Color(102, 102, 102));
        enemyInfo.setColumns(20);
        enemyInfo.setLineWrap(true);
        enemyInfo.setRows(5);
        enemyInfo.setWrapStyleWord(true);
        enemyInfo.setSelectedTextColor(new java.awt.Color(60, 60, 60));
        enemyInfo.setSelectionColor(new java.awt.Color(204, 204, 204));
        nullScrollPane.setViewportView(enemyInfo);

        nullScrollPane1.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
        nullScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);

        playerInfo.setBackground(new java.awt.Color(102, 102, 102));
        playerInfo.setColumns(20);
        playerInfo.setFont(new java.awt.Font("Segoe UI", 0, 18)); // NOI18N
        playerInfo.setLineWrap(true);
        playerInfo.setRows(5);
        playerInfo.setWrapStyleWord(true);
        playerInfo.setSelectedTextColor(new java.awt.Color(60, 60, 60));
        playerInfo.setSelectionColor(new java.awt.Color(204, 204, 204));
        nullScrollPane1.setViewportView(playerInfo);

        scrollPrompt.getVerticalScrollBar().setBackground(java.awt.Color.BLACK);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(commandLine, javax.swing.GroupLayout.PREFERRED_SIZE, 700, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(scrollPrompt))
                .addGap(0, 0, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(nullScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE)
                    .addComponent(nullScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(scrollPrompt, javax.swing.GroupLayout.PREFERRED_SIZE, 500, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, 0)
                .addComponent(commandLine))
            .addGroup(layout.createSequentialGroup()
                .addComponent(nullScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(nullScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        setSize(new java.awt.Dimension(960, 540));
        setLocationRelativeTo(null);
    }// </editor-fold>                        

    private void commandLineActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
    }                                           

    private void commandLineKeyPressed(java.awt.event.KeyEvent evt) {                                       
        if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_BACK_SPACE){
            String s = commandLine.getText();
            if (s.equals(">>> ")){
                evt.consume();
            }
        }
        if (!commandLine.getText().startsWith(">>> ")){
            commandLine.setText(">>>");
        }
    }                                      

    /**
     * @param args the command line arguments
     */

    public void create(){
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(BackupGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(BackupGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(BackupGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(BackupGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>

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

    // Variables declaration - do not modify                     
    private javax.swing.JTextField commandLine;
    private javax.swing.JTextArea enemyInfo;
    private javax.swing.JScrollPane nullScrollPane;
    private javax.swing.JScrollPane nullScrollPane1;
    public void setPlayerText(String t){
        playerInfo.setText(t);
        playerInfo.requestFocusInWindow();
    }
    private javax.swing.JTextArea playerInfo;
    private javax.swing.JScrollPane scrollPrompt;
    private javax.swing.JTextArea storyPrompt;
    // End of variables declaration                   
}

Within this code I tried to include a method with the functionality to change the text of one of the text areas whilst the program is running, however when I built and ran the program said functionality appeared not to work.

I was wondering if this is a fault on my part, or just a trait of the NetBeans GUI builder.

Any and all help is appreciated.


Solution

  • Okay, you've created the method to change the text within the playerInfo JTextArea but nowhere in your code do you call this method to actually make a text change. You can call this method after your JTextArea is initialized, for example:

    setPlayerText("I want this text in my PlayerInfo JTextArea!");
    

    I would suspect you want to do this from your commandLineActionPerformed method that is called from the commandLine actionPerformed event which is fired one the ENTER key is hit. In this case you might have something like this:

    private void commandLineActionPerformed(java.awt.event.ActionEvent evt) { 
        // Make sure something is provided within the Command 
        // Line JTextField, if not get outta here!.
        if (commandLine.getText().trim().isEmpty() || commandLine.getText().trim().equals(">>>")) {
            return;
        } 
        
        // Place NEW (overwrite) text within the playerInfo JTextArea.
        // To 'append' text you would need to do something different.
        setPlayerText(commandLine.getText().substring(3));
    }