Variable sharing from one class to another??
Hi!!
Suppose two classes, one class extend from JFrame and another
from JDialog.I want to share the variable of Second one(extending JDialog) into firstone.How can I get this? please help me.
For example:
In JFrame class...
JDialog theDialog = new JDialog ...
someVariable = theDialog.getVariable();
In the JDialog class, add the getVariable method.
Similar Messages
-
Using Variables/Arrays from one class in another
Hello all,
First, to explain what I am attempting to create, is a program that will accept input of employee names and hours worked into an array. The first class will accept a command line argument when invoked. If the argument is correct, it will call another class that will gather information from the user via an input box. After all names and hours have been input for employees, this class will calculate the salary based upon the first letter of each employee name and print the total hours, salary, etc. for each employee.
What I need to do now is to split the second class into two: one that will gather the data and another that will calculate and print the data. Yes, this is an assignment. However, I am trying to learn and I have gotten this far, but I am stuck on how to get a class to be able to use an array/variables from another class.
I realize the below code isn't exactly cleaned up...yet.
Code for AverageSalaryGather class:
import javax.swing.JOptionPane; // uses class JOptionPane
import java.lang.reflect.Array;
import java.math.*;
public class AverageSalaryGather {
public static void gatherData() {
char[] alphaArray = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','x','y','z'};
String[][] empInfoArray = new String[100][4];
String[] empNameArray = new String[100];
String finalOutput = "Name - Rate - Hours - Total Pay\n";
String averageHoursOutput = "Average Hours Worked:\n";
String averageSalaryOutput = "Average Hourly Salary:\n";
String averageGroupSalaryOutput = "Average Group Salary:\n";
String[] rateArray = new String[26];
char empNameChar = 'a';
int empRate = 0;
int payRate = 0;
for (int i = 0; i < 26; i++) {
payRate = i + 5;
rateArray[i] = Integer.toString(payRate);
int countJoo = 0;
while (true) {
String namePrompt = "Please enter the employee name: ";
String empName = JOptionPane.showInputDialog(namePrompt);
if (empName == null | empName.equals("")) {
break;
else {
empInfoArray[countJoo][0] = empName;
for (int i = 0; i < alphaArray.length; i++) {
empNameChar = empName.toLowerCase().charAt(0);
if (alphaArray[i] == empNameChar) {
empInfoArray[countJoo][1] = rateArray;
break;
countJoo++;
// DecimalFormat dollarFormat = new DecimalFormat("$#0.00");
for (int i = 0; i < empInfoArray.length; i++) {
if (!(empInfoArray[i][0] == null)) {
String hourPrompt = "Please enter hours for " + empInfoArray[i][0] + ": ";
String empHours = JOptionPane.showInputDialog(hourPrompt);
int test = 0;
empInfoArray[i][2] = empHours;
// convert type String to double
//double tmpPayRate = Double.parseDouble(empInfoArray[i][1]);
//double tmpHours = Double.parseDouble(empInfoArray[i][2]);
//double tmpTotalPay = tmpPayRate * tmpHours;
// create via a string in empInfoArray
BigDecimal bdRate = new BigDecimal(empInfoArray[i][1]);
BigDecimal bdHours = new BigDecimal(empInfoArray[i][2]);
BigDecimal bdTotal = bdRate.multiply(bdHours);
bdTotal = bdTotal.setScale(2, RoundingMode.HALF_UP);
String strTotal = bdTotal.toString();
empInfoArray[i][3] = strTotal;
//String strTotalPay = Double.toString(tmpTotalPay);
//empInfoArray[i][3] = dollarFormat.format(tmpTotalPay);
else {
break;
AverageSalaryCalcAndPrint averageSalaryCalcAndPrint = new AverageSalaryCalcAndPrint();
averageSalaryCalcAndprint.calcAndPrint();
Code for AverageSalaryCalcAndPrint class (upon compiling, there are more than a few complie errors, and that is due to me cutting/pasting the code from the other class into the new class and the compiler does not know how to access the array/variables from the gatherData class):
import javax.swing.JOptionPane; // uses class JOptionPane
import java.lang.reflect.Array;
import java.math.*;
public class AverageSalaryCalcAndPrint
public static void calcAndPrint() {
AverageSalaryGather averageSalaryGather = new AverageSalaryGather();
double totalHours = 0;
double averageHours = 0;
double averageSalary = 0;
double totalSalary = 0;
double averageGroupSalary = 0;
double totalGroupSalary = 0;
int countOfArray = 0;
for (int i = 0; i < empInfoArray.length; i++) {
if (!(empInfoArray[0] == null)) {
totalSalary = totalSalary + Double.parseDouble(empInfoArray[i][1]);
totalHours = totalHours + Double.parseDouble(empInfoArray[i][2]);
totalGroupSalary = totalGroupSalary + Double.parseDouble(empInfoArray[i][3]);
countOfArray = i;
averageHours = totalHours / (countOfArray + 1);
averageSalary = totalSalary / (countOfArray + 1);
averageGroupSalary = totalGroupSalary / (countOfArray + 1);
String strAverageHourlySalary = Double.toString(averageSalary);
String strAverageHours = Double.toString(averageHours);
String strAverageGroupSalary = Double.toString(averageGroupSalary);
for (int i = 0; i < empInfoArray.length; i++) {
if (!(empInfoArray[i][0] == null)) {
finalOutput = finalOutput + empInfoArray[i][0] + " - " + "$" + empInfoArray[i][1] + "/hr" + " - " + empInfoArray[i][2] + " - " + "$" + empInfoArray[i][3] + "\n";
averageHoursOutput = averageHoursOutput + strAverageHours + "\n";
averageSalaryOutput = averageSalaryOutput + strAverageHourlySalary + "\n";
averageGroupSalaryOutput = averageGroupSalaryOutput + strAverageGroupSalary + "\n";
JOptionPane.showMessageDialog(null, finalOutput + averageHoursOutput + averageSalaryOutput + averageGroupSalaryOutput, "Totals", JOptionPane.PLAIN_MESSAGE );Call the other class's methods. (In general, you
shouldn't even try to access fields from the other
class.) Also you should be looking at an
instance of the other class, and not the class
itself, generally.Would I not call the other classes method's by someting similar as below?:
AverageSalaryCalcAndPrint averageSalaryCalcAndPrint = new AverageSalaryCalcAndPrint();
averageSalaryCalcAndprint.calcAndPrint(); Well... don't break down classes based on broad steps
of the program. Break them down by the information
being managed. I'm not expressing this well...Could you give an example of this? I'm not sure I'm following well.
Anyway, you want one or more objects that represent
the data, and operations on that data. Those
operations include calculations on the data. Other
classes might represent the user interface, and
different output types (say, a file versus the
console).Yes, the requirements is to have a separate class to gather the data, and then another class to calculate and print the data. Is this what you mean in the above? -
How to pass a variable from one class to another class?
Hi,
Is it possible to pass a variable from one class to another? For e.g., I need the value of int a for calculation purpose in method doB() but I get an error <identifier> expected. What does the error mean? I know, it's a very, very simple question but once I learn this, I promise to remember it forever. Thank you.
class A {
int a;
int doA() {
a = a + 1;
return a;
class B {
int b;
A r = new A();
r.a; // error: <identifier> expected. What does that mean ?
int doB() {
int c = b/a; // error: operator / cannot be applied to a
}Thank you!elaine_g wrote:
I am wondering why does (r.a) give an error outside the method? What's the reason it only works when used inside the (b/r.a) maths function? This is illegal syntax:
class B {
int b;
A r = new A();
r.a; //syntax error
}Why? Class definition restricts what you can define within a class to a few things:
class X {
Y y = new Y(); //defining a field -- okay
public X() { //defining a constructor -- okay
void f() { //defining a method -- okay
}... and a few other things, but you can't just write "r.a" there. It also makes no sense -- that expression by itself just accesses a field and does nothing with it -- why bother?
This is also illegal syntax:
int doB() {
A r = new A();
r.a; // error: not a statement
}Again, all "r.a" does on its own is access a field and do nothing with it -- a "noop". Since it has no effect, writing this indicates confusion on the part of the coder, so it classified as a syntax error. There is no reason to write that. -
Moving Variable from one class to another.
I need to get a Variable from one class to another how would I do this?
Well this is a very tipical scehario for every enterprise application. You always create logger classes that generate log files for your application, as that is the only way to track errors in your system when its in the production enviorment.
Just create a simple class that acts as the Logger, and have a method in it that accepts a variable of the type that you are are trying to pass; most commonly a String; but can be overloaded to accept constom classes. e.g.
class Logger
public void log(String message)
writeToFile("< " + new Date() + " > " + message);
public void log(CustomClass queueEvent)
log("queue message was: " + queueEvent.getMessage() + " at: " + queueEven.getEventTime());
}Hope this makes things clearer
Regards
Omer -
Passing Variables from One Class to Another
Hello, I am new to Java Programming and I'm currently starting off by trying to build a simple application.
I need help to pass variables created in one class to another.
In my source package, I created 2 java classes.
1. Main.java
2. InputFileDeclared.java
InputFileDeclared reads numerical data from an external text file and store them as string variables within the main method while Main converts a text string into a number.
Hence, I would like to pass these strings variables from the InputFileDeclared class to the Main class so that they can be converted into numbers.
I hope somebody out there may enlighten me on this.
Thank you very much in advance!Values are passed from method to method, rather than from class to class. In a case such as you describe the code of a method in Main will probably call a method in InputFileDeclared which will return the String you want. The method in Main stores that in a local variable and processes it. It really doesn't matter here which class the method is in.
You InputFileDeclared object probably contains "state" information in its fields such as the details of the file it's reading and how far it's got, but generally the calling method in Main won't need to know about this state, just the last data read.
So the sequence in the method in Main will be:
1) Create an new instance of InputFileDeclared, probably passing it the file path etc..
2) Repeatedly call a method on that instance to return data values, until the method signals that it's reached the end of file, e.g. by returning a null String.
3) Probably call a "close()" method on the instance, which you should have written to close the file. -
Passing a parameter from one class to another class in the same package
Hi.
I am trying to pass a parameter from one class to another class with in a package.And i am Getting the variable as null every time.In the code there is two classes.
i. BugWatcherAction.java
ii.BugWatcherRefreshAction.Java.
We have implemented caching in the front-end level.But according to the business logic we need to clear the cache and again have to access the database after some actions are happened.There are another class file called BugwatcherPortletContent.java.
So, we are dealing with three java files.The database interaction is taken care by the portletContent.java file.Below I am giving the code for the perticular function in the bugwatcherPortletContent.java:
==============================================================
public Object loadContent() throws Exception {
Hashtable htStore = new Hashtable();
JetspeedRunData rundata = this.getInputData();
String pId = this.getPorletId();
PortalLogger.logDebug(" in the portlet content: "+pId);
pId1=pId;//done by sraha
htStore.put("PortletId", pId);
htStore.put("BW_HOME_URL",CommonUtil.getMessage("BW.Home.Url"));
htStore.put("BW_BUGVIEW_URL",CommonUtil.getMessage("BW.BugView.Url"));
HttpServletRequest request = rundata.getRequest();
PortalLogger.logDebug(
"BugWatcherPortletContent:: build normal context");
HttpSession session = null;
int bugProfileId = 0;
Hashtable bugProfiles = null;
Hashtable bugData = null;
boolean fetchProfiles = false;
try {
session = request.getSession(true);
// Attempting to get the profiles from the session.
//If the profiles are not present in the session, then they would have to be
// obtained from the database.
bugProfiles = (Hashtable) session.getAttribute("Profiles");
//Getting the selected bug profile id.
String bugProfileIdObj = request.getParameter("bugProfile" + pId);
// Getting the logged in user
String userId = request.getRemoteUser();
if (bugProfiles == null) {
fetchProfiles = true;
if (bugProfileIdObj == null) {
// setting the bugprofile id as -1 indicates "all profiles" is selected
bugProfileIdObj =(String) session.getAttribute("bugProfileId" + pId);
if (bugProfileIdObj == null) {
bugProfileId = -1;
else {
bugProfileId = Integer.parseInt(bugProfileIdObj);
else {
bugProfileId = Integer.parseInt(bugProfileIdObj);
session.setAttribute(
("bugProfileId" + pId),
Integer.toString(bugProfileId));
//fetching the bug list
bugData =BugWatcherAPI.getbugList(userId, bugProfileId, fetchProfiles);
PortalLogger.logDebug("BugWatcherPortletContent:: got bug data");
if (bugData != null) {
Hashtable htProfiles = (Hashtable) bugData.get("Profiles");
} else {
htStore.put("NoProfiles", "Y");
} catch (CodedPortalException e) {
htStore.put("Error", CommonUtil.getErrMessage(e.getMessage()));
PortalLogger.logException
("BugWatcherPortletContent:: CodedPortalException!!",e);
} catch (Exception e) {
PortalLogger.logException(
"BugWatcherPortletContent::Generic Exception!!",e);
htStore.put( "Error",CommonUtil.getErrMessage(ErrorConstantsI.GET_BUGLIST_FAILED));
if (fetchProfiles) {
bugProfiles = (Hashtable) bugData.get("Profiles");
session.setAttribute("Profiles", bugProfiles);
// putting the stuff in the context
htStore.put("Profiles", bugProfiles);
htStore.put("SelectedProfile", new Integer(bugProfileId));
htStore.put("bugs", (ArrayList) bugData.get("Bugs"));
return htStore;
=============================================================
And I am trying to call this function as it can capable of fetching the data from the database by "getbugProfiles".
In the new class bugWatcherRefreshAction.java I have coded a part of code which actually clears the caching.Below I am giving the required part of the code:
=============================================================
public void doPerform(RunData rundata, Context context,String str) throws Exception {
JetspeedRunData data = (JetspeedRunData) rundata;
HttpServletRequest request = null;
//PortletConfig pc = portlet.getPortletConfig();
//String userId = request.getRemoteUser();
/*String userId = ((JetspeedUser)rundata.getUser()).getUserName();//sraha on 1/4/05
String pId = request.getParameter("PortletId");
PortalLogger.logDebug("just after pId " +pId); */
//Calling the variable holding the value of portlet id from BugWatcherAction.java
//We are getting the portlet id here , through a variable from BugWatcherAction.java
/*BugWatcherPortletContent bgAct = new BugWatcherPortletContent();
String portletID = bgAct.pId1;
PortalLogger.logDebug("got the portlet ID in bugwatcherRefreshAction:---sraha"+portletID);*/
// updating the bug groups
Hashtable result = new Hashtable();
try {
request = data.getRequest();
String userId = ((JetspeedUser)data.getUser()).getUserName();//sraha on 1/4/05
//String pId = (String)request.getParameter("portletId");
//String pId = pc.getPorletId();
PortalLogger.logDebug("just after pId " +pId);
PortalLogger.logDebug("after getting the pId-----sraha");
result =BugWatcherAPI.getbugList(profileId, userId);
PortalLogger.logDebug("select the new bug groups:: select is done ");
context.put("SelectedbugGroups", profileId);
//start clearing the cache
ContentCacheContext cacheContext = getCacheContext(rundata);
PortalLogger.logDebug("listBugWatcher Caching - removing markup content - before removecontent");
// remove the markup content from cache.
PortletContentCache.removeContent(cacheContext);
PortalLogger.logDebug("listBugWatcher Caching-removing markup content - after removecontent");
//remove the backend content from cache
CacheablePortletData pdata =(CacheablePortletData) PortletCache.getCacheable(PortletCacheHelper.getUserHandle(((JetspeedUser)data.getUser()).getUserName()));
PortalLogger.logDebug("listBugWatcher Caching User: " +((JetspeedUser)data.getUser()).getUserName());
PortalLogger.logDebug("listBugWatcher Caching pId: " +pId);
if (pdata != null)
// User's data found in cache!
PortalLogger.logDebug("listBugWatcher Caching -inside pdata!=null");
pdata.removeObject(PortletCacheHelper.getUserPortletHandle(((JetspeedUser)data.getUser()).getUserName(),pId));
PortalLogger.logDebug("listBugWatcher Caching -inside pdata!=null- after removeObject");
PortalLogger.logDebug("listBugWatcher Caching -finish calling the remove content code");
//end clearing the cache
// after clearing the caching calling the data from the database taking a fn from the portletContent.java
PortalLogger.logDebug("after clearing cache---sraha");
BugWatcherPortletContent bugwatchportcont = new BugWatcherPortletContent();
Hashtable httable= new Hashtable();
httable=(Hashtable)bugwatchportcont.loadContent();
PortalLogger.logDebug("after making the type casting-----sraha");
Set storeKeySet = httable.keySet();
Iterator itr = storeKeySet.iterator();
while (itr.hasNext()) {
String paramName = (String) itr.next();
context.put(paramName, httable.get(paramName));
PortalLogger.logDebug("after calling the databs data from hashtable---sraha");
} catch (CodedPortalException e) {
PortalLogger.logException("bugwatcherRefreshAction:: Exception- ",e);
context.put("Error", CommonUtil.getErrMessage(e.getMessage()));
catch (Exception e) {
PortalLogger.logException("bugwatcherRefreshAction:: Exception- ",e);
context.put( "Error",CommonUtil.getErrMessage(ErrorConstantsI.EXCEPTION_CODE));
try {
((JetspeedRunData) data).setCustomized(null);
if (((JetspeedRunData) data).getCustomized() == null)
ActionLoader.getInstance().exec(data,"controls.EndCustomize");
catch (Exception e)
PortalLogger.logException("bugwatcherRefreshAction", e);
===============================================================
In the bugwatcher Action there is another function called PostLoadContent.java
here though i have found the portlet Id but unable to fetch that in the bugWatcherRefreshAction.java . I am also giving the code of that function under the bugWatcherAction.Java
================================================
// Get the PortletData object from intermediate store.
CacheablePortletData pdata =(CacheablePortletData) PortletCache.getCacheable(PortletCacheHelper.getUserHandle(
//rundata.getRequest().getRemoteUser()));
((JetspeedUser)rundata.getUser()).getUserName()));
pId1 = (String)portlet.getID();
PortalLogger.logDebug("in the bugwatcher action:"+pId1);
try {
Hashtable htStore = null;
// if PortletData is available in store, get current portlet's data from it.
if (pdata != null) {
htStore =(Hashtable) pdata.getObject( PortletCacheHelper.getUserPortletHandle(
((JetspeedUser)rundata.getUser()).getUserName(),portlet.getID()));
//Loop through the hashtable and put its elements in context
Set storeKeySet = htStore.keySet();
Iterator itr = storeKeySet.iterator();
while (itr.hasNext()) {
String paramName = (String) itr.next();
context.put(paramName, htStore.get(paramName));
bugwatcherRefreshAction bRefAc = new bugwatcherRefreshAction();
bRefAc.doPerform(pdata,context,pId1);
=============================================================
So this is the total scenario for the fetching the data , after clearing the cache and display that in the portal.I am unable to do that.Presently it is still fetching the data from the cache and it is not going to the database.Even the portlet Id is returning as null.
I am unable to implement that thing.
If you have any insight about this thing, that would be great .As it is very urgent a promt response will highly appreciated.Please send me any pointers or any issues for this I am unable to do that.
Please let me know as early as possible.
Thanks and regards,
Santanu Raha.Have you run it in a debugger? That will show you exactly what is happening and why.
-
How to transter contents of itab from one class to another...
Hello experts,
I am currently having problems on how to transfer the contents of an itab or even
the value of a variable from one class to another. For example, I have 10 records
in it_spfli in class 1 and when I loop at it_spfli in the method of class 2 it has no records!
This is an example:
class lcl_one definition.
public section.
data: gt_spfli type table of spfli.
methods get_data.
endclass.
class lcl_one implementation.
method get_data.
select * from spfli
into table gt_spfli.
endmethod.
endclass.
class lcl_two definition inheriting from lcl_one.
public section.
methods loop_at_itab.
endclass.
class lcl_two implementation.
method loop_at_itab.
field-symbols: <fs_spfli> like line of gt_spfli.
loop at gt_spfli assigning <fs_spfli>.
write: / <fs_spfli>-carrid.
endloop.
endmethod.
endclass.
start-of-selection.
data: one type ref to lcl_one,
two type ref to lcl_two.
create object: one, two.
call method one->get_data.
call method two->loop_at_itab.
In the example above, the contents of gt_spfli in class lcl_two is empty
even though it has records in class lcl_one. Help would be appreciated.
Thanks a lot guys and take care!Hi Uwe,
It is still the same. Here is my code:
REPORT zfi_ors_sms
NO STANDARD PAGE HEADING
LINE-SIZE 255
LINE-COUNT 65
MESSAGE-ID zz.
Include program/s *
INCLUDE zun_standard_routine. " Standard Routines
INCLUDE zun_header. " Interface Header Record
INCLUDE zun_footer. " Interface Footer Record
INCLUDE zun_interface_control. " Interface Control
INCLUDE zun_external_routine. " External Routines
INCLUDE zun_globe_header. " Report header
INCLUDE zun_bdc_routine. " BDC Routine
Data dictionary table/s *
TABLES: bkpf,
rf05a,
sxpgcolist.
Selection screen *
SELECTION-SCREEN BEGIN OF BLOCK b1 WITH FRAME TITLE text-001.
PARAMETERS: p_file TYPE sxpgcolist-parameters.
SELECTION-SCREEN END OF BLOCK b1.
*/ CLASS DEFINITIONS
CLASS lcl_main DEFINITION
CLASS lcl_main DEFINITION ABSTRACT.
PUBLIC SECTION.
Structure/s *
TYPES: BEGIN OF t_itab,
rec_content(100) TYPE c,
END OF t_itab.
TYPES: BEGIN OF t_upfile,
record_id(2) TYPE c, " Record ID
rec_date(10) TYPE c, " Record Date MM/DD/YYYY
prod_line(10) TYPE c, " Product Line
acc_code(40) TYPE c, " Acc Code
description(50) TYPE c, " Description
hits(13) TYPE c, " Hits
amount(15) TYPE c, " Amount
END OF t_upfile.
Internal table/s *
DATA: gt_bdcdata TYPE STANDARD TABLE OF bdcdata,
gt_bdcmsgcoll TYPE STANDARD TABLE OF bdcmsgcoll,
gt_itab TYPE STANDARD TABLE OF t_itab,
gt_header LIKE TABLE OF interface_header,
gt_footer LIKE TABLE OF interface_footer,
gt_upfile TYPE STANDARD TABLE OF t_upfile.
Global variable/s *
DATA: gv_target TYPE rfcdisplay-rfchost,
gv_err_flag(1) TYPE n VALUE 0,
gv_input_dir(100) TYPE c
VALUE '/gt/interface/FI/ORS/inbound/',
gv_inputfile_dir(255) TYPE c,
gv_eof_flag TYPE c VALUE 'N',
gv_string TYPE string,
gv_delimiter TYPE x VALUE '09',
gv_input_records(3) TYPE n,
gv_input_file_ctr(6) TYPE n,
gv_proc_tot_amt(14) TYPE p DECIMALS 2,
gv_prg_message TYPE string,
gv_gjahr TYPE bkpf-gjahr,
gv_monat TYPE bsis-monat.
Work area/s *
DATA: wa_itab LIKE LINE OF gt_itab,
wa_upfile LIKE LINE OF gt_upfile,
wa_footer LIKE LINE OF gt_footer,
wa_header LIKE LINE OF gt_header.
ENDCLASS.
CLASS lcl_read_app_server_file DEFINITION
CLASS lcl_read_app_server_file DEFINITION INHERITING FROM lcl_main.
PUBLIC SECTION.
METHODS: read_app_server_file,
read_input_file,
split_header,
process_upload_file,
split_string,
conv_num CHANGING value(amount) TYPE t_upfile-amount,
split_footer,
update_batch_control,
process_data.
ENDCLASS.
CLASS lcl_process_data DEFINITION
CLASS lcl_process_data DEFINITION INHERITING FROM
lcl_read_app_server_file.
PUBLIC SECTION.
METHODS process_data REDEFINITION.
ENDCLASS.
*/ CLASS IMPLEMENTATIONS
CLASS lcl_read_app_server_file IMPLEMENTATION
CLASS lcl_read_app_server_file IMPLEMENTATION.
*/ METHOD read_app_server_file - MAIN METHOD
METHOD read_app_server_file.
gv_target = sy-host.
PERFORM file_copy USING 'ZPPDCP' p_file 'HP-UX'
gv_target CHANGING gv_err_flag.
CONCATENATE gv_input_dir p_file INTO gv_inputfile_dir.
open application server file
PERFORM open_file USING gv_inputfile_dir 'INPUT'
CHANGING gv_err_flag.
WHILE gv_eof_flag = 'N'.
READ DATASET gv_inputfile_dir INTO wa_itab.
APPEND wa_itab TO gt_itab.
IF sy-subrc <> 0.
gv_eof_flag = 'Y'.
EXIT.
ENDIF.
CALL METHOD me->read_input_file.
ENDWHILE.
close application file server
PERFORM close_file USING gv_inputfile_dir.
IF wa_footer-total_no_rec <> gv_input_file_ctr.
MOVE 'Header Control on Number of Records is Invalid' TO
gv_prg_message.
PERFORM call_ws_message USING 'E' gv_prg_message 'Error'.
gv_err_flag = 1.
ELSEIF wa_footer-total_no_rec EQ 0 AND gv_input_file_ctr EQ 0.
MOVE 'Input File is Empty. Batch Control will be Updated' TO
gv_prg_message.
PERFORM call_ws_message USING 'I' gv_prg_message 'Information'.
CALL METHOD me->update_batch_control.
gv_err_flag = 1.
ENDIF.
IF gv_err_flag <> 1.
IF wa_footer-total_amount <> gv_proc_tot_amt.
MOVE 'Header Control on Amount is Invalid' TO gv_prg_message.
PERFORM call_ws_message USING 'E' gv_prg_message 'Error'.
gv_err_flag = 1.
ENDIF.
ENDIF.
ENDMETHOD.
*/ METHOD read_input_file
METHOD read_input_file.
CASE wa_itab-rec_content+0(2).
WHEN '00'.
CALL METHOD me->split_header.
WHEN '01'.
CALL METHOD me->process_upload_file.
ADD 1 TO gv_input_file_ctr.
ADD wa_upfile-amount TO gv_proc_tot_amt.
WHEN '99'.
CALL METHOD me->split_footer.
WHEN OTHERS.
gv_err_flag = 1.
ENDCASE.
ENDMETHOD.
*/ METHOD split_header
METHOD split_header.
CLEAR: wa_header,
gv_string.
MOVE wa_itab TO gv_string.
SPLIT gv_string AT gv_delimiter INTO
wa_header-record_id
wa_header-from_system
wa_header-to_system
wa_header-event
wa_header-batch_no
wa_header-date
wa_header-time.
APPEND wa_header TO gt_header.
ENDMETHOD.
*/ METHOD process_upload_file
METHOD process_upload_file.
CLEAR gv_string.
ADD 1 TO gv_input_records.
MOVE wa_itab-rec_content TO gv_string.
CALL METHOD me->split_string.
CALL METHOD me->conv_num CHANGING amount = wa_upfile-amount.
APPEND wa_upfile TO gt_upfile.
ENDMETHOD.
*/ METHOD split_string
METHOD split_string.
CLEAR wa_upfile.
SPLIT gv_string AT gv_delimiter INTO
wa_upfile-record_id
wa_upfile-rec_date
wa_upfile-prod_line
wa_upfile-acc_code
wa_upfile-description
wa_upfile-hits
wa_upfile-amount.
ENDMETHOD.
*/ METHOD conv_num
METHOD conv_num.
DO.
REPLACE gv_delimiter WITH ' ' INTO amount.
IF sy-subrc <> 0.
EXIT.
ENDIF.
ENDDO.
ENDMETHOD.
*/ METHOD split_footer
METHOD split_footer.
CLEAR: wa_footer,
gv_string.
MOVE wa_itab TO gv_string.
SPLIT gv_string AT gv_delimiter INTO
wa_footer-record_id
wa_footer-total_no_rec
wa_footer-total_amount.
CALL METHOD me->conv_num CHANGING amount = wa_footer-total_amount.
APPEND wa_footer TO gt_footer.
ENDMETHOD.
*/ METHOD update_batch_control
METHOD update_batch_control.
DATA: lv_sys_date TYPE sy-datum,
lv_sys_time TYPE sy-uzeit,
lv_temp_date(10) TYPE c.
CONCATENATE wa_header-date4(4) wa_header-date2(2)
wa_header-date+0(2)
INTO lv_temp_date.
MOVE lv_temp_date TO wa_header-date.
APPEND wa_header-date TO gt_header.
Update ZTF0001 Table
PERFORM check_interface_header USING wa_header 'U' 'GLOB'
CHANGING gv_err_flag.
Archive files
PERFORM archive_files USING 'ZPPDARC' gv_inputfile_dir 'HP-UX'
gv_target CHANGING gv_err_flag.
ENDMETHOD.
METHOD process_data.
SORT gt_upfile ASCENDING.
CLEAR wa_upfile.
READ TABLE gt_upfile INDEX 1 INTO wa_upfile.
IF sy-subrc = 0.
MOVE: wa_upfile-rec_date+6(4) TO gv_gjahr,
wa_upfile-rec_date+0(2) TO gv_monat.
ENDIF.
ENDMETHOD.
ENDCLASS.
CLASS lcl_process_data IMPLEMENTATION
CLASS lcl_process_data IMPLEMENTATION.
METHOD process_data.
CALL METHOD super->process_data.
IF NOT gt_upfile[] IS INITIAL.
ENDIF.
ENDMETHOD.
ENDCLASS.
Start of selection *
START-OF-SELECTION.
DATA: read TYPE REF TO lcl_read_app_server_file,
process TYPE REF TO lcl_process_data.
CREATE OBJECT: read, process.
CALL METHOD read->read_app_server_file.
CALL METHOD process->process_data. -
Calling a drawLine() from one class to another from an ActionEvent
I have several JPanel objects called and placed on a JFrame. The JFrame has a RadioButton group with radio buttons. If I select a radio button and call a drawLine() method from a JPanel, I receive a "NullPointerException". Is it not possible to call this graphic method from one class to another?
Thanks for any input you can provide.
JohnRemember that each panel draws it's own current state. So you need the ActionPerformed to change the state in your target panel.
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import javax.swing.*;
import javax.swing.event.*;
public class PanelComm extends JPanel {
private SubPanelOne subPanelOne = new SubPanelOne();
private SubPanelTwo subPanelTwo = new SubPanelTwo();
public class SubPanelOne extends JPanel {
public SubPanelOne () {
setLayout ( new BorderLayout() );
setBorder ( BorderFactory.createTitledBorder ( "SubPanel One" ) );
Reactor reactor = new Reactor();
ButtonGroup group = new ButtonGroup();
JPanel radioPanel = new JPanel(new GridLayout(0, 1));
JRadioButton buttonOne = new JRadioButton ( "One" );
buttonOne.addActionListener ( reactor );
group.add ( buttonOne );
radioPanel.add ( buttonOne );
JRadioButton buttonTwo = new JRadioButton ( "Two" );
buttonTwo.addActionListener ( reactor );
group.add ( buttonTwo );
radioPanel.add ( buttonTwo );
JRadioButton buttonThree = new JRadioButton ( "Three" );
buttonThree.addActionListener ( reactor );
group.add ( buttonThree );
radioPanel.add ( buttonThree );
add ( radioPanel ,BorderLayout.LINE_START );
protected void paintComponent ( Graphics _g ) {
super.paintComponent ( _g );
Graphics2D g = (Graphics2D)_g;
g.setRenderingHint ( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
public class SubPanelTwo extends JPanel {
private JLabel text = new JLabel();
public SubPanelTwo () {
setLayout ( new BorderLayout() );
setBorder ( BorderFactory.createTitledBorder ( "SubPanel Two" ) );
text.setFont ( new Font ( "Verdana" ,Font.PLAIN ,30 ) );
text.setHorizontalAlignment ( JLabel.CENTER );
add ( text ,BorderLayout.CENTER );
protected void paintComponent ( Graphics _g ) {
super.paintComponent ( _g );
Graphics2D g = (Graphics2D)_g;
g.setRenderingHint ( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
public void setChoice ( String cmd ) {
text.setText ( cmd );
public class Reactor implements ActionListener {
public void actionPerformed ( ActionEvent e ) {
subPanelTwo.setChoice ( e.getActionCommand() );
public PanelComm () {
setLayout ( new GridLayout ( 1 ,2 ) );
add ( subPanelOne );
add ( subPanelTwo );
// main
public static void main ( String[] args ) {
JFrame f = new JFrame ( "Panel Communication" );
f.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
f.getContentPane().add ( new PanelComm() ,BorderLayout.CENTER );
f.setSize ( 320 ,120 );
f.setVisible ( true );
} // main
} -
Moving a method from one class to another issues
Hi, im new. Let me explain what i am trying to achieve. I am basically trying to move a method from one class to another in order to refactor the code. However every time i do, the program stops working and i am struggling. I have literally tried 30 times these last two days. Can some one help please? If shown once i should be ok, i pick up quickly.
Help would seriously be appreciated.
Class trying to move from, given that this is an extraction:
class GACanvas extends Panel implements ActionListener, Runnable {
private WorldMenuItems speedMenuItems, designMenuItemsPlantGrowth, designMenuItemsPlantCount;
private WorldMenuItems designMenuItemsPlantEaten, designMenuItemsApproximatePopulation;
private WorldMenuItems designMenuItemsEatersBorn,designMenuItemsMutationProbability;
private WorldMenuItems designMenuItemsCrossoverProbability;
MenuBar getMenuBar() {
menuBar = new MenuBar();
addControlItemsToMenuBar();
addSpeedItemsToMenuBar();
addWorldDesignItemsToMenuBar();
return menuBar;
This is the method i am trying to move (below)
public void itemsInsideWorldDesignMenu() {
designMenuItemsPlantGrowth = new WorldMenuItems("Plants Grow",
new String[] { "In Rows", "In Clumps", "At Random",
"Along the Bottom", "Along the Edges" }, 1);
designMenuItemsPlantCount = new WorldMenuItems("Number Of Plants",
new String[] { "50", "100", "150", "250", "500" }, 3);
designMenuItemsPlantEaten = new WorldMenuItems("When a Plant is Eaten",
new String[] { "It grows back somewhere",
"It grows back nearby", "It's Gone" }, 0);
designMenuItemsApproximatePopulation = new WorldMenuItems(
"Approximate Population", new String[] { "10", "20", "25",
"30", "40", "50", "75", "100" }, 2);
designMenuItemsEatersBorn = new WorldMenuItems("Eaters are Born",
new String[] { "At the Center", "In a Corner",
"At Random Location", "At Parent's Location" }, 2);
designMenuItemsMutationProbability = new WorldMenuItems(
"Mutation Probability", new String[] { "Zero", "0.25%", "0.5%",
"1%", "2%", "3%", "5%", "10%" }, 3);
designMenuItemsCrossoverProbability = new WorldMenuItems(
"Crossover Probability", new String[] { "Zero", "10%", "25%",
"50%", "75%", "100%" }, 4);
Class Trying to move to:
class WorldMenuItems extends Menu implements ItemListener {
private CheckboxMenuItem[] items;
private int selectedIndex = -1;
WorldMenuItems(String menuName, String[] itemNames) {
this(menuName, itemNames, -1);
WorldMenuItems(String menuName, String[] itemNames, int selected) {
super(menuName);
items = new CheckboxMenuItem[itemNames.length];
for (int i = 0; i < itemNames.length; i++) {
items[i] = new CheckboxMenuItem(itemNames);
add(items[i]);
items[i].addItemListener(this);
selectedIndex = selected;
if (selectedIndex < 0 || selectedIndex >= items.length)
selectedIndex = 1;
items[selectedIndex].setState(true);
public int getSelectedIndex() {
return selectedIndex;
public void itemStateChanged(ItemEvent evt) { // This works on other systems
CheckboxMenuItem newSelection = (CheckboxMenuItem)evt.getSource();
for (int i = 0; i < items.length; i++) {
if (newSelection == items[i]) {
items[selectedIndex].setState(false);
selectedIndex = i;
newSelection.setState(true);
return;Ok i've done this. I am getting an error on the line specified. Can someone help me out and tell me what i need to do?
GACanvas
//IM GETTING AN ERROR ON THIS LINE UNDER NAME, SAYING IT IS NOT VISIBLE
WorldMenuItems worldmenuitems = new WorldMenuItems(name, null);
public MenuBar getMenuBar() {
menuBar = new MenuBar();
addControlItemsToMenuBar();
addSpeedItemsToMenuBar();
worldmenuitems.addWorldDesignItemsToMenuBar();
return menuBar;
class WorldMenuItems extends Menu implements ItemListener {
private WorldMenuItems speedMenuItems, designMenuItemsPlantGrowth, designMenuItemsPlantCount;
private WorldMenuItems designMenuItemsPlantEaten, designMenuItemsApproximatePopulation;
private WorldMenuItems designMenuItemsEatersBorn,designMenuItemsMutationProbability;
private WorldMenuItems designMenuItemsCrossoverProbability;
GACanvas gacanvas = new GACanvas(null);
private CheckboxMenuItem[] items;
private int selectedIndex = -1;
WorldMenuItems(String menuName, String[] itemNames) {
this(menuName, itemNames, -1);
WorldMenuItems(String menuName, String[] itemNames, int selected) {
super(menuName);
items = new CheckboxMenuItem[itemNames.length];
for (int i = 0; i < itemNames.length; i++) {
items[i] = new CheckboxMenuItem(itemNames);
add(items[i]);
items[i].addItemListener(this);
selectedIndex = selected;
if (selectedIndex < 0 || selectedIndex >= items.length)
selectedIndex = 1;
items[selectedIndex].setState(true);
public int getSelectedIndex() {
return selectedIndex;
public void itemStateChanged(ItemEvent evt) { // This works on other systems
CheckboxMenuItem newSelection = (CheckboxMenuItem)evt.getSource();
for (int i = 0; i < items.length; i++) {
if (newSelection == items[i]) {
items[selectedIndex].setState(false);
selectedIndex = i;
newSelection.setState(true);
return;
public void itemsInsideWorldDesignMenu() {
designMenuItemsPlantGrowth = new WorldMenuItems("Plants Grow",
new String[] { "In Rows", "In Clumps", "At Random",
"Along the Bottom", "Along the Edges" }, 1);
designMenuItemsPlantCount = new WorldMenuItems("Number Of Plants",
new String[] { "50", "100", "150", "250", "500" }, 3);
designMenuItemsPlantEaten = new WorldMenuItems("When a Plant is Eaten",
new String[] { "It grows back somewhere",
"It grows back nearby", "It's Gone" }, 0);
designMenuItemsApproximatePopulation = new WorldMenuItems(
"Approximate Population", new String[] { "10", "20", "25",
"30", "40", "50", "75", "100" }, 2);
designMenuItemsEatersBorn = new WorldMenuItems("Eaters are Born",
new String[] { "At the Center", "In a Corner",
"At Random Location", "At Parent's Location" }, 2);
designMenuItemsMutationProbability = new WorldMenuItems(
"Mutation Probability", new String[] { "Zero", "0.25%", "0.5%",
"1%", "2%", "3%", "5%", "10%" }, 3);
designMenuItemsCrossoverProbability = new WorldMenuItems(
"Crossover Probability", new String[] { "Zero", "10%", "25%",
"50%", "75%", "100%" }, 4);
public void addWorldDesignItemsToMenuBar() {
gacanvas = new GACanvas(null);
itemsInsideWorldDesignMenu();
Menu designMenuItems = new Menu("WorldDesign");
designMenuItems.add(designMenuItemsPlantGrowth);
designMenuItems.add(designMenuItemsPlantCount);
designMenuItems.add(designMenuItemsPlantEaten);
designMenuItems.add(designMenuItemsApproximatePopulation);
designMenuItems.add(designMenuItemsEatersBorn);
designMenuItems.add(designMenuItemsMutationProbability);
designMenuItems.add(designMenuItemsCrossoverProbability);
gacanvas.menuBar.add(designMenuItems); -
Transfering text from one class to another
Hi, I'm having a lot of trouble with getting the text from a textArea in a frame to transfer from one class to another.
I could really use any help given.
Thanks
Here's where the text should come from
import javax.swing.*;
import BreezySwing.*;
import java.util.*;
public class UserFrame extends GBFrame {
//String Design = null;
private
JTextArea InputArea = addTextArea
("...",1,1,1,1);
JButton drawButton = addButton
("Draw" ,3,1,1,1);
// UserPanel dPanel = new UserPanel();
GraphicsInputPanel dPanel = new GraphicsInputPanel();
GBPanel panel = addPanel(dPanel, 1, 2, 1, 1);
public void buttonClicked (JButton buttonObj){
GraphicsInputPanel.setdesign(InputArea.getText());
// rbPanel setDesign(graphicCodeArea.getText());
public static void main(String[] args) {
UserFrame tpo = new UserFrame();
tpo.setSize(400, 300);
tpo.setVisible(true);
and here's where it should be going
import BreezySwing.*;
import java.awt.*;
import java.util.*;
public class GraphicsInputPanel extends GBPanel{
String design;
public void setdesign (String d){
design = d;
public void paintComponent (Graphics g){
super.paintComponent(g);
StringTokenizer lines = new StringTokenizer(design, "\n");
while (lines.hasMoreTokens()){
String line = lines.nextToken();
if (design.equals ("Blue")){
g.setColor(Color.blue);
}else if (design.equals("Green")){
g.setColor(Color.green);
g.fillRect(0,0,100,100);
public void setDesign(String d){
design = d;
repaint();
}Hello Saqib,
The requirement to transfer asset with value date in the past year contradict the objective of audit trail established in the system although it is technically possible to do. Perhaps you should convince your client to adopt the standard approach, i.e. value date as at the date of asset transfer.
Kind regards,
John Chin -
Pass RowSet from one class to another
Hi, i am trying to pass a rowset from one class to another but i keep getting the error messages:
method does not return a value
statement not reachable
Does anybody know why?
package project1;
import java.sql.SQLException;
public class readdata {
public static void main(String[] args) {
Class2 cl = new Class2();
try {
while (cl.openConnection().next()) {
System.out.println(cl.openConnection().getInt("id") + "-");
catch (SQLException se)
System.out.println(se);
// while (rs.next())
// System.out.println(rs.getInt("id") + "-");
// System.out.println(rs.getString("field1") + '\n');
package project1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.RowSet;
public class Class2 {
private Connection conn;
public Class2() {
openConnection();
public RowSet openConnection()
try
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
conn = DriverManager.getConnection("jdbc:odbc:;DRIVER=Microsoft Access Driver (*.mdb);DBQ=D:\\test.mdb;PWD=","admin","");
Statement command = conn.createStatement();
RowSet rs = (RowSet)command.executeQuery("select * FROM testing");
return rs;
System.out.println("Connected To Access");
rs.close();
conn.close();
catch (SQLException se)
System.out.println(se);
catch (Exception ex)
System.out.println(ex);
}Thanks in advance
Message was edited by:
snipered2003
Message was edited by:
snipered2003Hi snipered2003
I'm fairly new to java, so check out anything I say.
to me it appears that the code within your try block in the main method of readdata class can never throw a SQLException since the calls are to cl.openConnection() which catches any SQLException and does not throw it.
So one statement not reachable is the statement in the catch blockSystem.out.println(se);Second, the only return statement in your openConnection() method is inside the try block, whic means that if an exception is encountered there will be no RowSet returned by the method.
Secondly, the code in the try block in your Class2.openConnection() after the return statement will also never be reached.
You may need something like public RowSet openConnection()
RowSet rs = null;
try
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
conn = DriverManager.getConnection("jdbc:odbc:;DRIVER=Microsoft Access Driver (*.mdb);DBQ=D:\\test.mdb;PWD=","admin","");
Statement command = conn.createStatement();
rs = (RowSet)command.executeQuery("select * FROM testing");
System.out.println("Connected To Access");
catch (SQLException se)
System.out.println(se);
catch (Exception ex)
System.out.println(ex);
return rs;
}But you will have to check for a null return value in the call to the method.
It also looks like the code in your main method, when these things are ironed out, will run an infinite loop, but I could be wrong on that.
I think (note: think) this part should be RowSet rs = cl.openConnection()
if (rs != null) {
while (rs.next()) {
System.out.println(rs.getInt("id") + "-");
rs.close();
}Anybody please correct me if I am wrong.
And I don't know where the conn.close would fit in this scheme of things.
Cheers, Darryl -
Fire event from one class to another.
I have a Login JFrame class that allows users to enter username and password. I then have another JFrame class which will monitor when someone logs in. I am trying to get the username and password to appear on the monitor login frame text area when the user presses enter on the login frame.
I can get it ot work by passing the Monitor class into the Login classes constructor but I want to be able to open the classes separately.When I try to open separatley at present I get java.lang.NullPointerException
at project.LoginGUI.actionPerformed(LoginGUI.java:70) which is referring to the following code:
if(listen.equals("OK")){
GymMonitor.username.setText(username.getText());
Both classes are in the same package. What I want to know is how to fire an event from one class to another? when the class you are firing to is constructed separately.
I hope this question is not too verbose.
ThanksGenerally for something like this you would use a listener.
Your login window is its own entity--it has a user interface, and it gets some information which someone else could ask it for. It could even generate its own events, such as when the user presses "OK". You would first define an interface for anyone who wants to know when someone logs in:
public interface ILoginListener extends java.util.EventListener
public void login(LoginEvent event);
}You would then define the LoginEvent class to contain information like what the user entered for username and password. You could give your login dialog a couple of methods:
private Vector myListeners = new Vector();
public void addLoginListener(ILoginListener listener) {
myListeners.add(listener);
public void removeLoginListener(ILoginListener listener) {
myListeners.remove(listener);
protected void fireLogin(LoginEvent event) {
for (Iterator it = myListeners.iterator(); it.hasNext(); ) {
ILoginListener listener = (ILoginListener)it.next();
listener.login(event);
}You'd have your login dialog call fireLogin every time the user logged in.
Then, you could implement ILoginListener in your monitor window:
public void login(LoginEvent event) {
// now do something with the event you just got.
}All the code I put in here is really generic stuff. You'll write this kind of stuff hundreds of times probably during your career. I haven't tested it though.
Hope this helps. :) -
Pass variable value from one dashboard to another dashboard
Hello,
I have one main dashboard which have "year" prompt with drop down and variaous links & also some reports.
And we have same year prompt on another dashboards only difference is, this prompt is editable not drop down.
The requirement is, when I navigate from main dashboard to another dashboard through reports, that time selected prompt value
comes in navigated dashboard prompt.
But When I navigate from main dashboard to another dashboard using Link or using <A Href> tag, now selected prompt value can not come in navigated dashboard prompt.
How can we pass selected prompt value from one dashboard to another dashboard? OR Is there any other technique?
Thanks,
PradipHi,
You need to make the scope of the prompt as 'Dashboard' and if this doesnt work.
Then use presentation variable in the first prompt and pass it to the second prompt.
So this will surely pass the values across pages.
Regards
MuRam
NOTE: Please mention if this resolved your problem/still facing and close the thread. -
Using a variable from one class to another
Hi !
I've a class called ModFam (file ModFam.java) where I define a variable as
protected Connection dbconn;
Inside ModFam constructor I said:
try
String url = "jdbc:odbc:baselocal";
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
dbconn = DriverManager.getConnection(url);
System.err.println("Connection successful");
} ..... rest of code
This class define a TabbedPane as follows:
tabbedPane.addTab("Welcome",null,new Familias(),"Familias");
As you can see it call a new instance of the Familias class (file Familias.java).
This constructor will try to connect with the DB to populate a combo box with some data retireved from the DB.
If I do
Statement stmt;
stmt = dbconn.createStatement();
inside Familias constructor I receive the message
Familias.java:50: cannot resolve symbol
symbol : variable dbconn
location: class fam.Familias
stmt = dbconn.createStatement();
at compile time.
While I can�t use a variable defined as "protected" in one class of my package on another class of the same package ?
How could I do ?
Thanks in advance
<jl>Familias doesn't have a reference to ModFam or the Connection.
So change the constructor in Familias to be
public class Familias {
private ModFam modFam;
public Familias(ModFam m) {
modFam = m;
// ... somewhere else in the code
Statement stmt = modFam.dbconn.createStatement();
}or
public class Familias {
private Connection dbconn;
public Familias(Connection c) {
dbconn = c;
// ... somewhere else in the code
Statement stmt = dbconn.createStatement();
}And when you instantiate Familias it should then be
new Familias(this) // ModFam reference
or
new Familias(dbconn) -
Sending a variable from one class to another?
Dear Java Users - please can you help me out here... I know that what I am asking should be straight forward BUT I just don't understand any of the responses people have put on the web....
Here is what I am trying to do:
This piece of code - creates a window with a simple textbox on it to enter a word...
The button then calls another class file to open a new window...
All I want to do is to take the word from the text box and print it in the new window....
The first .java file I have is this:
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class FrontPageGUI extends JFrame implements ActionListener
//declare all instance variables for THIS per class
JLabel lblInfoOne;
JLabel lblButtonPopUp;
JTextField txtName;
JButton close;
JButton popUp;
public FrontPageGUI()
//set characteristics of the JFrame object
super("Title Bar");
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
//we need to define a Container to place objects onto the frame - this is inside the JFrame Object Above
Container ca = getContentPane( );
ca.setSize(600,600);
ca.setBackground(Color.white);
ca.setLayout(null);
//define all other objects and set thier characteristics
lblInfoOne = new JLabel("Enter a word in the box above to send:");
lblButtonPopUp = new JLabel("Click Here:");
txtName = new JTextField("");
//create Button components
close = new JButton("Close");
popUp = new JButton("Click Me");
//now add all objects to the container
//Labels
addXY(ca,lblInfoOne, 30, 160, 550,45);
addXY(ca,lblButtonPopUp, 30, 210, 550,45);
//TextField
addXY(ca,txtName, 120, 100, 200,30);
//Buttons
addButtonXY(ca, popUp, 30, 260, 200, 45);
addButtonXY(ca, close, 30, 310, 80, 30);
// add the Container to the Frame
setContentPane(ca);
void addButtonXY(Container c, JButton cp, int x, int y, int w, int h)
cp.setBounds(x,y,w,h);
cp.addActionListener(this);
c.add(cp);
void addXY(Container c, Component cp, int x, int y, int w, int h)
cp.setBounds(x,y,w,h);
c.add(cp);
public void actionPerformed(ActionEvent event)
if (event.getSource()== popUp)
//This is WHERE THE PROBLEM IS...
//Here I want to send to contents of the textfield - txtName
String temp = txtName.getText();
new PopUpGUI(temp);
if (event.getSource()==close)
closeUp();
void closeUp()
System.exit(0);
//dispose();
//we need a driver program - this is the only time MAIN is used.
public class FrontPage
//create an instance of the GUI and showit
public static void main(String args [])
new FrontPageGUI();
The second .java file I have is this:
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class PopUpGUI extends JFrame implements ActionListener
//declare all instance variables ie per class
JLabel headerLabel;
JLabel sentLabel;
JButton close;
public PopUpGUI(String Sent)
//set characteristics of the JFrame object
super("Pop Up Window");
setSize(320,450);
setVisible(true);
//need to define a Container to place objects onto the frame
Container ca = getContentPane( );
ca.setSize(320,450);
ca.setLayout(null);
//define all other objects and set characteristics
headerLabel = new JLabel("New Window!"); //heading label
sentLabel = new JLabel(Sent);
close = new JButton("Close");
//now add all objects to the container
addXY(ca,headerLabel,10,10,380,80);
addXY(ca,sentLabel,10,100,380,80);
addButtonXY(ca, close, 50, 200, 100, 30); //Bottom Left
// add the Container to the Frame
setContentPane(ca);
//We need these 2 methods - EVERY TIME
void addButtonXY(Container c, JButton cp, int x, int y, int w, int h)
cp.setBounds(x,y,w,h);
cp.addActionListener(this);
c.add(cp);
void addXY(Container c, Component cp, int x, int y, int w, int h)
cp.setBounds(x,y,w,h);
c.add(cp);
//What to do when the click happens
public void actionPerformed(ActionEvent event)
if (event.getSource()==close)
dispose();
//closeUp(); - Doesn't run CLOSEUP this time (i.e. exit program) - instead just DISPOSEs of the window
//Driver class is in FrontPage.javaThis seems to work... but is it the best way to do it????
Tony.Well,
Using the constructor is the way to go. Otherwise create a method that takes the string as parameter.
Maybe you are looking for
-
Webdynpro ABAP/Portal. Plugin HTTP connection issue on WaitingEventQueue.js
Hello, We are experiencing a strange Portal Behavior with our Webdynpros. Our portal contains several iViews including some Webdynpro (ABAP) and some reporting transaction calls that use SAPgui for HTML. When portal is called for the first time and a
-
I have installed windows on the new NTFS partician and cant boot it back to mac
I have installed windows on the new NTFS partician and cant boot it back to mac. I dont think I loaded the bootcamp for windows properly now it is stuck in Windows with no bootcamp icon
-
Does report2.5 works with srw.run_report and Oracle Apps11.0.3
Hi, I have reports2.5 and using srw,run_report I want to call another report. NOw I have registered this in oracle apps 11.0.3 . Now through oracle apps if I run the main report it has to call the child report (calling via srw.run_report) and the out
-
Windows Server 2012 R2 boots in CMD after several Restarts
Hi, I have been facing this problem after i installed some applications on the server and after we did several restarts the server boots up only in cmd. I am very sure that i installed the OS with GUI since i have logged in with it while i am instal
-
Is there a way to find my sons iPod by the serial #.
Someone on my sons bus stole his iPod Touch Gen 4. I have the serial#. Is there a way to find his iPod by the serial #? Or anything else that can help?