gpt4 book ai didi

java - JTextField ActionListener 不会更改 RGB 变量

转载 作者:行者123 更新时间:2023-12-01 09:40:32 25 4
gpt4 key购买 nike

我正在尝试创建一个程序,允许我更改 Text 类中的变量 R、G、B。每当我尝试运行小程序时,通过单击“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 吗?

我已经有一段时间没有使用swing了,但这是我的内存。你能尝试一下吗: https://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html

关于java - JTextField ActionListener 不会更改 RGB 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38490279/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com