Using HashMaps from another class
I'm trying to use a HashMap to store a person with a given Id. When i create a HashMap as part of a main method and use the put method on that HashMap everything goes fine ie:
Map myMap = new HashMap();
Person james = new Person)("James", "Smith");
myMap.put(1,james);However, when I use a HashMap as part of one class and attempt to call it in another using a simple add method I get a null pointer exception. For example, I have the class People which is basically:
import java.util.*;
public class People
private Map myPeople;
public People()
Map myPeople = new HashMap();
public void addPerson(int id, Person p)
PeopleTable.put(id,p);
}I then make a call to this using a separate main method
Person james = new Person ("James","Smith");
People myFamily = new myFamily();
myFamily.addPerson(1,james);but get a null pointer exception. I can't see anything glaringly obvious that i'm getting wrong, but i've just started using HashMaps so I may be missing something.
Any insight would be greatly appreciated!
Thanks,
Nick
nickd_101 wrote:
However, when I use a HashMap as part of one class and attempt to call it in another using a simple add method I get a null pointer exception. For example, I have the class People which is basically:
import java.util.*;
public class People
private Map myPeople;
public People()
Map myPeople = new HashMap(); //*** You're declaring the map again here, don't do this.
public void addPerson(int id, Person p)
PeopleTable.put(id,p);
You're declaring the map twice, once at the top of the class, which is good, and once again in the constructor, which is very bad since the class's hashmap never gets constructed. Don't do this.
The constructor should be:
public People()
myPeople = new HashMap(); // ** better
}
Similar Messages
-
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? -
Use a method from another class in another package?
How can I use a method from another class in another package?
WhiteJ wrote:
What do you mean by "new keyword?" You posted this previously:
I tried that, it seems to not be working. I want to use the constructor from the other class. I imported it, using this piece of code:
import components.FileChooser;
components.FileChoser();
Typically if I am going to call a constructor on a class called Fubar, I'd use new to create a new object:
Fubar myFubar = new Fubar();Incidently, is it a simple typo in your post or are you trying to use a FileChoser object when it should be FileChooser? -
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);
} -
Getting a variable value from another class
Is there any way to get the value of a variable from another class? I have a file that calls another that does some checking then gives a true or false. The place the checking is done is inside an ActionListener I want to use that value in the file that calls the second. Any help would be great.
in 'another class', implement a method,
public boolean isCheckedOutOK( Object obj )
do the comparison in that method (use a suitable argument) -
Accessing a variable defined in one class from another class..
Greetings,
I've only been programming in as3 for a couple months, and so far I've written several compositional classes that take MovieClips as inputs to handle behaviors and interactions in a simple game I'm creating. One problem I keep coming upon is that I'd love to access the custom variables I define within one class from another class. In the game I'm creating, Main.as is my document class, from which I invoke a class called 'Level1.as' which invokes all the other classes I've written.
Below I've pasted my class 'DieLikeThePhishes'. For example, I would love to know the syntax for accessing the boolean variable 'phish1BeenHit' (line 31) from another class. I've tried the dot syntax you would use to access a MovieClip inside another MovieClip and it doesn't seem to be working for me. Any ideas would be appreciated. Thanks,
- Jeremy
package jab.enemy
import flash.display.MovieClip;
import flash.events.Event;
import jab.enemy.MissleDisappear;
public class DieLikeThePhishes
private var _clip2:MovieClip; // player
private var _clip3:MovieClip; //phish1
private var _clip4:MovieClip; //phish2
private var _clip5:MovieClip; //phish3
private var _clip6:MovieClip; //phish4
private var _clip10:MovieClip; // background
private var _clip11:MovieClip // missle1
private var _clip12:MovieClip // missle2
private var _clip13:MovieClip // missle3
private var _clip14:MovieClip // missle4
private var _clip15:MovieClip // missle5
private var _clip16:MovieClip // missle6
private var _clip17:MovieClip // missle7
private var _clip18:MovieClip // missle8
private var _clip19:MovieClip // missle9
private var _clip20:MovieClip // missle10
private var _clip21:MovieClip // missle11
private var _clip22:MovieClip // missle12
var ay1 = 0;var ay2 = 0;var ay3 = 0;var ay4 = 0;
var vy1 = 0;var vy2 = 0;var vy3 = 0;var vy4 = 0;
var phish1BeenHit:Boolean = false;var phish2BeenHit:Boolean = false;
var phish3BeenHit:Boolean = false;var phish4BeenHit:Boolean = false;
public function DieLikeThePhishes(clip2:MovieClip,clip3:MovieClip,clip4:MovieClip,clip5:MovieClip,clip6:M ovieClip,clip10:MovieClip,clip11:MovieClip,clip12:MovieClip,clip13:MovieClip,clip14:MovieC lip,clip15:MovieClip,clip16:MovieClip,clip17:MovieClip,clip18:MovieClip,clip19:MovieClip,c lip20:MovieClip,clip21:MovieClip,clip22:MovieClip)
_clip2 = clip2;_clip3 = clip3;_clip4 = clip4;_clip5 = clip5;_clip6 = clip6;
_clip10 = clip10;_clip11 = clip11;_clip12 = clip12;_clip13 = clip13;_clip14 = clip14;
_clip15 = clip15;_clip16 = clip16;_clip17 = clip17;_clip18 = clip18;_clip19 = clip19;
_clip20 = clip20;_clip21 = clip21;_clip22= clip22;
_clip3.stage.addEventListener(Event.ENTER_FRAME, onEnterFrame)
function onEnterFrame(event:Event):void
vy1+= ay1;_clip3.y += vy1; vy2+= ay2;_clip4.y += vy2;
vy3+= ay3;_clip5.y += vy3; vy4+= ay4;_clip6.y += vy4;
if (phish1BeenHit ==false)
if(_clip3.y >620)
{_clip3.y = 620;}
if (phish2BeenHit ==false)
if(_clip4.y >620)
{_clip4.y = 620;}
if (phish3BeenHit ==false)
if(_clip5.y >620)
{_clip5.y = 620;}
if (phish4BeenHit ==false)
if(_clip6.y >620)
{_clip6.y = 620;}
if (_clip11.hitTestObject(_clip3) ||_clip12.hitTestObject(_clip3)||_clip13.hitTestObject(_clip3)||_clip14.hitTestObject(_cl ip3)||_clip15.hitTestObject(_clip3)||_clip16.hitTestObject(_clip3)||_clip17.hitTestObject( _clip3)||_clip18.hitTestObject(_clip3)||_clip19.hitTestObject(_clip3)||_clip20.hitTestObje ct(_clip3)||_clip21.hitTestObject(_clip3)||_clip22.hitTestObject(_clip3))
_clip3.scaleY = -Math.abs(_clip3.scaleY);
_clip3.alpha = 0.4;
ay1 = 3
vy1= -2;
phish1BeenHit = true;
if (_clip11.hitTestObject(_clip4) ||_clip12.hitTestObject(_clip4)||_clip13.hitTestObject(_clip4)||_clip14.hitTestObject(_cl ip4)||_clip15.hitTestObject(_clip4)||_clip16.hitTestObject(_clip4)||_clip17.hitTestObject( _clip4)||_clip18.hitTestObject(_clip4)||_clip19.hitTestObject(_clip4)||_clip20.hitTestObje ct(_clip4)||_clip21.hitTestObject(_clip4)||_clip22.hitTestObject(_clip4))
_clip4.scaleY = -Math.abs(_clip4.scaleY);
_clip4.alpha = 0.4;
ay2 = 3
vy2= -2;
phish2BeenHit = true;
if (_clip11.hitTestObject(_clip5) ||_clip12.hitTestObject(_clip5)||_clip13.hitTestObject(_clip5)||_clip14.hitTestObject(_cl ip5)||_clip15.hitTestObject(_clip5)||_clip16.hitTestObject(_clip5)||_clip17.hitTestObject( _clip5)||_clip18.hitTestObject(_clip5)||_clip19.hitTestObject(_clip5)||_clip20.hitTestObje ct(_clip5)||_clip21.hitTestObject(_clip5)||_clip22.hitTestObject(_clip5))
_clip5.scaleY = -Math.abs(_clip5.scaleY);
_clip5.alpha = 0.4;
ay3 = 3
vy3= -2;
phish3BeenHit = true;
if (_clip11.hitTestObject(_clip6) ||_clip12.hitTestObject(_clip6)||_clip13.hitTestObject(_clip6)||_clip14.hitTestObject(_cl ip6)||_clip15.hitTestObject(_clip6)||_clip16.hitTestObject(_clip6)||_clip17.hitTestObject( _clip6)||_clip18.hitTestObject(_clip6)||_clip19.hitTestObject(_clip6)||_clip20.hitTestObje ct(_clip6)||_clip21.hitTestObject(_clip6)||_clip22.hitTestObject(_clip6))
_clip6.scaleY = -Math.abs(_clip6.scaleY);
_clip6.alpha = 0.4;
ay4 = 3
vy4= -2;
phish4BeenHit = true;
if (_clip3.y > 10000)
_clip3.x = 1000 +3000*Math.random()-_clip10.x;
_clip3.y = 300;
_clip3.alpha = 1;
_clip3.scaleY = Math.abs(_clip3.scaleY);
ay1 = vy1 = 0;
phish1BeenHit = false;
if (_clip4.y > 10000)
_clip4.x = 1000 +3000*Math.random()-_clip10.x;
_clip4.y = 300;
_clip4.alpha = 1;
_clip4.scaleY = Math.abs(_clip4.scaleY);
ay2 = vy2 = 0;
phish2BeenHit = false;
if (_clip5.y > 10000)
_clip5.x = 1000 +3000*Math.random()-_clip10.x;
_clip5.y = 300;
_clip5.alpha = 1;
_clip5.scaleY = Math.abs(_clip5.scaleY);
ay3 = vy3 = 0;
phish3BeenHit = false;
if (_clip6.y > 10000)
_clip6.x = 1000 +3000*Math.random()-_clip10.x;
_clip6.y = 300;
_clip6.alpha = 1;
_clip6.scaleY = Math.abs(_clip6.scaleY);
ay4 = vy4 = 0;
phish4BeenHit = false;
var missleDisappear1 = new MissleDisappear(_clip11,_clip3,_clip4,_clip5,_clip6,_clip10);
var missleDisappear2 = new MissleDisappear(_clip12,_clip3,_clip4,_clip5,_clip6,_clip10);
var missleDisappear3 = new MissleDisappear(_clip13,_clip3,_clip4,_clip5,_clip6,_clip10);
var missleDisappear4 = new MissleDisappear(_clip14,_clip3,_clip4,_clip5,_clip6,_clip10);
var missleDisappear5 = new MissleDisappear(_clip15,_clip3,_clip4,_clip5,_clip6,_clip10);
var missleDisappear6 = new MissleDisappear(_clip16,_clip3,_clip4,_clip5,_clip6,_clip10);
var missleDisappear7 = new MissleDisappear(_clip17,_clip3,_clip4,_clip5,_clip6,_clip10);
var missleDisappear8 = new MissleDisappear(_clip18,_clip3,_clip4,_clip5,_clip6,_clip10);
var missleDisappear9 = new MissleDisappear(_clip19,_clip3,_clip4,_clip5,_clip6,_clip10);
var missleDisappear10 = new MissleDisappear(_clip20,_clip3,_clip4,_clip5,_clip6,_clip10);
var missleDisappear11 = new MissleDisappear(_clip21,_clip3,_clip4,_clip5,_clip6,_clip10);
var missleDisappear12 = new MissleDisappear(_clip22,_clip3,_clip4,_clip5,_clip6,_clip10);I would approach it in much the same way as you would in java, by making getters and setters for all of your class variables.
Getters being for returning the values, Setters being for setting them.
So you would make a get function for the variable you want to access ala:
function get1PhishBeenHit():boolean {
return this.phish1BeenHit;
Then to access the value of that variable from outwith the class:
var result:boolean = ClassInstanceName.get1PhishBeenHit(); -
Can I invoke a class that extends JAppl from another class extends JAppl
Can I invoke a class that extends JApplet from another class that extends JApplet. I need to invoke an applet then select an action which opens another applet. Thanks in advance.
Nobody is able to solve this problem, i cant even
think this things. i have hope so plz try and get
result and help.Did you understand what Sharad has said???
Yep, you can forward to specific error page from servlet when even error occured in JSP. In order to achieve you have to open jsp file from servlet say example by using reqdisp.forward.
handle exception in the part where you are forwarding. And forward to the specific error page inside catch block. -
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;
}; -
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 do you call a method from another class without extending as a parent?
How do you call a method from another class without extending it as a parent? Is this possible?
Why don't you just create an instance of the class?
Car c = new Car();
c.drive("fast");The drive method is in the car class, but as long as the method is public, you can use it anywhere.
Is that what you were asking or am I totally misunderstanding your question?
Jen -
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][ -
How to kill one class from another class
I need to dipose one class from another class.
So that first i have to find what are all threads running in that class and then to kill them
Assist me.Subbu_Srinivasan wrote:
I am explaining you in clear way
No you haven't been.
>
In my application i am handling many JInternalFrame.Simultaneously i am running working on more than one frame.
Due to some poor performance of some thread in one JInternalFrame,the thread is keeps on running .
i could not able to proceed further on that screen.
So i have to kill that JInternalFrame.Yoinks.
To be begin with your problem sounds like you are doing everything in one thread. So stop doing that. Second when you get it split up and if a task is taking too much time then interrupt it. No kill. Interrupt. This means the worker thread needs to check sometimes if it has been interrupted. -
Calling a method from another class... that requires variables?
I'm calling a method from another class to change the date (its a date object) in another class.
I keep getting the error 'setDate(int,int,int) in Date cannot be applied to ()'
My code is:
public int changeDate()
cycleDate.setDate();
}I'm guessing I need to pass 3 parameters (day, month, year), but I'm not sure how! I have tried, but then I get errors such as ')' expected?
Any ideas! :Df1d wrote:
I'm calling a method from another class to change the date (its a date object) in another class.
I keep getting the error 'setDate(int,int,int) in Date cannot be applied to ()'
My code is:
public int changeDate()
cycleDate.setDate();
}I'm guessing I need to pass 3 parameters (day, month, year), seems that way from the error you posted
but I'm not sure how!
setDate(16, 6, 2008);
I have tried, but then I get errors such as ')' expected?
Any ideas! :Dyou need to post your code if you're getting specific errors like that.
but typically ')' expected means just that, you have too many or not enough parenthesis (or in the wrong place, etc.)
i.e. syntax error -
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;
}
Maybe you are looking for
-
Can't figure out beeps....HP pavillion p6110f
We have a HP Pavillion p6110f that is basically stock except for the addition of a 160 gb HD that i use for backups. Our problem is that upon start up (the first start up of the day only) that it beeps various codes, sometimes it 3 -1, then its ok, s
-
Hi! I need a help to use XMLTable instead of XMLSequence. This is the part of my XML. <emiDocAnt> <owner>11111111111111</owner> <idDocAnt> <idDocAntPap> <tpDoc>01</tpDoc> </
-
ICal - I have all the events from the past decade listed for this week
My iCal calendar has every event from the last ten years listed in every day - each event is tagged 'repeat Every day' and 'end Never'. I have a non-corrupted version on my iPhone. I have tried restoring from Time machine and this works but then reve
-
What is the diff? OI Mgmt, OI Mgr, OAM?
Hi, I'm new to FMW and confused by all the offerings. Can someone tell me in a few words what the difference is between these 3 technologies? - Oracle Identity Management - Oracle Identity Manager - Oracle Access Manager Based on what I see... - Orac
-
Assets Captalised with wrong cost center
Hi, I am facing one problem while capitalizing the asset it get capitalized with the wrong cost center and the depreciation is also get posted for two month. Now my problem is how to correct this entry as this is posted to wrong profit center. Is the