Java / Swing - 如何从其他类访问JTextArea

时间:2016-10-19 07:46:33

标签: java swing nullpointerexception jtextarea

我想在我的JTextArea(ConsoleTxt)中显示我其他类的所有Printlns。我已经在其他类中引用了GUI类,但是 出现此错误:线程“AWT-EventQueue-0”中的异常java.lang.NullPointerException“

有我的GUI代码:

package Execucao;

import static java.lang.Thread.sleep;
import java.util.ArrayList;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;


public class Interface extends javax.swing.JFrame {

int pc = 0, opCode, op1, op2, rx, ry;
String iR;
int endereço = 0;
ArrayList<String> mem = new ArrayList<String>();


MemoryTable mCard = new MemoryTable();
UnidadeBusca b = new UnidadeBusca();
Decodificador dec = new Decodificador();
Registradores r = new Registradores();
Ula ula = new Ula();
MovimentoDados dFluxo = new MovimentoDados();
/**
 * Creates new form Interface
 */

public Interface(JTextArea ConsoleTxt) {
    this.ConsoleTxt = ConsoleTxt;
}

public Interface() {        

    this.endereço = endereço;
    initComponents();
    Op1Txt.setDocument(new LimDigit(6));
    Op2Txt.setDocument(new LimDigit(6));



public int executar() {
    append("Memória:");
    for(int i = 0; i < mem.size(); i++) {            
        String palavra = mem.get(i);
        append("|"+ palavra + "|");
    }

    while (pc < mem.size()){

        append("\nIniciando busca...");
        b.buscar(pc, mem);          
        iR = b.getiR();
        append("\nA palavra de endereço "+ pc +" é: "+ iR+".");

        append("\nDecodificando palavra...");
        dec.decodificar(pc, iR); 

        opCode = dec.getOperacao();
        op1 = dec.getOp1();
        op2 = dec.getOp2();

        append("\nCarregando valor do Operando 1 em Rx...");
        r.armazenarDado(op1);           
        rx = r.getRx();
        if (dec.decodId() == 0){
            append("\nCarregando valor do Operando 2 em Ry...");
            r.armazenarDado(op2);
            ry = r.getRy();
            append("\nExecutando Instrução...");
            ula.executarOp(opCode, rx, ry);
            dFluxo.executarOp(opCode, rx, ry);
        }
        else{
            append("\nExecutando Instrução...");
    ula.executarOp(opCode, rx, op2);
    dFluxo.executarOp(opCode, rx, op2);
        }

        r.zerarBanco();
        if (opCode == 6)
            pc = dFluxo.getPc();
        else
    pc++;
}
    return 0;
}


private void jBAdicionarActionPerformed(java.awt.event.ActionEvent evt) {                                            
    String OpCod = OpCodeTxt.getText();
    String Op1 = Op1Txt.getText();
    String OpId = Op2IdTxt.getText();
    String Op2 = Op2Txt.getText();
    String palavra = OpCod.concat(Op1).concat(OpId).concat(Op2);
    Object[] linha = {endereço, palavra};


    DefaultTableModel model = (DefaultTableModel) jTMemoria.getModel();

    endereço++;
    mem.add(palavra);
    model.addRow(linha);
}                                           

private void jRNotActionPerformed(java.awt.event.ActionEvent evt) {                                      
    if (jRNot.isSelected())
        OpCodeTxt.setText("000");
}                                     

private void jRAndActionPerformed(java.awt.event.ActionEvent evt) {                                      
    if (jRAnd.isSelected())
        OpCodeTxt.setText("001");
}                                     

private void jRAddActionPerformed(java.awt.event.ActionEvent evt) {                                      
    if (jRAdd.isSelected())
        OpCodeTxt.setText("010");
}                                     

private void jRSubActionPerformed(java.awt.event.ActionEvent evt) {                                      
    if (jRSub.isSelected())
        OpCodeTxt.setText("011");
}                                     

private void jRMovActionPerformed(java.awt.event.ActionEvent evt) {                                      
    if (jRMov.isSelected())
        OpCodeTxt.setText("100");
}                                     

private void jRJmpActionPerformed(java.awt.event.ActionEvent evt) {                                      
    if (jRJmp.isSelected())
        OpCodeTxt.setText("101");
}                                     

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

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

}                                      

private void jRHaltActionPerformed(java.awt.event.ActionEvent evt) {                                       
    if (jRHalt.isSelected())
        OpCodeTxt.setText("110");
}                                      

private void jBCompilarActionPerformed(java.awt.event.ActionEvent evt) {                                           
    executar();
}                                          

private void jRRegActionPerformed(java.awt.event.ActionEvent evt) {                                      
    if (jRReg.isSelected())
        Op2IdTxt.setText("0");
}                                     

private void jRImediatoActionPerformed(java.awt.event.ActionEvent evt) {                                           
    if (jRImediato.isSelected())
        Op2IdTxt.setText("1");
}                                          

public void append(String str){
    ConsoleTxt.append(str + "\n");
}

private void bTesteActionPerformed(java.awt.event.ActionEvent evt) {                                       
    String address = Integer.toString(jTMemoria.getRowCount());
    ConsoleTxt.setText("");
}                                      

public void setEndereço(int endereço) {
    this.endereço = endereço;
}

public int getEndereço() {
    return endereço;
}

public void setConsoleTxt(JTextArea ConsoleTxt){
    this.ConsoleTxt = ConsoleTxt;
}

public JTextArea getConsoleTxt(){
    return ConsoleTxt;
}

/**
 * @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(Interface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Interface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Interface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Interface.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() {
            Interface gui = new Interface();
            new Interface().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JTextArea ConsoleTxt;
private javax.swing.JTextField Op1Txt;
private javax.swing.JTextField Op2IdTxt;
private javax.swing.JTextField Op2Txt;
private javax.swing.JTextField OpCodeTxt;
private javax.swing.JButton bTeste;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.ButtonGroup buttonGroup2;
private javax.swing.JButton jBAdicionar;
private javax.swing.JButton jBCompilar;
private javax.swing.JButton jBRemove;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JPanel jPanel1;
private javax.swing.JRadioButton jRAdd;
private javax.swing.JRadioButton jRAnd;
private javax.swing.JRadioButton jRHalt;
private javax.swing.JRadioButton jRImediato;
private javax.swing.JRadioButton jRJmp;
private javax.swing.JRadioButton jRMov;
private javax.swing.JRadioButton jRNot;
private javax.swing.JRadioButton jRReg;
private javax.swing.JRadioButton jRSub;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable jTMemoria;
// End of variables declaration                   

}

还有我的其他类代码:

package Execucao;

import java.util.Scanner;
import javax.swing.JTextArea;

public class Decodificador {
    Scanner enter = new Scanner(System.in);

private int maskInst, maskRM, maskOp1, maskOp2, operacao, op1, op2, idOp2, opId, tipOp2, imediato, numDec;
String X, Y, TipOp2;

    private Interface w;

public Decodificador ()
{}

public Decodificador (int op1, int op2, int idOp2, int operacao, int opId, int numDec, Interface gui) {
    this.op1 = op1;
    this.op2 = op2;
    this.idOp2 = idOp2;
    this.operacao = operacao;
    this.opId = opId;
    this.numDec = numDec;
            w = gui;
    }

public int decodId() {

    idOp2 = ((numDec & maskRM) >> 6);

    switch(idOp2) {
    case 0: 
        TipOp2 = "ry";
        tipOp2 = 0;
        break;
    case 1: imediato = op2;
        TipOp2 = "imediato";
        tipOp2 = 1;
        break;
    }
    return tipOp2;
}


public int decodificar(int pc, String iR){
    numDec = 0;
    int j;
    int k = 0;

    for(j = 15; j >= 0; j--) {
        if (iR.charAt(j) == '1')
            numDec += Math.pow(2, k);
        k++;
    }
            System.out.println("Palavra "+(pc)+" convertida para decimal: "+ numDec + ".");
            w.append("Palavra "+(pc)+" convertida para decimal: "+ numDec + ".");

    maskInst = 0b1110000000000000;
    maskRM = 0b0000000001000000;
    maskOp1 = 0b0001111110000000;
    maskOp2 = 0b0000000000111111;


    operacao = ((numDec & maskInst) >> 13); 
    op1 = ((numDec & maskOp1) >> 7);
    op2 = (numDec & maskOp2);

    System.out.println("MASCARA DA OPERA��O:("+numDec+" & "+ maskInst +"): "+operacao+ ".");
    System.out.println("MASCARA DO OPERANDO 1:("+numDec+" & "+ maskOp1 +"): "+op1+ ".");
    System.out.println("MASCARA DO OPERANDO 2:("+numDec+" & "+ maskOp2 +"): "+op2+ ".");


    switch(operacao){
        case 0: 
            X = "lógica";
            Y = "NOT";
            break;
        case 1:
            X = "lógica";
            Y = "AND";
            break;
        case 2:
            X = "aritmética";
            Y = "ADD";
            break;
        case 3: 
            X = "aritmética";
            Y = "SUB";
            break;
        case 4: 
            X = "de desvio de fluxo";
            Y = "MOV";
            break;
        case 5: 
            X = "de desvio de fluxo";
            Y = "JMP";
            break;
                    case 6:
                            X = "de desvio de fluxo";
            Y = "HTL";
            break;
    }

    decodId();
    System.out.println("Operação "+ X + " " + Y +" com operando(s): " + op1 + "(rx) e " + op2 + "("+TipOp2+")." );
    return 0;
}

public int getOperacao() {
    return operacao;
}

public void setOperacao(int operacao) {
    this.operacao = operacao;
}

public int getOp1() {
    return op1;
}

public void setOp1(int op1) {
    this.op1 = op1;
}

public int getOp2() {
    return op2;
}

public void setOp2(int op2) {
    this.op2 = op2;
}

public int getIdOp2() {
    return idOp2;
}

public void setIdOp2(int idOp2) {
    this.idOp2 = idOp2;
}

public int getNumDec() {
    return numDec;
}

public void setNumDec(int numDec) {
    this.numDec = numDec;
}

public int getOpId() {
    return opId;
}

public void setOpId(int opId) {
    this.opId = opId;
}

错误:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at Execucao.Decodificador.decodificar(Decodificador.java:56)
at Execucao.Interface.executar(Interface.java:80)
at Execucao.Interface.jBCompilarActionPerformed(Interface.java:531)
at Execucao.Interface.access$1300(Interface.java:19)
at Execucao.Interface$15.actionPerformed(Interface.java:411)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6535)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6300)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4891)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4713)
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:2750)
at java.awt.Component.dispatchEvent(Component.java:4713)
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)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

你能帮帮我吗?

1 个答案:

答案 0 :(得分:0)

根据要求快速而肮脏:

public class TextFieldTest {
    static class Dto {
        private final SimpleStringProperty someStringProperty = new SimpleStringProperty();

        public SimpleStringProperty someStringProperty() {
            return someStringProperty;
        }

    }

    static class StringProvider {
        private final Dto dto;

        public StringProvider(Dto dto) {
            this.dto = dto;
        }

        public void requestInput() {
            JTextField jTextField = new JTextField();
            JOptionPane.showMessageDialog(null, jTextField);
            dto.someStringProperty().set(jTextField.getText());
        }
    }

    static class StringConsumer {
        private final Dto dto;

        public StringConsumer(Dto dto) {
            this.dto = dto;
            dto.someStringProperty
                    .addListener((ChangeListener<String>) (arg0, arg1, newString) -> System.out.println(newString));
        }

        @Override
        public String toString() {
            return "StringConsumer [string="
                    + dto.someStringProperty.get()
                    + "]";
        }
    }

    public static void main(String[] args) {
        Dto theModel = new Dto();
        StringConsumer stringConsumer = new StringConsumer(theModel);
        System.out.println(stringConsumer.toString());

        StringProvider stringProvider = new StringProvider(theModel);
        stringProvider.requestInput();
        System.out.println(stringConsumer.toString());
    }
}