[英]jPanel button triggering another class in java
So, I have a Class called Math
, that runs a small piece of code, and another class called GUI that holds a button and a text box. 因此,我有一个名为
Math
的类,该类运行一小段代码,还有一个名为GUI的类,其中包含一个按钮和一个文本框。 I need to make it so pressing the button runs the Math class. 我需要做到这一点,以便按下按钮可以运行Math类。
In the Math Class: 在数学课中:
public class Math {
public static int com;
public static void main (String[] args) {
com = GUI.num1 * GUI.num2;
GUI.TextBox3.setText(com);
}
}
In the GUI class (It's jPanel, by the way): 在GUI类中(顺便说一下,它是jPanel):
public class GUI extends javax.swing.JFrame {
public static int num1;
public static int num2;
public GUI() {
initComponents();
}
private void Button1ActionPerformed(java.awt.event.ActionEvent evt) {
num1 = Integer.parseInt(TextBox1.getText());
num1 = Integer.parseInt(TexBox2.getText());
Math.main (Sring[] );//This is the part the doesn't work
}
If you could help, that would be great, thanks! 如果您能提供帮助,那就太好了,谢谢!
You better don't call your class Math
since java already have a class called like this, it might create some conflict. 最好不要调用
Math
类,因为java已经有一个像这样的类,它可能会产生一些冲突。
What is your error? 你怎么了
Looking at your code, a don't understand how your Math class can access your GUI, is this all the code? 在查看您的代码时,您不了解Math类如何访问您的GUI,这就是全部代码吗?
You better replace your Math.main(...) with : 您最好将Math.main(...)替换为:
private void Button1ActionPerformed(java.awt.event.ActionEvent evt) {
num1 = Integer.parseInt(TextBox1.getText());
num2 = Integer.parseInt(TexBox2.getText());
TextBox3.setText(String.valueOf(num1 * num2));
}
Edit, fixed an error 编辑,修复错误
class MyClass {
public static int com;
public static void Method()
{
com = GUI.num1 * GUI.num2;
GUI.TextBox3.setText(""+com);
}
}
And 和
private void Button1ActionPerformed(java.awt.event.ActionEvent evt) {
num1 = Integer.parseInt(TextBox1.getText());
num2 = Integer.parseInt(TexBox2.getText());
MyClass.Method();
}
This will be more Convenient. 这样会更方便。
Here 这里
GUI.TextBox3.setText(com);
TextBox3
also needs to be static. TextBox3
也需要是静态的。
NOTE: You even don't need the class for calculation directly calculate 注意:您甚至不需要用于计算的类直接计算
TextBox3.setText(""+(num1*num2));
Here is a more appropriate answer 这是一个更合适的答案
public class MyMath {
public static int com;
public int squareIt(int a, int b) {
com = a * b;
return com; // return a*b;
}
}
This would make your life a whole lot easier and you could modify your front-end(GUI) like so: 这将使您的生活变得更加轻松,您可以像这样修改前端(GUI):
public class GUI extends javax.swing.JFrame {
public static int num1;
public static int num2;
public GUI() {
initComponents();
}
private void Button1ActionPerformed(java.awt.event.ActionEvent evt) {
num1 = Integer.parseInt(TextBox1.getText());
num2 = Integer.parseInt(TexBox2.getText());
TextBox3.setText(""+new MyMath().squareIt(num1,num2));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.