This question already has answers here:
What is a NullPointerException, and how do I fix it?

(12个答案)


3年前关闭。




我试图创建一个程序,使我可以更改Text类中的变量R,G,B。每当我尝试运行Applet时,通过单击“ SubmitR”按钮,它都会在线程“ AWT-EventQueue-1” java.lang.NullPointerException中给我一个异常。

public class Main extends JApplet {
private ButtonHandlerR buttonHandlerR;




@Override
public void start() {
    super.start();
}


@Override
public void init() {


    this.setSize(750, 300);

    setLayout(new BorderLayout());

    add(new SetTextColour(), BorderLayout.NORTH);
    add(new Text(),BorderLayout.CENTER);






}


}

public class SetTextColour extends JPanel {


private JLabel labelR;
private JLabel labelG;
private JLabel labelB;

public JTextField textR;
public JTextField textG;
public JTextField textB;

public JButton submitR;
public JButton submitG;
public JButton submitB;


public SetTextColour() {

    labelR = new JLabel("RED: ");
    labelG = new JLabel("GREEN: ");
    labelB = new JLabel("BLUE: ");

    textR = new JTextField(10);
    textB = new JTextField(10);
    textG = new JTextField(10);


    add(textR, BorderLayout.NORTH);
    submitR = new JButton("SubmitR");
    add(submitR, BorderLayout.NORTH);

    add(textB, BorderLayout.NORTH);

    submitG = new JButton("SubmitG");
    add(submitG, BorderLayout.NORTH);

    add(textG, BorderLayout.NORTH);

    submitB = new JButton("SubmitB");
    add(submitB, BorderLayout.NORTH);

    ButtonHandlerB BHB = new ButtonHandlerB();
    ButtonHandlerG BHG = new ButtonHandlerG();
    ButtonHandlerR BHR = new ButtonHandlerR(this);

    submitB.addActionListener(BHB);
    submitR.addActionListener(BHR);
    submitG.addActionListener(BHG);


}


}

public class ButtonHandlerR implements ActionListener {
private SetTextColour colour;
private Text text;


ButtonHandlerR(Text change){
    this.text = change;

}

ButtonHandlerR(SetTextColour set){
    this.colour = set;

}






@Override
public void actionPerformed(ActionEvent e) {

    JButton Clicked = (JButton) e.getSource();
    double tempV;
    int tempV2;

    if(colour.submitR == Clicked){
        tempV = Double.parseDouble(colour.textR.getText());
        tempV2 = (int) tempV;
        text.R = tempV2;
        System.out.println(text.R);
        text.repaint();


    }



}


}

public class Text extends JApplet {
private String textField = "Welcome to CE203 Assignment 1 - Hassan Khan, 1404460";
 public int R=50;
 private int G=32;
 private int B=54;

public void start(){

}





public void init(){




}

public void paint (Graphics g) {


    Color customColor = new Color(R, G, B);

    g.setColor(customColor);

    g.drawString(textField, 125, 150);



}


}

最佳答案

您不应该在这里使用SwingUtilities.invokeLater或SwingUtilities.invokeAndWait吗?

我已经有一段时间没有使用秋千了,但这是我的记忆。您可以尝试一下:
https://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html

10-06 01:27