简体   繁体   English

如何在Java中将字符串值从一个类调用到另一个类

[英]How to call String value from one class to another in Java

so in one class I have this string: String LB = lcfield.getText(); 所以在一个类中我有以下字符串: String LB = lcfield.getText(); to store whatever is written inside the JTextField . 存储JTextField内编写的任何内容。 In another class I have a SQL statement where I need to use the same value as whatever is inside the LB string. 在另一个类中,我有一个SQL语句,在这里我需要使用与LB字符串内部相同的值。

How to call this string? 如何调用这个字符串?

Inside the class that owns the JTextField : 在拥有JTextField的类中:

public String getLcfieldText() {
   return lcfield.getText();
}

And next to the SQL-statement, you can simply do: 在SQL语句旁边,您可以简单地执行以下操作:

String lcFieldText = fooView.getLcfieldText();

You have a couple of options. 您有两种选择。

One option is to make the String LB variable a static public variable of your first class, or private with a getter method to retrieve it. 一种选择是使String LB变量成为您的第一类的静态公共变量,或者使用getter方法将其私有化以检索它。

The second option depends on how the first class creates an instance of your second. 第二个选项取决于第一个类如何创建第二个实例的实例。 You could make a constructor that accepts a string value, which you would pass in when creating the object to call the sql. 您可以使构造函数接受一个字符串值,该字符串值将在创建对象以调用sql时传入。

I guess it depends on how you have you program setup. 我想这取决于您如何进行程序设置。 I have something like this in a swing program I wrote. 我编写的swing程序中有类似的内容。 I store the sql string in a public static String variable of my gui java class. 我将sql字符串存储在gui java类的公共静态String变量中。 Then when I need to execute the sql, I create an instance of the second class, then call it's sql method that takes a String parameter as input, which is where I pass my String value in to execute. 然后,当我需要执行sql时,创建第二个类的实例,然后调用它的sql方法,该方法将String参数作为输入,这是我将String值传递到其中的执行方法。

For example. 例如。 Class one has public static String mySql; 第一类具有公共静态字符串mySql; Class two has a method named executeSql(String sql); 第二个类具有一个名为executeSql(String sql);的方法。

After I create some sql in a string in Class one, I create an instance of Class two and call classTwo.executeSql(mySql); 在第一类的字符串中创建一些sql之后,创建第二类的实例并调用classTwo.executeSql(mySql);。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM