JTextField ActionListner不会更改RGB变量

时间:2016-07-20 20:29:24

标签: java swing jtextfield rgb actionevent

我试图创建一个程序,允许我更改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);



}

}

1 个答案:

答案 0 :(得分:1)

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

我有一段时间没有使用过摇摆,但这是我的记忆。你能尝试一下吗: https://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html