Reference to string from another class
I've searched google and this forum a bit, but can't seem to find an answer. I'd say the thing I'm looking for is really simple and essential, so I must be a moron. But anyways; I want to get the output of the "process" thing in another class. How do I reference to that string fomr outside it's class?
Thanks.
public class ReadInput {
private static void printCommands() {
System.out.println("blabla");
System.out.println("blabla");
System.out.println("blabla");
public static void process(String in) {
Do something with the String "in" here. Say, eventually rename it to "output".
public static void doReadFromStdin() {
try {
BufferedReader inStream = new BufferedReader (
new InputStreamReader(System.in)
String inLine = "";
String in = inLine;
while ( !(in.equalsIgnoreCase("quit"))
!(in.equalsIgnoreCase("exit")) ) {
System.out.print("prompt> ");
in = inStream.readLine();
process(in);
} catch (IOException e) {
System.out.println("IOException: " + e);
public static void main(String[] args) {
printCommands();
doReadFromStdin();
}
Maybe this might help
Igor_Pavlove wrote:
public static void process(String in) {
Do something with the String "in" here. Say, eventually rename it to "output".
public static String process(String in){
//Do something, e.g.
String temp = "ifeeltired";
return temp; //Returns the String temp when this method is called.
public static void main(String[] args) {
printCommands();
doReadFromStdin();
public static void main(String[] args){
String temp = "thisisaroughexamples";
String result = this.process(temp); //Returns a string and stores it in result
CreatePlural.print(result); //This is possible because the method print() in CreatePlural is static and an instance of CreatePlural is not required.
}Edited by: Melanie_Green on Feb 2, 2009 6:46 AM
Edited by: Melanie_Green on Feb 2, 2009 6:47 AM
Similar Messages
-
Calling a TextFields get method from another class as a String
This is my first post so be kind....
I'm trying to create a login screen with Java Studio Creator. The Login.jsp has a Text Field for both the username and password. JSC automatically created get and set methods for these.
public class Login extends AbstractPageBean
private TextField usernameTF = new TextField();
public TextField getUsernameTF() {
return usernameTF;
public void setUsernameTF(TextField tf) {
this.usernameTF = tf;
private PasswordField passwordTF = new PasswordField();
public PasswordField getPasswordTF() {
return passwordTF;
public void setPasswordTF(PasswordField pf) {
this.passwordTF = pf;
My problem is in trying to call these methods from another class and return the value as a string.
Any help on this matter would be greatly appreciated.the method returns the textfield, so you just need to get its text
import java.awt.*;
class Testing
public Testing()
Login login = new Login();
System.out.println(login.getUsernameTF().getText());//<----
public static void main(String[] args){new Testing();}
class Login
private TextField usernameTF = new TextField("Joe Blow");
public TextField getUsernameTF() {
return usernameTF;
} -
Problem getting arraylist from another class
I am trying to call information about an arraylist from another class. I am using this code to call the size of an arraylist:
import java.io.*;
public class Test
public static void main(String argv[]) throws IOException
Echo03 thing = new Echo03();
int y=thing.value();
System.out.println(y);
Echo03 thing2 = new Echo03();
int x=thing2.percent.size();
System.out.println(x);
}from another file which starts like this:
public class Echo03 extends DefaultHandler
static ArrayList<String> percent = new ArrayList<String>();
static ArrayList<String> text = new ArrayList<String>();
int a;
public int value(){
return percent.size();
public static void main(String argv[]) throws IOException
{The second file is based on an example piece of code from the Java website. I havent posted the whole thing, but if it is relevant then please ask.
Anyway when I run Echo03 by itself, the arraylist has a size of 2. But when I run it from the Test file, it says a size of 0. Is this because the data is not being transferred between the classes? Or is the Echo03 program not executing (and hence the arraylist is not filling up)?
How can I fix this? I have tried 2 ways of calling the data (As seen in my Test file). Neither work.I didnt post the full bit of the code for the second one. Here it is:
import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import java.util.ArrayList;
import java.awt.*;
import javax.swing.*;
public class Echo03 extends DefaultHandler
static ArrayList<String> percent = new ArrayList<String>();
static ArrayList<String> text = new ArrayList<String>();
int a;
public static void main(String argv[]) throws IOException
if (argv.length != 1) {
System.err.println("Usage: cmd filename");
System.exit(1);
// Use an instance of ourselves as the SAX event handler
DefaultHandler handler = new Echo03();
// Use the default (non-validating) parser
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
// Set up output stream
out = new OutputStreamWriter(System.out, "UTF8");
// Parse the input
SAXParser saxParser = factory.newSAXParser();
saxParser.parse( new File(argv[0]), handler);
for (int b=0; b<percent.size();b++){
System.out.println(percent.get(b+1));
} catch (Throwable t) {
System.exit(0);
static private Writer out;
public void startElement(String namespaceURI,
String lName, // local name
String qName, // qualified name
Attributes attrs)
throws SAXException
if (attrs != null) {
StringBuffer sb = new StringBuffer (250);
for (int i = 0; i < attrs.getLength(); i++) {
nl();
emit(attrs.getValue(i));
sb.append (attrs.getValue(i));
String sf = sb.toString ();
percent.add(sf);
System.out.println(" String: "+sf); a++;
public void characters(char buf[], int offset, int len)
throws SAXException
emit(" ");
String s = new String(buf, offset, len);
if (!s.trim().equals("")) {text.add(s); emit(s);}
//===========================================================
// Utility Methods ...
//===========================================================
// Wrap I/O exceptions in SAX exceptions, to
// suit handler signature requirements
private void emit(String s)
throws SAXException
try {
out.write(s);
out.flush();
} catch (IOException e) {
throw new SAXException("I/O error", e);
// Start a new line
private void nl()
throws SAXException
String lineEnd = System.getProperty("line.separator");
try {
out.write(lineEnd);
} catch (IOException e) {
throw new SAXException("I/O error", e);
} -
Calling a class's method from another class
Hi, i would like to know if it's possible to call a Class's method and get it's return from another Class. This first Class doesn't extend the second. I've got a Choice on this first class and depending on what is selected, i want to draw a image on the second class witch is a Panel extended. I put the control "if" on the paint() method of the second class witch is called from the first by the repaint() (first_class.repaint()) on itemStateChanged(). Thankx 4 your help. I'm stuck with this.This program is for my postgraduation final project and i'm very late....
import java.awt.*;
import java.sql.*;
* This type was generated by a SmartGuide.
class Test extends Frame {
private java.awt.Panel ivjComboPane = null;
private java.awt.Panel ivjContentsPane = null;
IvjEventHandler ivjEventHandler = new IvjEventHandler();
private Combobox ivjCombobox1 = null;
class IvjEventHandler implements java.awt.event.WindowListener {
public void windowActivated(java.awt.event.WindowEvent e) {};
public void windowClosed(java.awt.event.WindowEvent e) {};
public void windowClosing(java.awt.event.WindowEvent e) {
if (e.getSource() == Test.this)
connEtoC1(e);
public void windowDeactivated(java.awt.event.WindowEvent e) {};
public void windowDeiconified(java.awt.event.WindowEvent e) {};
public void windowIconified(java.awt.event.WindowEvent e) {};
public void windowOpened(java.awt.event.WindowEvent e) {};
private Panel ivjPanel1 = null;
* Combo constructor comment.
public Test() {
super();
initialize();
* Combo constructor comment.
* @param title java.lang.String
public Test(String title) {
super(title);
* Insert the method's description here.
* Creation date: (11/16/2001 7:48:51 PM)
* @param s java.lang.String
public void conexao(String s) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String url = "jdbc:oracle:thin:system/[email protected]:1521:puc";
Connection db = DriverManager.getConnection(url);
//String sql_str = "SELECT * FROM referencia";
Statement sq_stmt = db.createStatement();
ResultSet rs = sq_stmt.executeQuery(s);
ivjCombobox1.addItem("");
while (rs.next()) {
String dt = rs.getString(1);
ivjCombobox1.addItem(dt);
db.close();
} catch (SQLException e) {
System.out.println("Erro sql" + e);
} catch (ClassNotFoundException cnf) {
* connEtoC1: (Combo.window.windowClosing(java.awt.event.WindowEvent) --> Combo.dispose()V)
* @param arg1 java.awt.event.WindowEvent
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void connEtoC1(java.awt.event.WindowEvent arg1) {
try {
// user code begin {1}
// user code end
this.dispose();
// user code begin {2}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {3}
// user code end
handleException(ivjExc);
* Return the Combobox1 property value.
* @return Combobox
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private Combobox getCombobox1() {
if (ivjCombobox1 == null) {
try {
ivjCombobox1 = new Combobox();
ivjCombobox1.setName("Combobox1");
ivjCombobox1.setLocation(30, 30);
// user code begin {1}
this.conexao("select * from referencia");
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {2}
// user code end
handleException(ivjExc);
return ivjCombobox1;
* Return the ComboPane property value.
* @return java.awt.Panel
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private java.awt.Panel getComboPane() {
if (ivjComboPane == null) {
try {
ivjComboPane = new java.awt.Panel();
ivjComboPane.setName("ComboPane");
ivjComboPane.setLayout(null);
getComboPane().add(getCombobox1(), getCombobox1().getName());
getComboPane().add(getPanel1(), getPanel1().getName());
// user code begin {1}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {2}
// user code end
handleException(ivjExc);
return ivjComboPane;
* Return the ContentsPane property value.
* @return java.awt.Panel
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private java.awt.Panel getContentsPane() {
if (ivjContentsPane == null) {
try {
ivjContentsPane = new java.awt.Panel();
ivjContentsPane.setName("ContentsPane");
ivjContentsPane.setLayout(new java.awt.BorderLayout());
getContentsPane().add(getComboPane(), "Center");
// user code begin {1}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {2}
// user code end
handleException(ivjExc);
return ivjContentsPane;
* Return the Panel1 property value.
* @return Panel
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private Panel getPanel1() {
if (ivjPanel1 == null) {
try {
ivjPanel1 = new Panel();
ivjPanel1.setName("Panel1");
ivjPanel1.setBackground(java.awt.SystemColor.scrollbar);
ivjPanel1.setBounds(24, 118, 244, 154);
// user code begin {1}
// user code end
} catch (java.lang.Throwable ivjExc) {
// user code begin {2}
// user code end
handleException(ivjExc);
return ivjPanel1;
* Called whenever the part throws an exception.
* @param exception java.lang.Throwable
private void handleException(java.lang.Throwable exception) {
/* Uncomment the following lines to print uncaught exceptions to stdout */
// System.out.println("--------- UNCAUGHT EXCEPTION ---------");
// exception.printStackTrace(System.out);
* Initializes connections
* @exception java.lang.Exception The exception description.
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void initConnections() throws java.lang.Exception {
// user code begin {1}
// user code end
this.addWindowListener(ivjEventHandler);
* Initialize the class.
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void initialize() {
try {
// user code begin {1}
// user code end
setName("Combo");
setLayout(new java.awt.BorderLayout());
setSize(460, 300);
setTitle("Combo");
add(getContentsPane(), "Center");
initConnections();
} catch (java.lang.Throwable ivjExc) {
handleException(ivjExc);
// user code begin {2}
// user code end
* Insert the method's description here.
* Creation date: (11/17/2001 2:02:58 PM)
* @return java.lang.String
public String readCombo() {
String dado = ivjCombobox1.getSelectedItem();
return dado;
* Starts the application.
* @param args an array of command-line arguments
public static void main(java.lang.String[] args) {
try {
/* Create the frame */
Test aTest = new Test();
/* Add a windowListener for the windowClosedEvent */
aTest.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosed(java.awt.event.WindowEvent e) {
System.exit(0);
aTest.setVisible(true);
} catch (Throwable exception) {
System.err.println("Exception occurred in main() of Test");
exception.printStackTrace(System.out);
* Insert the type's description here.
* Creation date: (11/17/2001 1:59:15 PM)
* @author:
class Combobox extends java.awt.Choice {
public java.lang.String dado;
* Combobox constructor comment.
public Combobox() {
super();
initialize();
* Called whenever the part throws an exception.
* @param exception java.lang.Throwable
private void handleException(java.lang.Throwable exception) {
/* Uncomment the following lines to print uncaught exceptions to stdout */
// System.out.println("--------- UNCAUGHT EXCEPTION ---------");
// exception.printStackTrace(System.out);
* Initialize the class.
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void initialize() {
try {
// user code begin {1}
// user code end
setName("Combobox");
setSize(133, 23);
} catch (java.lang.Throwable ivjExc) {
handleException(ivjExc);
// user code begin {2}
// user code end
* main entrypoint - starts the part when it is run as an application
* @param args java.lang.String[]
public static void main(java.lang.String[] args) {
try {
java.awt.Frame frame = new java.awt.Frame();
Combobox aCombobox;
aCombobox = new Combobox();
frame.add("Center", aCombobox);
frame.setSize(aCombobox.getSize());
frame.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
frame.setVisible(true);
} catch (Throwable exception) {
System.err.println("Exception occurred in main() of Combobox");
exception.printStackTrace(System.out);
* Insert the type's description here.
* Creation date: (11/17/2001 2:16:11 PM)
* @author:
class Panel extends java.awt.Panel {
* Panel constructor comment.
public Panel() {
super();
initialize();
* Panel constructor comment.
* @param layout java.awt.LayoutManager
public Panel(java.awt.LayoutManager layout) {
super(layout);
* Called whenever the part throws an exception.
* @param exception java.lang.Throwable
private void handleException(java.lang.Throwable exception) {
/* Uncomment the following lines to print uncaught exceptions to stdout */
// System.out.println("--------- UNCAUGHT EXCEPTION ---------");
// exception.printStackTrace(System.out);
* Initialize the class.
/* WARNING: THIS METHOD WILL BE REGENERATED. */
private void initialize() {
try {
// user code begin {1}
// user code end
setName("Panel");
setLayout(null);
setSize(260, 127);
} catch (java.lang.Throwable ivjExc) {
handleException(ivjExc);
// user code begin {2}
// user code end
* main entrypoint - starts the part when it is run as an application
* @param args java.lang.String[]
public static void main(java.lang.String[] args) {
try {
java.awt.Frame frame = new java.awt.Frame();
Panel aPanel;
aPanel = new Panel();
frame.add("Center", aPanel);
frame.setSize(aPanel.getSize());
frame.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
frame.setVisible(true);
} catch (Throwable exception) {
System.err.println("Exception occurred in main() of java.awt.Panel");
exception.printStackTrace(System.out);
* Insert the method's description here.
* Creation date: (11/17/2001 2:18:36 PM)
public void paint(Graphics g) {
/* Here's the error:
C:\Test.java:389: non-static method readCombo() cannot be referenced from a static context
System.out.println(Test.lerCombo());*/
System.out.println(Test.readCombo()); -
Accessing string from other classes
Sorry if this seems simple to you, but i'm having problems accessing four string that are declared and used in my public class from another class.
I've tried declaring the strings public but it still says 'cannot resolve symbol' when i try to compile.
Help much appreciated.
fightspamYep, heres my code(sorry if it's a bit untidy):
//Zimmerman M3 email client.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
class where extends JFrame implements ActionListener
private JLabel path;
private JTextField pathText;
private String pathFile;
private JButton save;
File outputFile = new File(pathFile);
public where()
super("Save Email");
Container f=getContentPane();
f.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
f.setBackground(Color.lightGray);
path = new JLabel("Path: ");
f.add(path);
pathText = new JTextField(20);
f.add(pathText);
save = new JButton("Save");
f.add(save);
this.setSize(300, 100);
public void actionPerformed(ActionEvent q)
pathFile = pathText.getText();
try
FileWriter out = new FileWriter(outputFile);
out.write(zimmernorm.toFile);
out.write(zimmernorm.fromFile);
out.write(zimmernorm.subjectFile);
out.write(zimmernorm.bodyFile);
out.close();
catch(IOException err)
System.exit(0);
class about extends JFrame
private JLabel title;
public about()
super("About Zimmerman M3");
Container d=getContentPane();
d.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
d.setBackground(Color.lightGray);
title = new JLabel("Zimmerman M3 by Louis Goddard, 2003");
d.add(title);
this.setSize(246, 62);
class newmail extends JFrame implements ActionListener
public static String toFile, fromFile, subjectFile, bodyFile;
public JTextField To, From, Subject;
private String toBuffer, fromBuffer, subjectBuffer, bodyBuffer;
private JButton send, clear;
private JTextArea Body;
private JLabel toLabel, fromLabel, subjectLabel;
private JMenuBar mb;
private JMenu File, Edit;
private JMenuItem New, Sender, Copy, Paste, About;
public newmail()
super("New Email");
Container c=getContentPane();
c.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
c.setBackground(Color.lightGray);
//<MENU STUFF!!!>
mb = new JMenuBar();
File = new JMenu("File");
Edit = new JMenu("Edit");
New = new JMenuItem("New");
Sender = new JMenuItem("Save");
Copy = new JMenuItem("Copy");
Paste = new JMenuItem("Paste");
File.add(New);
New.addActionListener(this);
New.setActionCommand("1");
File.add(Sender);
Sender.addActionListener(this);
Sender.setActionCommand("2");
Edit.add(Copy);
Copy.addActionListener(this);
Copy.setActionCommand("3");
Edit.add(Paste);
Paste.addActionListener(this);
Paste.setActionCommand("4");
mb.add(File);
mb.add(Edit);
setJMenuBar(mb);
//</MENU STUFF!!!>
toLabel = new JLabel("To: ");
c.add(toLabel);
To = new JTextField(35);
c.add(To);
fromLabel = new JLabel("From: ");
c.add(fromLabel);
From = new JTextField(35);
c.add(From);
subjectLabel = new JLabel("Subject:");
c.add(subjectLabel);
Subject = new JTextField(35);
c.add(Subject);
Body = new JTextArea(12,40);
c.add(Body);
send = new JButton("Send");
c.add(send);
clear = new JButton("Clear");
c.add(clear);
clear.addActionListener(this);
clear.setActionCommand("6");
this.setSize(459, 364);
public static void main(String []args)
JFrame.setDefaultLookAndFeelDecorated(true);
new newmail().show();
public void actionPerformed(ActionEvent e)
String s = e.getActionCommand();
if (s == ("1"))
new newmail().show();
else if (s == ("2"))
new where().show();
toFile = To.getText();
fromFile = From.getText();
subjectFile = Subject.getText();
bodyFile = Body.getText();
else if (s == ("3"))
bodyBuffer = Body.getSelectedText();
toBuffer = To.getSelectedText();
fromBuffer = From.getSelectedText();
subjectBuffer = Subject.getSelectedText();
else if (s == ("4"))
Body.setText(bodyBuffer);
To.setText(toBuffer);
From.setText(fromBuffer);
Subject.setText(subjectBuffer);
else if (s == ("5"))
new about().show();
else if (s == ("6"))
To.setText("");
From.setText("");
Subject.setText("");
Body.setText("");
public class zimmernorm extends JFrame implements ActionListener
public String toFile, fromFile, subjectFile, bodyFile;
private String toBuffer, fromBuffer, subjectBuffer, bodyBuffer;
private JMenuBar mb;
private JMenu File, Help, View;
private JMenuItem New, About, Inboxmenu, Outboxmenu, Savedmenu;
public zimmernorm()
super("Zimmerman M3");
Container c=getContentPane();
c.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
c.setBackground(Color.lightGray);
//<MENU STUFF!!!>
mb = new JMenuBar();
File = new JMenu("File");
View = new JMenu("View");
Help = new JMenu("Help");
New = new JMenuItem("New");
About = new JMenuItem("About");
Inboxmenu = new JMenuItem("Inbox");
Outboxmenu = new JMenuItem("Outbox");
Savedmenu = new JMenuItem("Saved");
File.add(New);
New.addActionListener(this);
New.setActionCommand("1");
Help.add(About);
About.addActionListener(this);
About.setActionCommand("5");
View.add(Inboxmenu);
Inboxmenu.addActionListener(this);
Inboxmenu.setActionCommand("7");
View.add(Outboxmenu);
Outboxmenu.addActionListener(this);
Outboxmenu.setActionCommand("8");
View.add(Savedmenu);
Savedmenu.addActionListener(this);
Savedmenu.setActionCommand("9");
mb.add(File);
mb.add(Help);
mb.add(View);
setJMenuBar(mb);
//</MENU STUFF!!!>
this.setSize(1024, 768);
this.setDefaultCloseOperation( EXIT_ON_CLOSE );
public static void main(String []args)
JFrame.setDefaultLookAndFeelDecorated(true);
new zimmernorm().show();
public void actionPerformed(ActionEvent e)
String s = e.getActionCommand();
if (s == ("1"))
new newmail().show();
else if (s == ("5"))
new about().show(); -
Accessing an Array List from another class
Hi, I was a member on here before, but I forgot my password and my security question is wrong.
My question is how do I access a private arraylist from a different class in the same package?
What I am trying to do is the following (hard to explain).
Make a picking client for a shop, so that when an order is recieved, the picker can click on the orders button, and view all of the current orders that have not been completed. This Pick client has its own user interface, in a seperate class from where the BoughtList array is created, in the cashier client. The boughtlist is created when the cashier puts in the product number into the cashier client and clicks buy. I seem to be having trouble accessing the list from another class. Once the order is completed the cashier clicks bought and the list is reset. There is another class in a different pagage that processes some of the functions of the order, eg newOrder().
Yes it is for Uni so I dont need / want the full answers, jist something to get started. Also please dont flame me, I have done many other parts of this project, just having trouble getting started on this one.
Here is the code for the cashier client. The code for the Pick client is almost the same, I just need to make the code that displays the orders.
package Clients;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.NumberFormat;
import java.util.Locale;
import Catalogue.*;
import DBAccess.*;
import Processing.*;
import Middle.*;
class CashierGUI
class STATE // Cashier states
public static final int PROCESS = 0;
public static final int CHECKED = 1;
class NAME // Names of buttons
public static final String CHECK = "Check";
public static final String BUY = "Buy";
public static final String CANCEL = "Cancel";
public static final String BOUGHT = "Bought";
private static final int H = 300; // Height of window pixels
private static final int W = 400; // Width of window pixels
private JLabel theAction = new JLabel();
private JTextField theInput = new JTextField();
private JTextArea theOutput = new JTextArea();
private JScrollPane theSP = new JScrollPane();
private JButton theBtCheck = new JButton( NAME.CHECK );
private JButton theBtBuy = new JButton( NAME.BUY );
private JButton theBtCancel= new JButton( NAME.CANCEL );
private JButton theBtBought= new JButton( NAME.BOUGHT );
private int theState = STATE.PROCESS; // Current state
private Product theProduct = null; // Current product
private BoughtList theBought = null; // Bought items
private Transaction theCB = new Transaction();
private StockReadWriter theStock = null;
private OrderProcessing theOrder = null;
private NumberFormat theMoney =
NumberFormat.getCurrencyInstance( Locale.UK );
public CashierGUI( RootPaneContainer rpc, MiddleFactory mf )
try //
theStock = mf.getNewStockReadWriter(); // DataBase access
theOrder = mf.getNewOrderProcessing(); // Process order
} catch ( Exception e )
System.out.println("Exception: " + e.getMessage() );
Container cp = rpc.getContentPane(); // Content Pane
Container rootWindow = (Container) rpc; // Root Window
cp.setLayout(null); // No layout manager
rootWindow.setSize( W, H ); // Size of Window
Font f = new Font("Monospaced",Font.PLAIN,12); // Font f is
theBtCheck.setBounds( 16, 25+60*0, 80, 40 ); // Check Button
theBtCheck.addActionListener( theCB ); // Listener
cp.add( theBtCheck ); // Add to canvas
theBtBuy.setBounds( 16, 25+60*1, 80, 40 ); // Buy button
theBtBuy.addActionListener( theCB ); // Listener
cp.add( theBtBuy ); // Add to canvas
theBtCancel.setBounds( 16, 25+60*2, 80, 40 ); // Cancel Button
theBtCancel.addActionListener( theCB ); // Listener
cp.add( theBtCancel ); // Add to canvas
theBtBought.setBounds( 16, 25+60*3, 80, 40 ); // Clear Button
theBtBought.addActionListener( theCB ); // Listener
cp.add( theBtBought ); // Add to canvas
theAction.setBounds( 110, 25 , 270, 20 ); // Message area
theAction.setText( "" ); // Blank
cp.add( theAction ); // Add to canvas
theInput.setBounds( 110, 50, 270, 40 ); // Input Area
theInput.setText(""); // Blank
cp.add( theInput ); // Add to canvas
theSP.setBounds( 110, 100, 270, 160 ); // Scrolling pane
theOutput.setText( "" ); // Blank
theOutput.setFont( f ); // Uses font
cp.add( theSP ); // Add to canvas
theSP.getViewport().add( theOutput ); // In TextArea
rootWindow.setVisible( true ); // Make visible
class Transaction implements ActionListener // Listener
public void actionPerformed( ActionEvent ae ) // Interaction
if ( theStock == null )
theAction.setText("No conection");
return; // No connection
String actionIs = ae.getActionCommand(); // Button
try
if ( theBought == null )
int on = theOrder.uniqueNumber(); // Unique order no.
theBought = new BoughtList( on ); // Bought list
if ( actionIs.equals( NAME.CHECK ) ) // Button CHECK
theState = STATE.PROCESS; // State process
String pn = theInput.getText().trim(); // Product no.
int amount = 1; // & quantity
if ( theStock.exists( pn ) ) // Stock Exists?
{ // T
Product pr = theStock.getDetails(pn); // Get details
if ( pr.getQuantity() >= amount ) // In stock?
{ // T
theAction.setText( // Display
pr.getDescription() + " : " + // description
theMoney.format(pr.getPrice()) + // price
" (" + pr.getQuantity() + ")" // quantity
); // of product
theProduct = pr; // Remember prod.
theProduct.setQuantity( amount ); // & quantity
theState = STATE.CHECKED; // OK await BUY
} else { // F
theAction.setText( // Not in Stock
pr.getDescription() +" not in stock"
} else { // F Stock exists
theAction.setText( // Unknown
"Unknown product number " + pn // product no.
if ( actionIs.equals( NAME.BUY ) ) // Button BUY
if ( theState != STATE.CHECKED ) // Not checked
{ // with customer
theAction.setText("Check if OK with customer first");
return;
boolean stockBought = // Buy
theStock.buyStock( // however
theProduct.getProductNo(), // may fail
theProduct.getQuantity() ); //
if ( stockBought ) // Stock bought
{ // T
theBought.add( theProduct ); // Add to bought
theOutput.setText( "" ); // clear
theOutput.append( theBought.details()); // Display
theAction.setText("Purchased " + // details
theProduct.getDescription()); //
// theInput.setText( "" );
} else { // F
theAction.setText("!!! Not in stock"); // Now no stock
theState = STATE.PROCESS; // All Done
if ( actionIs.equals( NAME.CANCEL ) ) // Button CANCEL
if ( theBought.number() >= 1 ) // item to cancel
{ // T
Product dt = theBought.remove(); // Remove from list
theStock.addStock( dt.getProductNo(), // Re-stock
dt.getQuantity() ); // as not sold
theAction.setText(""); //
theOutput.setText(theBought.details()); // display sales
} else { // F
theOutput.setText( "" ); // Clear
theState = STATE.PROCESS;
if ( actionIs.equals( NAME.BOUGHT ) ) // Button Bought
if ( theBought.number() >= 1 ) // items > 1
{ // T
theOrder.newOrder( theBought ); // Process order
theBought = null; // reset
theOutput.setText( "" ); // Clear
theInput.setText( "" ); //
theAction.setText( "Next customer" ); // New Customer
theState = STATE.PROCESS; // All Done
theInput.requestFocus(); // theInput has Focus
catch ( StockException e ) // Error
{ // Of course
theOutput.append( "Fail Stock access:" + // Should not
e.getMessage() + "\n" ); // happen
catch ( OrderException e ) // Error
{ // Of course
theOutput.append( "Fail Order process:" + // Should not
e.getMessage() + "\n" ); // happen
}(disclaimer: I did not read through your Swing code, as I find that painful)
My question is how do I access a private arraylist from a different class in the same
package?Provide a public accessor method (getMyPrivateArrayList()) -
Is it possible to call methods from another class from within an abstract c
Is it possible to call methods from another class from within an abstract class ?
I found an example in teh JDK 131 JFC that may help you. I t is using swing interface and JTable
If you can not use Swing, then you may want to do digging or try out with the idea presented here in example 3
Notice that one should refine the abstract table model and you may want to create a method for something like
public Object getValuesAtRow(int row) { return data[row;}
to give the desired row and leave the method for
getValuesAt alone for getting valued of particaular row and column.
So Once you got the seelcted row index, idxSelctd, from your table
you can get the row or set the row in your table model
public TableExample3() {
JFrame frame = new JFrame("Table");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}});
// Take the dummy data from SwingSet.
final String[] names = {"First Name", "Last Name", "Favorite Color",
"Favorite Number", "Vegetarian"};
final Object[][] data = {
{"Mark", "Andrews", "Red", new Integer(2), new Boolean(true)},
{"Tom", "Ball", "Blue", new Integer(99), new Boolean(false)},
{"Alan", "Chung", "Green", new Integer(838), new Boolean(false)},
{"Jeff", "Dinkins", "Turquois", new Integer(8), new Boolean(true)},
{"Amy", "Fowler", "Yellow", new Integer(3), new Boolean(false)},
{"Brian", "Gerhold", "Green", new Integer(0), new Boolean(false)},
{"James", "Gosling", "Pink", new Integer(21), new Boolean(false)},
{"David", "Karlton", "Red", new Integer(1), new Boolean(false)},
{"Dave", "Kloba", "Yellow", new Integer(14), new Boolean(false)},
{"Peter", "Korn", "Purple", new Integer(12), new Boolean(false)},
{"Phil", "Milne", "Purple", new Integer(3), new Boolean(false)},
{"Dave", "Moore", "Green", new Integer(88), new Boolean(false)},
{"Hans", "Muller", "Maroon", new Integer(5), new Boolean(false)},
{"Rick", "Levenson", "Blue", new Integer(2), new Boolean(false)},
{"Tim", "Prinzing", "Blue", new Integer(22), new Boolean(false)},
{"Chester", "Rose", "Black", new Integer(0), new Boolean(false)},
{"Ray", "Ryan", "Gray", new Integer(77), new Boolean(false)},
{"Georges", "Saab", "Red", new Integer(4), new Boolean(false)},
{"Willie", "Walker", "Phthalo Blue", new Integer(4), new Boolean(false)},
{"Kathy", "Walrath", "Blue", new Integer(8), new Boolean(false)},
{"Arnaud", "Weber", "Green", new Integer(44), new Boolean(false)}
// Create a model of the data.
TableModel dataModel = new AbstractTableModel() {
// These methods always need to be implemented.
public int getColumnCount() { return names.length; }
public int getRowCount() { return data.length;}
public Object getValueAt(int row, int col) {return data[row][col];}
// The default implementations of these methods in
// AbstractTableModel would work, but we can refine them.
public String getColumnName(int column) {return names[column];}
public Class getColumnClass(int col) {return getValueAt(0,col).getClass();}
public boolean isCellEditable(int row, int col) {return (col==4);}
public void setValueAt(Object aValue, int row, int column) {
data[row][column] = aValue;
}; -
Using a class that has a main from another class
Can I call a class that has a main from another classes public methods?
Yes, you can, although strictly speaking you won't be calling that classes "main" method, you will simply be calling and initializing the class through it's constructor, the "main" method will be ignored. If you have code inside your main method that you want executed as well consider moving it inside your constructor and simply using the "main" method as an application initializer:
public static void main( String args[] ) {
new MyClass();
This way you can use your class as an application or call it from another class and not have any duplicate code inside your "main" method and constructor. You can also take this further and have it call the applet initialization so that you can launch it any way you like, I suspect this is a bit beyond what you were asking.
Does this solve your problem? -
I have a class Score and in that lcass I have the following method:
* Draw the score to the applet windows
* @param g The graphics object
public void draw(Graphics g, int x, int y)
calculateScore();
String stringScore = new Integer(usersScore).toString();
g.drawString(stringScore, x, y);
In my Applet class, Driver, I have a global graphics object:
Graphics gObject;
I initialize it in the paint method by sayingpublic void paint(Graphics g)
gObject = g;
But, inside the Applet when I call the method draw it doesn't work.
Then I tried
gObject = getGraphics(0But that didn't work either.
Is it possible to draw to an applet from another class?
Thanks.I just read one of you other postings on a similiar topic. In that thread everybody is assuming you are using Swing and are giving suggestions based on that assumption.
In this thread it appears you are using AWT so I gave suggestions based on that assumption.
It would be nice if you actually asked a clear question and stated what you are doing so people don't waste time guessing what the heck you are trying to do.
Thats one reason why I always ask for demo code. So we don't waste time guessing.
If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting. -
How to call a method from another class
I have a problem were i have to call a method from another class. What is the command line that i have to use. Thanks.
Here's one I wipped up in 10 minutes... Cool!
package forums;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import krc.utilz.io.Filez;
import java.io.FileNotFoundException;
class FileDisplayer extends JFrame
private static final long serialVersionUID = 0L;
FileDisplayer(String filename) {
super(filename);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(600, 800);
JTextArea text = new JTextArea();
try {
text.setText(Filez.read(filename));
} catch (FileNotFoundException e) {
text.setText(e.toString());
this.add(text);
public static void main(String args[]) {
final String filename = (args.length>0 ? args[0] : "C:/Java/home/src/forums/FileDisplayer.java");
try {
java.awt.EventQueue.invokeLater(
new Runnable() {
public void run() {
new FileDisplayer(filename).setVisible(true);
} catch (Exception e) {
e.printStackTrace();
Filez.read
* reads the given file into one big string
* @param String filename - the name of the file to read
* @return the contents filename
public static String read(String filename) throws FileNotFoundException {
return Filez.read(new FileReader(filename));
* Reads the contents of the given reader into one big string, and closes the reader.
* @param java.io.Reader reader - a subclass of Reader to read from.
* @return the whole contents of the given reader.
public static String read(Reader in) {
try {
StringBuffer out = new StringBuffer();
try {
char[] bfr = new char[BFRSIZE];
int n = 0;
while( (n=in.read(bfr,0,BFRSIZE)) > 0 ) {
out.append(bfr,0,n);
} finally {
if(in!=null)in.close();
return out.toString();
} catch (IOException e) {
throw new RuntimeIOException(e.getMessage(), e);
}Edited by: corlettk on Dec 16, 2007 1:01 PM - dang [code [/tags][ -
Running a main Method from another class??
Hi,
I am trying to run a main method from another class, eg the main method is in Class1 and i am trying to run it from class2.
So I have
class1 c1 = new class1();
c1.main();and I get the following compilation error:
clas2.java:42: main(java.lang.String[]) in class1 cannot be applied to () c1.main();
any ideas on how to do this correctly
thanks in advance,
DonalHi thanks for the replies,
tried just passing a string earlier and that just gave errors too, I should have been more specific and pass a string array.
Its working now thanks again.
Donal -
.How to instantiate the innerclass from another class with coded eg.
How to instantiate the innerclass from another class(both for static & non static) please give me an eg with coding.
It's just a preference, but I like writing factory methods:
public class Outer {
public class Inner {}
public static class StaticInner {}
public Inner innerInstance() {
return new Inner();
public static StaticInner staticInnerInstance() {
return new StaticInner();
public static void main(String[] args) {
Outer.StaticInner si = Outer.staticInnerInstance();
Outer outer = new Outer();
Outer.Inner i = outer.innerInstance();
}Often, for me, the inner class implements an interface, and the factory method
lets you hide the implementation class:
public class Outer {
private class Inner implements Runnable {
public void run() {}
public Runnable runnerInstance() {
return new Inner();
public static void main(String[] args) {
Outer outer = new Outer();
Runnable r = outer.runnerInstance();
} -
Instantiating an Array declared in a class from another class
Hi Guys,
I am working on a project for University and I'm stuck with this thins, which I'm sure is pretty easy when you know how...
I have a first class "Courses" in which I declare my Array, here is the code:
import java.util.*;
public class Courses
private String[][] Listing;
Courses(String[][] l)
l = Listing;
}This class compiles just fine but I have 2 problems:
1/ Can I make sure that this array will be [3][4] ?
When I try : "private String[3][4] Listing;" or "Courses(String[3][4] l)" the class doesn't compile anymore...
FYI: I want to store the followings in my array:
French Language, 250, 130, 70
Painting, 270, 140, 70
Yoga, 250, 130, 70
2/ How can I instantiate this from another class?
From a class "Booking" I want to be able to create a new array "Listing" by calling my constructor from the Courses class and populate it with the above data (course,full-time price, part-time price, Concessions price )
How do I do that?Thanks, I've modofied my code as follows:
import java.util.*;
public class Courses
private String[][] Listing = new String[3][4]; //create array 3 rows * 4 columns
Courses(String[][] l)
l = Listing;
int i;
int j;
int p;
String t;
String p1;
String getTitle(int i) //return Course Title
t=Listing[0];
return t;
int getPrice(int i, int j) //return Price (Full-Time, Part-Time, Concessions)
p1=Listing[i][j];
p=Integer.parseInt(p1);
return p;
now from my nex class Booking I want to instantiate Courses:
public class Booking
Courses c = new Courses()
}How do I actually pass the data to this...what's the syntax so that my instance will be:
c[0][0]="French Language"
c[0][1]="250"
c[0][2]="130"
c[0][3]="70"
c[1][0]="Painting"
c[1][1]="270"
c[1][2]="140"
c[1][3]="70"
c[2][0]="Yoga"
c[2][1]="250"
c[2][2]="130"
c[2][3]="70"
Thanks in advance,
Tom -
How can I to control any element of my GUI from another class?
How can I to control any element of my GUI from another class?
For that, you need the external class to have the reference to your element.. If your idea is to change basic properties like width, height etc.. then you can have the constructor of the external class to take the object of the parent of your class as the parameter and modify ..
However, if the properties to be altered/accessed are custom to your element, then you will have to have the class accept an object of your class as the parameter. No other option..
What exactly is your requirement? -
How Do I Run A Class From Another Class?
Hiya everyone, id like to know how to run a class from another class.
Ive got a Login class which extends a JFrame and a Personnel class which also extends a JFrame. When i press the login button (in Login class), ive got it to decide if password/login are acceptable and if they are, I want the Login class to close then run the Personnel class.
Im just after the code which says to close this class and run the Personnel class. How do i do that?
Ive researched this but couldnt get an understandable answer!
Help would be much appreciated, Ant...This is the Login Class:
public class MainMenu extends javax.swing.JFrame {
Statement statement = null;
int currentRecord;
ResultSet rs = null;
String name = null, job = null, mission = null, login = null, password = null;
String loginVal;
String passwordVal;
/** Creates new form MainMenu */
public MainMenu() {
initComponents();
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String filename = System.getProperty("user.dir") + "/src/Personnel.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + filename;
Connection conn = DriverManager.getConnection( database , "","");
statement = conn.createStatement();
System.out.println("Connected...ok");
} catch (Exception e) {
System.err.println("Got a connection Problem!");
System.err.println(e.getMessage());
private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {
loginVal = txtLogin.getText();
passwordVal = txtPassword.getText();
String name = null, job = null, mission = null, login = null, password = null;
try{
rs = statement.executeQuery("SELECT Login,Password FROM Personnel WHERE Login = '" + loginVal + "' ");
System.out.println("TRYING SELECT CLAUSE");
if(rs.next()){
System.out.println("THERE IS A NEXT RECORD");
login = rs.getString(1);
password = rs.getString(2);
System.out.println("GOT THE NEXT RECORD");
System.out.println(login + password);
System.out.println("Query Complete");
}catch(Exception s){
//s.printStackTrace();
System.out.println("NO RECORDS EXIST FOR THIS LOGIN ID");
if(passwordVal.equals(password)){
System.out.println("Access Granted"); //CLOSE MAIN AND RUN CONTROL CLASS
} else{
System.out.println("Access Denied"); //RE-RUN CLASS
}
Maybe you are looking for
-
I logged on to my computer today and I have no I-photo application. the icon is still present at the bottom of the screen but nothing opens. I used finder to open applications and were I-photo used to be is now a blank space. When I looked in the pic
-
Error serializing non-built in data type
hi I am getting the following exception while accessing a webservice which uses non-built-in data types as parameter to the service method Its called ProcessingOrderTO. The ProcessingOrderTO has three sub-types.. one of which is a Collection Does any
-
I receiving an error message (49) when I download the update for Photoshop CC. The mesage told to contact the assitance
-
Hohe Prozessorauslastung in PS CS5
Hallo Zusammen! Folgendes Problem macht mir in PS CS5 (64bit) zu schaffen: Die Prozessorauslastung beim Filter Tiefen/Lichter steigt ins unermessliche (1 Kern: ca. 97%, die anderen drei bei ca. 70-80%) - selbst bei einem 50MB "kleinen" Bild. Deswe
-
How to uninstall iFamebook from Facebook?
I installed iFamebook on my Facebook account and now I am getting popup adds that I never got before. Do you know how I can uninstall iFamebook? Or can you direct me to the right place to find this information?