Access textfield value from other class
Hi guys,
I got a little newbie-problem to solve.
To say it simple I have the following code (2 classes):
@interface class1 : UIViewController {
IBOutlet UITextField *textField;
@property(nonatomic, retain) UITextField *textField;
@implementation
@synthesize textField;
@implementation class2
class1 *class = [[class1 alloc] init];
[[class textField] setText:@"text"];
My problem is, that the text will not show up in the textfield.
If I set the text in class1 everything works fine, but not when I try to set it from class2. The connections between the classes work well, because by using code completion it finds the textfield. I am not used to use property and synthesize, maybe thats the problem?
Thanks for help,
Krissi
I'm more familiar with Mac programming and have just started playing with the iPhone SDK so I'm still trying to get my head around how iPhone apps are structured. It's a little hard to give you a definite answer without knowing more about your "class2" and how your xib file(s) are set up and perhaps which template you used to create your iPhone app.
Assuming your xib file is named "class1.xib", it looks like the code you posted should load the xib. To check: set a breakpoint at that line, run in the debugger, once you stop at that line click the "Step over" button and see if the pointer value for your class1 variable gets updated.
When you run your app are you even seeing the view with the text field on the screen? It may be that you've loaded the xib but you need to add it to your window. Here's a code snippet from the "MoveMeAppDelegate.m" file in Apple's "MoveMe" sample code for iPhone. This is from the "applicationDidFinishLaunching" method where the delegate object is loading a xib file and adding it to the window:
UIViewController *aViewController = [[UIViewController alloc] initWithNibName:@"MoveMeView"
bundle:[NSBundle mainBundle]];
self.viewController = aViewController;
[aViewController release];
// Add the view controller's view as a subview of the window
UIView *controllersView = [viewController view];
[window addSubview:controllersView];
[window makeKeyAndVisible];
Hope this helps,
Steve
Similar Messages
-
Accessing public variables from other classes
Probably a simple questions, but how can I access a variable from another class. My exact situation is as follows.
A class called WorldCalender has a variable which is defined: public int hour; (the value is given to it elsewhere).
I want to access this variable and increase it by one in a subroutine in the class Hour. In this class I have put: WorldCalender.hour++; but it doesn't seem to work. How should I do it?don't expose the hour variable at all.
have a method eg addToHourBy( int hrs )
Probably a simple questions, but how can I access a
variable from another class. My exact situation is as
follows.
A class called WorldCalender has a variable which is
defined: public int hour; (the value is given to it
elsewhere).
I want to access this variable and increase it by one
in a subroutine in the class Hour. In this class I
have put: WorldCalender.hour++; but it doesn't seem to
work. How should I do it? -
How to access form objects from different class?
Hello, I am new to java and i started with netbeans 6 beta,
when i create java form application from template i get 2 classes one ends with APP and one with VIEW,
i put for example jTextField1 with the form designer to the form and i can manipulate it's contents easily from within it's class (let's say it is MyAppView).
Question>
How can i access jTextField1 value from different class that i created in the same project?
please help. and sorry for such newbie question.
Thanks Mikehmm now it says
non static variable jTree1 can not be referenced from static context
My code in ClasWithFormObjects is
public static void setTreeModel (DefaultMutableTreeNode treemodel){
jTree1.setModel(new DefaultTreeModel(treemodel));
and in Class2 it is
ClasWithFormObjects.setTreeModel(model); -
How to access variables from other class
public boolean inIn(Person p)
if (name == p.name && natInsceNo == p.natInsceNo && dateOfBirth == p.dateOfBirth)
return true;
else
return false;
}//returns true if Person with same name/natInsceNo/dateOfBirth as phello,
here am trying to compare the existing object with another object.
could you please tell me how to access the variables of other class because i meet this error?
name cannot be resolved!
thank you!public class Person
protected String name;
protected char gender; //protected attributes are visible in the subclass
protected int dateOfBirth;
protected String address;
protected String natInsceNo;
protected String phoneNo;
protected static int counter;//class variable
//Constractor Starts, (returns a new object, may set an object's initial state)
public Person(String nme,String addr, char sex, int howOld, String ins,String phone)
dateOfBirth = howOld;
gender = sex;
name = nme;
address = addr;
natInsceNo = ins;
phoneNo = phone;
counter++;
public class Store
//Declaration of variables
private Person[] list;
private int count;
private int maxSize;
//constructor starts
public Store(int max)
list = new Person[max];//size array with parameters
maxSize = max;
count = 0;
}//end of store
//constructor ends
//accessor starts
public boolean inIn(Person p)
return (name == p.name && address == p.address && natInsceNo == p.natInsceNo);
}//returns true if Person with same name/natInsceNo/dateOfBirth as phope it helps now! -
Access oracle database from different classes in desktop / standalone app.
I am a bit confused as to what way to go. I am building a desktop application that needs to access an oracle database. I have done this in the past using code similar to the following:
try { DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); Connection conn = DriverManager.getConnection( "jdbc:oracle:thin:@111.111.111.111:oracledb", "username", "password" ); // Create a Statement Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery( "select ... from ..."); while (rs.next()) { ReportNumberCombo.addItem(rs.getString(1)); } // end of rs while conn.close(); } // end of try catch( Exception e ) { e.printStackTrace(); }
The problem I would like to resolve is that I have this code all over the place in my application. I would like to have it in one objects method that i can call from other classes. I can't easily see how to do this, or maybe at this point I'm just too confused.
I want to be able to change this connection info from a properties file which I have already done, not sure if this bit of information would change the answer to my question. I was also looking at the DataSource api, this looks like it is close to what I should use, what are your thoughts?
I would also like to if JNDI is only for web applications or would be appropriate for a desktop app.
Thank you for your help, I realize this is all over the place but I really need these topics cleared up!I have tried exactly that and am getting an error which let me to believe it couldn't be done that way. Here is my code and error message:
public class readPropsFile {
String getURL() throws IOException {
// default values for properties file
String Family = "Family:jdbc" + ":oracle:" + "thin:@";
String Server = "Server:111.111.111.111";
String Port = "Port:1521";
String Host = "Host:oradb";
String Username = "Username:username";
String Password = "Password:password";
try {
new BufferedReader(new FileReader("C:\\data\\Properties.txt"));
} catch (FileNotFoundException filenotfound) {
System.out.println("Error: " + filenotfound.getMessage());
// displays to console if file DOES NOT exist
System.out.println("The file DOES NOT exist, now creating...");
FileWriter fileObject = null;
fileObject = new FileWriter("c:\\data\\Properties.txt");
BufferedWriter out = new BufferedWriter(fileObject);
// writes to output as simple text.
out.write(Family);
out.newLine();
out.write(Server);
out.newLine();
out.write(Port);
out.newLine();
out.write(Host);
out.newLine();
out.write(Username);
out.newLine();
out.write(Password);
out.newLine();
out.close();
// displays to console if file exists
System.out.println("The file exists, or was created sucessfully");
// creates the properties object, assigns text file.
Properties props = new Properties();
FileInputStream in = new FileInputStream("c:\\data\\Properties.txt");
props.load(in);
Family = props.getProperty("Family");
Server = props.getProperty("Server");
Port = props.getProperty("Port");
Host = props.getProperty("Host");
Username = props.getProperty("Username");
Password = props.getProperty("Password");
// prints properties to a file for troubleshooting
PrintStream s = new PrintStream("c:\\data\\list.txt");
props.list(s);
in.close();
String URL = "\"" + Family + Server + ":" + Port + ":" + Host + "\"" +
"," + "\"" + Username + "\"" + "," + "\"" + Password + "\"";
System.out.println("This is the URL:" + URL);
return URL;
}And here is where I try to call the method:
public class connWithProps1 {
public static void main(String[] args) {
readPropsFile callProps = new readPropsFile();
try {
callProps.getURL();
String url = callProps.getURL(); // not needed
System.out.println("The URL (in connWithProps1) is: " + csoProps.getURL());
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection conn = DriverManager.getConnection(url);
// Create a Statement
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select .... WHERE ....'");
while (rs.next()) {
System.out.println(rs.getString(1));
} // end of rs while
conn.close();
} catch (SQLException sqle) {
Logger.getLogger(connWithProps1.class.getName()).log(Level.SEVERE, null, sqle);
} catch (IOException ioe) {
Logger.getLogger(connWithProps1.class.getName()).log(Level.SEVERE, null, ioe);
}The error I get is:
SEVERE: null
java.sql.SQLException: Listener refused the connection with the following error:
ORA-12505, TNS:listener does not currently know of SID given in connect descriptor
The Connection descriptor used by the client was:
111.111.111.111:1521:oradb","username","password"
at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:173)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:460)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:411)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:490)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:202)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:33)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:474)
{code}
Although the URL prints out correctly and when I tried plugging in the URL manually, it works just fine. One other thing I noticed was the line "The file exists, or was created sucessfully" is output 3 times.
I will go back and change my code to properly close the resultset, thanks for catching that. Id rather use what I have instead of JNDI unless it's nesessary.
Edited by: shadow_coder on Jun 19, 2009 2:16 PM -
Handeling EventListeners given from other classes...
Hello again,
I got the folloing Problem:
I've got a Frame-Class, with calls a Class from jPanel, this Panel has a button.
My Problem is this, Is there a way, to handle the button-event from the Parent-Frame?
Means this:
MyPanel mp = new MyPanel();
this.add(mp);
// Here to wait for the button event, and do something.
If anybody has a solution, thx alot.don't expose the hour variable at all.
have a method eg addToHourBy( int hrs )
Probably a simple questions, but how can I access a
variable from another class. My exact situation is as
follows.
A class called WorldCalender has a variable which is
defined: public int hour; (the value is given to it
elsewhere).
I want to access this variable and increase it by one
in a subroutine in the class Hour. In this class I
have put: WorldCalender.hour++; but it doesn't seem to
work. How should I do it? -
Accessing a JTextField from another class
I 've got 2 classes I am trying to get the value of a JTextField that located in a second class see the code
class1 myClass = new class1();
String text = myClass.jTextField1.getText();
System.out.print(text);What happens is when i run the program and enter some text in the jTextFild1 and then click on my Jbutton it does not print anything
the JButton is in the caller class
Could anyone explains to me what is wrongan example would help maybe....
if you want to access your jtextfield from another class then:
import javax.swing.*;
public class FieldHolderClass {
public JTextField jtf = null;
public FieldHolder() {
JFrame jf = new JFrame();
jtf = new JTextField();
jtf.setText("this is the text that is here when other callerclass seeks for text");
jf.getContentPane().add(jtf);
jf.setVisible(true);
public class CallerClass {
public static void main(String args[]) {
FieldHolderClass fHolder = new FieldHolderClass();
System.out.println((fHolder.jtf.getText());
}of course i have not written any swing app for a long time, so i might have forgotten everything... so, don't flame me when that code does not compile.
the thing that it's supposed to show, is that you make a <b>public</b> variabel (jtf) and you simply ask for it from another class by typing holderclass instances name dot and that variable name (in this case jtf) and dot and then call the method on that variable (or object...)
it might also be that you want your code to work the way that when you enter a text into jtextfield, then after pressing enter it would get printed on terminal...
in that case you should also register some Listeners... i remember that back when i was just getin' to know java then i had problems with it as well... but then again, i didn't read any manuals...
i hope i was somewhat help... -
How to get textfield values from a tableRowGroup
I have textfield in a table.
my problem is
How to get textfield values from a tablerowgroup1.I have created getQuantity and setQuantity properties in my session bean and mapped text property of tabletextbox to session bean quantity.
also used map to set and reatrieve quantity values.
I am getting error for bean type quantity. -
Obtaining values from other programs
I seen where you can use Spy ++ to get values from other running programs, how do you do it? I found the values un Spy ++ from the window, so where from I go from here?
Regards, Carter HumphreysHere's some more.
Option Strict On
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
Imports System.Text
Public Class Form1
<DllImport("User32.dll")> _
Private Shared Function FindWindow(ByVal lpClassName As String, ByVal lpWindowName As String) As Integer
End Function
Private Declare Auto Function IsIconic Lib "user32.dll" (ByVal hwnd As IntPtr) As Boolean
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ListView1.AllowColumnReorder = True
ListView1.GridLines = True
ListView1.View = View.Details
ListView1.Sorting = SortOrder.Ascending
ListView1.Columns.Add("Main Window Title", 150, HorizontalAlignment.Left)
ListView1.Columns.Add("Child Class Name", 300, HorizontalAlignment.Left)
ListView1.Columns.Add("Child hWnd", 100, HorizontalAlignment.Left)
ListView1.Columns.Add("Child Main Window Title", 300, HorizontalAlignment.Left)
ListView1.Columns.Add("Is Application Minimized", 300, HorizontalAlignment.Left)
Timer1.Interval = 5000
End Sub
Private Sub ListView1_Click(sender As Object, e As EventArgs) Handles ListView1.Click
TextBox1.Text = ""
TextBox1.Text = "Main Window Title = " & ListView1.FocusedItem.SubItems.Item(0).Text.ToString & vbCrLf & _
"Child Class Name = " & ListView1.FocusedItem.SubItems.Item(1).Text.ToString & vbCrLf & _
"Child hWnd = " & ListView1.FocusedItem.SubItems.Item(2).Text.ToString & vbCrLf & _
"Child Main Window Title = " & ListView1.FocusedItem.SubItems.Item(3).Text.ToString & vbCrLf & _
"Is Application Minimized = " & ListView1.FocusedItem.SubItems.Item(4).Text.ToString
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListView1.Items.Clear()
Dim enumerator As New WindowsEnumerator()
For Each top As ApiWindow In enumerator.GetTopLevelWindows()
For Each child As ApiWindow In enumerator.GetChildWindows(top.hWnd)
Dim item1 As New ListViewItem(top.MainWindowTitle)
item1.SubItems.Add(child.ClassName)
item1.SubItems.Add(child.hWnd.ToString)
item1.SubItems.Add(child.MainWindowTitle)
If top.MainWindowTitle.Length > 0 Then
Dim ICONIC As IntPtr = CType(CInt(FindWindow(Nothing, top.MainWindowTitle).ToString), IntPtr)
item1.SubItems.Add(IsIconic(ICONIC).ToString)
End If
ListView1.Items.AddRange(New ListViewItem() {item1})
Next child
Next top
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Timer1.Start()
Using OFD As New OpenFileDialog
If OFD.ShowDialog = DialogResult.OK Then
End If
End Using
End Sub
Dim InfoToWrite As New List(Of String)
Dim CountIt As Integer = 1
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
InfoToWrite.Clear()
Timer1.Stop()
ListView1.Items.Clear()
Dim enumerator As New WindowsEnumerator()
For Each top As ApiWindow In enumerator.GetTopLevelWindows()
For Each child As ApiWindow In enumerator.GetChildWindows(top.hWnd)
InfoToWrite.Add(top.MainWindowTitle & " - " & child.ClassName & " - " & child.hWnd.ToString & " - " & child.MainWindowTitle)
Dim item1 As New ListViewItem(top.MainWindowTitle)
item1.SubItems.Add(child.ClassName)
item1.SubItems.Add(child.hWnd.ToString)
item1.SubItems.Add(child.MainWindowTitle)
If top.MainWindowTitle.Length > 0 Then
Dim ICONIC As IntPtr = CType(CInt(FindWindow(Nothing, top.MainWindowTitle).ToString), IntPtr)
item1.SubItems.Add(IsIconic(ICONIC).ToString)
End If
ListView1.Items.AddRange(New ListViewItem() {item1})
Next child
Next top
IO.File.WriteAllLines("C:\Users\John\Desktop\Some Info " & CountIt.ToString & ".Txt", InfoToWrite.ToArray)
CountIt += 1
End Sub
End Class
Public Class ApiWindow
Public MainWindowTitle As String = ""
Public ClassName As String = ""
Public hWnd As Int32
End Class
''' <summary>
''' Enumerate top-level and child windows
''' </summary>
''' <example>
''' Dim enumerator As New WindowsEnumerator()
''' For Each top As ApiWindow in enumerator.GetTopLevelWindows()
''' Console.WriteLine(top.MainWindowTitle)
''' For Each child As ApiWindow child in enumerator.GetChildWindows(top.hWnd)
''' Console.WriteLine(" " + child.MainWindowTitle)
''' Next child
''' Next top
''' </example>
Public Class WindowsEnumerator
Private Delegate Function EnumCallBackDelegate(ByVal hwnd As Integer, ByVal lParam As Integer) As Integer
' Top-level windows.
Private Declare Function EnumWindows Lib "user32" _
(ByVal lpEnumFunc As EnumCallBackDelegate, ByVal lParam As Integer) As Integer
' Child windows.
Private Declare Function EnumChildWindows Lib "user32" _
(ByVal hWndParent As Integer, ByVal lpEnumFunc As EnumCallBackDelegate, ByVal lParam As Integer) As Integer
' Get the window class.
Private Declare Function GetClassName _
Lib "user32" Alias "GetClassNameA" _
(ByVal hwnd As Integer, ByVal lpClassName As StringBuilder, ByVal nMaxCount As Integer) As Integer
' Test if the window is visible--only get visible ones.
Private Declare Function IsWindowVisible Lib "user32" _
(ByVal hwnd As Integer) As Integer
' Test if the window's parent--only get the one's without parents.
Private Declare Function GetParent Lib "user32" _
(ByVal hwnd As Integer) As Integer
' Get window text length signature.
Private Declare Function SendMessage _
Lib "user32" Alias "SendMessageA" _
(ByVal hwnd As Int32, ByVal wMsg As Int32, ByVal wParam As Int32, ByVal lParam As Int32) As Int32
' Get window text signature.
Private Declare Function SendMessage _
Lib "user32" Alias "SendMessageA" _
(ByVal hwnd As Int32, ByVal wMsg As Int32, ByVal wParam As Int32, ByVal lParam As StringBuilder) As Int32
Private _listChildren As New List(Of ApiWindow)
Private _listTopLevel As New List(Of ApiWindow)
Private _topLevelClass As String = ""
Private _childClass As String = ""
''' <summary>
''' Get all top-level window information
''' </summary>
''' <returns>List of window information objects</returns>
Public Overloads Function GetTopLevelWindows() As List(Of ApiWindow)
EnumWindows(AddressOf EnumWindowProc, &H0)
Return _listTopLevel
End Function
Public Overloads Function GetTopLevelWindows(ByVal className As String) As List(Of ApiWindow)
_topLevelClass = className
Return Me.GetTopLevelWindows()
End Function
''' <summary>
''' Get all child windows for the specific windows handle (hwnd).
''' </summary>
''' <returns>List of child windows for parent window</returns>
Public Overloads Function GetChildWindows(ByVal hwnd As Int32) As List(Of ApiWindow)
' Clear the window list.
_listChildren = New List(Of ApiWindow)
' Start the enumeration process.
EnumChildWindows(hwnd, AddressOf EnumChildWindowProc, &H0)
' Return the children list when the process is completed.
Return _listChildren
End Function
Public Overloads Function GetChildWindows(ByVal hwnd As Int32, ByVal childClass As String) As List(Of ApiWindow)
' Set the search
_childClass = childClass
Return Me.GetChildWindows(hwnd)
End Function
''' <summary>
''' Callback function that does the work of enumerating top-level windows.
''' </summary>
''' <param name="hwnd">Discovered Window handle</param>
''' <returns>1=keep going, 0=stop</returns>
Private Function EnumWindowProc(ByVal hwnd As Int32, ByVal lParam As Int32) As Int32
' Eliminate windows that are not top-level.
If GetParent(hwnd) = 0 AndAlso CBool(IsWindowVisible(hwnd)) Then
' Get the window title / class name.
Dim window As ApiWindow = GetWindowIdentification(hwnd)
' Match the class name if searching for a specific window class.
If _topLevelClass.Length = 0 OrElse window.ClassName.ToLower() = _topLevelClass.ToLower() Then
_listTopLevel.Add(window)
End If
End If
' To continue enumeration, return True (1), and to stop enumeration
' return False (0).
' When 1 is returned, enumeration continues until there are no
' more windows left.
Return 1
End Function
''' <summary>
''' Callback function that does the work of enumerating child windows.
''' </summary>
''' <param name="hwnd">Discovered Window handle</param>
''' <returns>1=keep going, 0=stop</returns>
Private Function EnumChildWindowProc(ByVal hwnd As Int32, ByVal lParam As Int32) As Int32
Dim window As ApiWindow = GetWindowIdentification(hwnd)
' Attempt to match the child class, if one was specified, otherwise
' enumerate all the child windows.
If _childClass.Length = 0 OrElse window.ClassName.ToLower() = _childClass.ToLower() Then
_listChildren.Add(window)
End If
Return 1
End Function
''' <summary>
''' Build the ApiWindow object to hold information about the Window object.
''' </summary>
Private Function GetWindowIdentification(ByVal hwnd As Integer) As ApiWindow
Const WM_GETTEXT As Int32 = &HD
Const WM_GETTEXTLENGTH As Int32 = &HE
Dim window As New ApiWindow()
Dim title As New StringBuilder()
' Get the size of the string required to hold the window title.
Dim size As Int32 = SendMessage(hwnd, WM_GETTEXTLENGTH, 0, 0)
' If the return is 0, there is no title.
If size > 0 Then
title = New StringBuilder(size + 1)
SendMessage(hwnd, WM_GETTEXT, title.Capacity, title)
End If
' Get the class name for the window.
Dim classBuilder As New StringBuilder(64)
GetClassName(hwnd, classBuilder, 64)
' Set the properties for the ApiWindow object.
window.ClassName = classBuilder.ToString()
window.MainWindowTitle = title.ToString()
window.hWnd = hwnd
Return window
End Function
End Class
La vida loca -
Accessing the ServletContext from a class that is not a Servlet?
Is there any way of accessing the ServletContext from a class that is not a
Servlet? The class is being used as part of a Web Application.
Thanks.
http://www.mozilla.org/mirrors.html
Mozilla has download mirrors around the globe. If it is on the list, it is trustworthy. -
Accesing from other classes to protected void
Hy! I'm a newbie to java programming. So i am making a program in J2ME, and the problem is :
I have an abstract class, wich i must extend. That class defines a procedure
abstract protected void destroyApp(boolean unconditional), so in my extended class this void is protected. But i want to access to this procedure from other class, and do it somehow static.
I have made a main program class (the extended class), and i want to send from other class a destroy message to it (to call destroyApp procedure).
Kazhha.Your question has nothing to do with Native Methods.
In the future, for novice questions, use the New To Java Technology forum.
I have an abstract class, which i must extend. That
class defines a procedure
abstract protected void destroyApp(boolean
unconditional), so in my extended class this void is
protected.You can make the method public in your class.
But i want to access to this procedure
from other class, and do it somehow static.IIRC you cannot make a method static if it is not static in the class you extend.
I have made a main program class (the extended class),
and i want to send from other class a destroy message
to it (to call destroyApp procedure).Huh? -
Making object accesible from other class?
hi all
how can i have an object of class to be accesible from other class?
thanksIt's not clear what you mean by "object of class". Do you mean fields within an object. Do you mean using an object of one class within the code of another?
For most named objectes in java, whether field, method or class, there are four levels of access.
public means accessible from anywhere in the program
private means accessible only from the same source file.
protected means only from the class, or a class that extends it.
or if you don't put any of these keywords it means accessible only from the same package, that is set of source files in a single directory. -
Method not accessible from other classes
Hi,
I ve defined a class and would like to create an instance of it from another class. That works fine, I am also able to access class variables. However the class method "calcul" which is defined as following, is not accessible from other classes:
class Server {
static String name;
public static void calcul (String inputS) {
int length = inputS.length();
for (int i = 0 ; i < length; i++) {
System.out.println(newServer.name.charAt(i)); }
If I create an instant of the class in the same class, the method is then available for the object.
I am using JBuilder, so I can see, which methods and variables are available for an object. Thanks for your helpcalcul is a static method, that means you do not need an instance of server to run this method. This method is also public, but your class Server is not, your Server class is package protected. So only classes within the same package has Server can use its method. How to use the calcul method?// somewhere in the same package as the Server class
Server.calcul( "toto" ); -
Calling a object of class from other class's function with in a package
Hello Sir,
I have a package.package have two classes.I want to use object of one class in function of another class of this same package.
Like that:
one.java
package co;
public class one
private String aa="Vijay"; //something like
}main.java:
package co;
import java.util.Stack;
public class main extends Stack
public void show(one obj)
push(obj);
public static void main(String args[])
main oo=new main();
}when I compile main class, Its not compile.
Its give error.can not resolve symbol:
symbol: class one
location: class co.main
public void show(one obj)
^Please help How that compile "Calling a object of class from other class's function with in a package" beacuse I want to use this funda in an applicationkumar.vijaydahiya wrote:
.It is set in environment variable.path=C:\bea\jdk141_02\bin;.,C:\oraclexe\app\oracle\product\10.2.0\server\bin;. command is:
c:\Core\co\javac one.javaIts compiled already.
c:\Core\co\javac main.javaBut it give error.
Both java classes in co package.Okay, open a command prompt and execute these two commands:
// to compile both classes:
javac -cp c:\Core c:\Core\co\*.java
// to run your main-class:
java -cp c:\Core co.main -
How add buttons to Jframe from other class
Hi, a have a little problem;)
I want make a JFrame, but i want to add JButtons from other class. Now I have something like that:
My JFrame class:
package windoow;
import javax.swing.*;
import java.awt.*;
public class MyWindow extends JFrame {
Butt buttons ;
public Window(String s) {
super(s);
this.setSize(600, 600);
this.setVisible(true);
Buttons();
public void Buttons(){
setLayout(null);
buttons = new Butt();
buttons.mywindow =this;
} My class with buttons:
package windoow;
import javax.swing.JButton;
public class Butt {
MyWindow mywindow;
JButton b1;
Butt(){
b1 = new JButton("Button");
b1.setBounds(100,100,100,20);
mywindow.add(b1);
} and i have NullPointerException.
When i try to make new MyWindow in Butt clas i have something like StackOverFlow.
what should i do?Your null pointer exception is occuring because, in your Butt() constructor, you are calling mywindow.add(b1), but you don't set mywindow until after you call the constructor in the MyWindow::Buttons() method.
And, if you try to create a new MyWindow() in your Butt() constructor, and, assuming that you are calling the MyWindow::Window(String s) method from the MyWindow() constructor (which is not clear from the code fragment you posted), then Butt() calls new MyWindow() which calls Window(String s) which calls Butt() which calls ... and so on, until the stack overflows.
One possible solution ... pass your MyWindow reference into your Butt() constructor as this, as so:
public void Buttons()
// stuff deleted
buttons = new Butt( this );
// stuff deleted
// AND
Butt( MyWindow mw )
// stuff deleted
mywindow = mw;
mywindow.add( b1 ); // b1 created in stuff deleted section
}Also, I would call setVisible(true) as the last thing I did during the construction of the frame. This realizes the frame, and from that point forward, most changes to the frame should be made on the event thread.
¦ {Þ
Maybe you are looking for
-
Creation of Add-on package for 64 bit and 32 bit SAP Business One Client
Please help me creating package for 64 bit and 32 bit SAP Business One. If Add-on executable is compiled with x86 option then there is no issue of connecting Add-on with 32 bit SAP Business one and if Add-on executable is compiled with Any CPU option
-
Error while assignment of Paying Co Code in FBZP
HI friends, I am getting the following error while assigning Paying Co Code in FBZP - Company code 7144 is not permitted as the paying company code Message no. F3063 Diagnosis The paying company code and the company code on whose behalf the payment i
-
ORA-12545 .... host or object does not exi
Hi there. Im tiered from that Trying install 8.1.7 on Red Hat 7.0. Not working. (I read all from what I cud from this group, but still dont know what to do ) I installed glibc 2.1.3. After that I was able to create a database. I can open it, connect
-
Spry widget menu bar background image help
Does anyone know of a good tutorial for putting a background image behind the whole menu bar, not just each button, and a tutorial for putting images behind each button. Also, does anyone have a good tutorial on creating some sort of gallery, with th
-
Condition YPS1 not copied into Billing document
Hi All, I have an urgent issue wherein my condition YpS1 determined in the sales order is not copied into the billing document Any suggestions would be appreciated... The YPS1 is pulled out from the standard price from the material master Any suggest