Snažím sa odovzdať hodnotu JTEXTFIELD, ktorú som vytvoril v triede 2, do triedy 3. Môj terminál pri kompilácii mi ukazuje toto:
error: incompatible types
username = class2.username;
Štruktúra môjho kódu je táto.
class 1
- has main
-class2 c2 = new class2
class 2 (extends JFrame)
- JTextField username = new JTextField("", 15);
-method gui here
-method actionlistener here
if e.getsource == submit
class3 c3 = new class3
c3.connection();
class 3
-method connection
-string username declared here
- username = class2.username
Ako môžem získať hodnotu z triedy 2 do triedy 3?
odpovede:
1 pre odpoveď č. 1Túto chybu ste dostali, pretože ste priraďovali JTextField
na a String
čo by malo za následok incompatible types
chyba.
Aby bolo možné získať hodnotu JTextField
musíte použiť getText()
metóda takto:
username = class2.username.getText();
getText()
vráti a String
ktoré potom môžete priradiť každému String
sa vám páči.
Tu je dokumentácia pre getText()
: http://docs.oracle.com/javase/7/docs/api/javax/swing/text/JTextComponent.html#getText()