Public static void vs. public static int

hey java_experts,
we're learning arrays and i was just wondering whats the difference between public static void vs. public static int

hi i want to do java mail but i am new in this field
so please suggest me how i have to get help for the
java mailNext time start your own thread.
Google for Java mail tutorial.

Similar Messages

  • What is public static int??

    hi everybody,
    I am attending data structure and alogrithms class ...i wanna know about all, so which book can I read to understand.
    Also in java what is the meaning of
    "public static int"....
    it have got "return" what is the meaning it ??
    best regards
    blazer

    Perhaps you should try the Java forums and not the Sun Ray forum :)

  • How to javadoc "public final static int"?

    How can we create "Field Summary" HTML document for "public final static int" variables?
    This question is probably same as the below question.
    http://forums.java.sun.com/thread.jsp?forum=41&thread=72832
    p.s.
    The below document indicates CENTER, NORTH, ...
    How an we achieve it to document "public final static" variables?
    http://java.sun.com/products/jdk/1.2/docs/api/index.html

    No, 1.3 does not have the static constant values exposed to the Doclet API,
    and so that information is not available to any doclets to place in the
    generated documentation.
    BTW, based on feedback from a developer, we changed the format from:
    public static final int NORTH = 0
    to
    public static final int NORTH
    See: Constant values
    where the "Constant values" link takes them to a summary page that
    lists all of the values. This helps discourage users from mistakenly
    seeing and using the value instead of the constant.
    -Doug Kramer
    Javadoc team

  • Question about public void characters(char []ch, int start, int length) thr

    Can anyone tell me how you would keep all the characters from within one pair of tags together each time characters() is called?
    the character() method doesn't read all the character data at once, and i would like to create a buffer of what it has read.
    thank you.

    I recommend using getNodeName and/or/combination
    with
    getNodeValue to get the strings.i have tried using a buffer, and i have got that to work!
    At long last I am seeing the string I would like to see as it is in the xml file!
    thank you for your help
    here is an example of my code:
    private boolean isDescription = false;
    StringBuffer sb = new StringBuffer();
    public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
         if(localName.equals("description")) {
              sb = new StringBuffer();
              isDescription = true;
    public void characters(char []ch, int start, int length) throws SAXException {
         if(isDescription == true) {
              String desc = new String(ch, start, length);
              sb.append(desc);
    public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
         if(localName.equals("description")) {
              isDescription == false;
              System.out.println(sb.toString());
    }

  • Code standard for get/set or static int?

    What is the standard for getting setting values in a class?
    ie.
    static int VALUE = 0;
    String[] values = new String[1];
    public void set(int in, String val){
         values[in] = val;
    public String get(int in){
         return values[in];
    }OR
    String val1;
    String val2;
    public String getVal1(){
         return val1;
    public void setVal1(String in){
         val1 = in;

    I would say the first is Very Bad, and the second is Good. In-between is Bad, which would be storing everything in a Map, where at least the values are named rather than having an anonymous number to identify them.
    With that said, where I work we actually have a class that uses the Bad solution that I outlined, but it's designed to be exposed publicly by subclasses using the standard getter/setter idiom, and the map itself is not used externally. So instead of being backed by variables, all the getters and setters are backed by a Map. It ends up being Not So Bad. :-)

  • Array static int help

    static int[]      insert(int x, int i, int[] a)
    insert takes an item x, an index i, and an array a, and returns a new array containing all the elements of a with one additional element, namely x, at position i.
    ok im trying to add 2 ints to the array?
    and i dont understand what im doing wrong this is what i tried and it says error bc it needs an int in the return.
    its suppose to do this
    a = new int[3]; a[0] = 5; a[1] = 2; a[2] = 7;
    a.length3
    b = insert(-42, 1, a); // -42 is passed into x and 1 is passed into i
    b.length4
    b[1]-42
    b[2]2
    this is what i have written that is wrong...
    public static int[] insert(int newZ, int newX, int[] a){
    int totals = 1;
    int z = newZ;
    int x = newX;
    for (int i = 0; i < a.length; i++){
    totals = (a[i]+ z + x);
    return totals;
    }

    Hi,
    This forum is exclusively for discussions related to Sun Java Studio Creator. Please post your question at :
    http://forum.java.sun.com/forum.jspa?forumID=54
    Thanks,
    RK.

  • Static int

    Hello guys, I have this public static int ID = 1; in my main class. However, i wanted to increment it at a different class. That was why i declared it to public. And i really need it to be static.
    Here is the incrementation in a different class int x = Driver.ID;
    Driver.ID = x++;The problem now is the ID in the Driver class does not increase. Please explain and tell me a solution. Thank you.

    Just as a somewhat unrelated suggestion.
    It would be better if you made a public method in your driver class to increment your ID variable(which by the way is named wrong, as its name suggests it is final).
    This way you don't even have to declare it to public, you can leave it private or protected. It also makes your code overall much more easier to read and maintain. And last but certainly not least it makes your driver class more reuse friendly for any other classes that want to use it or increment ID in it, even in the future, without the necessity of removing any control you have over it.
    Anytime you want to change data in another class your thoughts should be "what does that class have to let me do that?" If the answer is nothing but you authored both classes, then before doing it the way you did, you should consider adding a method to the class with the data to allow the answer to be present the next time you ask it.
    Forcing data changes the way you did will eventually cause you headaches. So it is best to get into the right habbits now, rather than having to learn the hard way.
    JSG

  • How can i pass the values to method public static void showBoard(boolean[][

    I need x and y to pass to the method
    public static void showBoard(boolean[][] board
    i am very confused as to why its boolean,i know its an array but does that mean values ar true or false only?Thanks
    import java.util.Random;
    import java.util.Scanner;
    public class Life1
         public static void main(String[] args)
              int x=0;
              int y=0;
              Scanner keyIn = new Scanner(System.in);
              System.out.println("Enter the first dimension of the board : ");
              x = keyIn.nextInt();
              System.out.println("Enter the second dimension of the board : );
              y = keyIn.nextInt();
              boolean[][] board = new boolean[x][y];
              fillBoard(board);
              showBoard(board);
              //Ask the user how many generations to show.
              board = newBoard(board);
              showBoard(board);
         //This method randomly populates rows 5-9 of the board
         //Rewrite this method to allow the user to populate the board by entering the
         //coordinates of the live cells.  If the user requests that cell 1, 1 be alive,
         //your program should make cell 0,0 alive.
         public static void fillBoard(boolean[][] board)
              int row, col, isAlive;
              Random picker = new Random();
              for(row = 4; row < 9; row++)
                   for(col = 4; col < 9; col++)
                        if (picker.nextInt(2) == 0)
                          board[row][col] = false;
                        else
                          board[row][col] = true;
         //This method displays the board
         public static void showBoard(boolean[][] board)
              int row, col;
              System.out.println();
              for(row=0; row < x; row++)
                   for(col=0; col<y; col++)
                        if (board[row][col])
                             System.out.print("X");
                        else
                             System.out.print(".");
                   System.out.println();
              System.out.println();
         //This method creates the next generation and returns the new population
         public static boolean[][] newBoard(boolean[][] board)
              int row;
              int col;
              int neighbors;
              boolean[][] newBoard = new boolean[board.length][board[0].length];
              makeDead(newBoard);
              for(row = 1; row < board.length-1; row++)
                   for(col = 1; col < board[row].length-1; col++)
                        neighbors = countNeighbors(row, col, board);
                        //make this work with one less if
                        if (neighbors < 2)
                             newBoard[row][col]=false;
                        else if (neighbors > 3)
                             newBoard[row][col] = false;
                        else if (neighbors == 2)
                             newBoard[row][col]= board[row][col];
                        else
                             newBoard[row][col] = true;
              return newBoard;
         //This method counts the number of neighbors surrounding a cell.
         //It is given the current cell coordinates and the board
         public static int countNeighbors(int thisRow, int thisCol, boolean[][] board)
              int count = 0;
              int row, col;
              for (row = thisRow - 1; row < thisRow + 2; row++)
                   for(col = thisCol - 1; col < thisCol + 2; col++)
                     if (board[row][col])
                          count++;
              if (board[thisRow][thisCol])
                   count--;
              return count;
         //This method makes each cell in a board "dead."
         public static void makeDead(boolean[][] board)
              int row, col;
              for(row = 0; row < board.length; row++)
                   for(col = 0; col < board[row].length; col++)
                        board[row][col] = false;
    }

    this is what im workin with mabey you can point me in the right directionimport java.util.Random;
    /* This class creates an application to simulate John Conway's Life game.
    * Output is sent to the System.out object.
    * The rules for the Life game are as follows...
    * Your final version of the program should explain the game and its use
    * to the user.
    public class Life
         public static void main(String[] args)
              //Allow the user to specify the board size
              boolean[][] board = new boolean[10][10];
              fillBoard(board);
              showBoard(board);
              //Ask the user how many generations to show.
              board = newBoard(board);
              showBoard(board);
         //This method randomly populates rows 5-9 of the board
         //Rewrite this method to allow the user to populate the board by entering the
         //coordinates of the live cells.  If the user requests that cell 1, 1 be alive,
         //your program should make cell 0,0 alive.
         public static void fillBoard(boolean[][] board)
              int row, col, isAlive;
              Random picker = new Random();
              for(row = 4; row < 9; row++)
                   for(col = 4; col < 9; col++)
                        if (picker.nextInt(2) == 0)
                          board[row][col] = false;
                        else
                          board[row][col] = true;
         //This method displays the board
         public static void showBoard(boolean[][] board)
              int row, col;
              System.out.println();
              for(row=0; row < 10; row++)
                   for(col=0; col<10; col++)
                        if (board[row][col])
                             System.out.print("X");
                        else
                             System.out.print(".");
                   System.out.println();
              System.out.println();
         //This method creates the next generation and returns the new population
         public static boolean[][] newBoard(boolean[][] board)
              int row;
              int col;
              int neighbors;
              boolean[][] newBoard = new boolean[board.length][board[0].length];
              makeDead(newBoard);
              for(row = 1; row < board.length-1; row++)
                   for(col = 1; col < board[row].length-1; col++)
                        neighbors = countNeighbors(row, col, board);
                        //make this work with one less if
                        if (neighbors < 2)
                             newBoard[row][col]=false;
                        else if (neighbors > 3)
                             newBoard[row][col] = false;
                        else if (neighbors == 2)
                             newBoard[row][col]= board[row][col];
                        else
                             newBoard[row][col] = true;
              return newBoard;
         //This method counts the number of neighbors surrounding a cell.
         //It is given the current cell coordinates and the board
         public static int countNeighbors(int thisRow, int thisCol, boolean[][] board)
              int count = 0;
              int row, col;
              for (row = thisRow - 1; row < thisRow + 2; row++)
                   for(col = thisCol - 1; col < thisCol + 2; col++)
                     if (board[row][col])
                          count++;
              if (board[thisRow][thisCol])
                   count--;
              return count;
         //This method makes each cell in a board "dead."
         public static void makeDead(boolean[][] board)
              int row, col;
              for(row = 0; row < board.length; row++)
                   for(col = 0; col < board[row].length; col++)
                        board[row][col] = false;
    }

  • How can i change the class in the Class Library project to be static or public so i can use it from the windows application project ?

    First i know that when i make any changes to the class library project i need to rebuild the project then to remove the Capture.dll from the TestScreenshot project and then to add again the updated Capture.dll
    The problem for example in this case i'm trying to use a public static variable i add in the DXHookD3D9.
    In the DXHookD3D9 i added this public static variable:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    //using SlimDX.Direct3D9;
    using EasyHook;
    using System.Runtime.InteropServices;
    using System.IO;
    using System.Threading;
    using System.Drawing;
    using Capture.Interface;
    using SharpDX.Direct3D9;
    namespace Capture.Hook
    internal class DXHookD3D9: BaseDXHook
    public DXHookD3D9(CaptureInterface ssInterface)
    : base(ssInterface)
    LocalHook Direct3DDevice_EndSceneHook = null;
    LocalHook Direct3DDevice_ResetHook = null;
    LocalHook Direct3DDevice_PresentHook = null;
    LocalHook Direct3DDeviceEx_PresentExHook = null;
    object _lockRenderTarget = new object();
    Surface _renderTarget;
    public static decimal framesperhourtodisplay = 0;
    protected override string HookName
    get
    return "DXHookD3D9";
    List<IntPtr> id3dDeviceFunctionAddresses = new List<IntPtr>(
    framesperhourtodisplay
    The problem is i can't even get to the Capture.Hook namespace and not to the DXHookD3D9 from the TestScreenshot application window project.
    This is a screenshot:
    For example fro the FramesPerSecond class i can use it get to it from the windows forms application.
    namespace Capture.Hook
    /// <summary>
    /// Used to determine the FPS
    /// </summary>
    public class FramesPerSecond
    int _frames = 0;
    int _lastTickCount = 0;
    float _lastFrameRate = 0;
    Since it's public i guess.
    But if i will change the DXHookD3D9 class from internal to public:
    public class DXHookD3D9: BaseDXHook
    I will get error on the DXHookD3D9: 
    Error 1
    Inconsistent accessibility: base class 'Capture.Hook.BaseDXHook' is less accessible than class 'Capture.Hook.DXHookD3D9'
    And the BaseDXHook class:
    namespace Capture.Hook
    internal abstract class BaseDXHook: IDXHook
    protected readonly ClientCaptureInterfaceEventProxy InterfaceEventProxy = new ClientCaptureInterfaceEventProxy();
    public BaseDXHook(CaptureInterface ssInterface)
    this.Interface = ssInterface;
    this.Timer = new Stopwatch();
    this.Timer.Start();
    this.FPS = new FramesPerSecond();
    Interface.ScreenshotRequested += InterfaceEventProxy.ScreenshotRequestedProxyHandler;
    Interface.DisplayText += InterfaceEventProxy.DisplayTextProxyHandler;
    InterfaceEventProxy.ScreenshotRequested += new ScreenshotRequestedEvent(InterfaceEventProxy_ScreenshotRequested);
    InterfaceEventProxy.DisplayText += new DisplayTextEvent(InterfaceEventProxy_DisplayText);
    ~BaseDXHook()
    Dispose(false);
    How can i solve it so i can use the variable framesperhourtodisplay in the DXHookD3D9 class with the TestScreenshot windows forms application ?

    Hi,
    I dont know if it will work here, since I dont know the complete structure, but the base call must be public, if the derived class is public, so the base class is at least as accessible as the derived class.
    Try make the base class public. (And maybe the base-class IDXHook of the base also...)
    Or use a different approach and make only the properties public that are needed to be public by adding an extra class...
    A structure could look like:(you need to create a class thats public in your dll and expose a property, and set this property in the internal class...)
    In the Accessing class (here Form1)
    public partial class Form1 : Form
    public Form1()
    InitializeComponent();
    private void Form1_Load(object sender, EventArgs e)
    C c = new C();
    MessageBox.Show(B.F.ToString());
    and in the class Lib:
    internal class A
    public A()
    B.F = DateTime.Now.Millisecond;
    public class B
    public static int F { get; set; }
    public class C
    public C()
    A a = new A();
    (add a referenc to the class lib from the accessing project)
    Regards,
      Thorsten

  • Private,public and static variable

    I am just not able to understand the use of declaring the variable as private.Because even if i declare the variable as public ,other user of the same application anyway will never be acess that variable !! Can someone clear my doubt.
    Also can some one tell me when can I declare a variable as static...that is ideallly when should i declare a variable as static (and for that matter private and public )
    Thanks.
    Tha

    Hi,
    There are some rules for variable declarations:
    Only the containing class and its inner classes can access private variables.
    Every class can access public variables.
    All classes in the same package can access protected variables.
    Imagine you're writing a program for archiving all your CD's.
    If you want to know how many cd's you have got you simply read the static variable.
    public class CD {
    private String name, author;
    public static int cdCount = 0;
    public CD(String name, String author){
    //do something to initialize
    cdCount++; //Increase the value, because a new CD has been created.
    public static int getCDCount(){      //static methods can be accessed without creating instances of classes
    return cdCount;
    public static void main(String[] args){
    CD kravitz = new CD("Lenny Kravitz", "A Song");
    CD britney = new CD("Britney Spears", "Another Song");
    System.out.println("You have " CD.getCDCount() " CDs"); //You call static methods on the class (you can also call them on instances, but it is important that you do not need to create a object of that class)
    }

  • Discussion: private final static vs public final static

    take following class variable:public final static int constant = 1;Is there any harm in making this variable public if it's not used (and never will be) in any other class?
    Under the same assumption Is there any point in making this variable static?
    tx for your input

    Is there any harm in making this variablepublic
    if it's not used (and never will
    be) in any other class?Harm? No. Use? Neither.I suppose it makes no difference at all concerning
    runtime performance?
    Under the same assumption Is there any point inmaking this variable
    static?If the creation of the constant is costly, for
    instance. A logger is private final static most of
    the time.Same here, does making a variable final or static
    have any influence on runtime performance?No. And for 'expensive' operations (say, parsing a XML configuration file, which only needs to occur once), making a variable static will improve performance.
    - Saish

  • Public static vs private

    Hi
    I have 3 classes, A, B & C.
    I have one variable, var, that can be used in class B and C; I have declared it in class B, and passed when I create an istance of C in B.
    Then I need also to read its value in class A.
    Now the ways are two (I think ...):
    1. declare it as public static in class A and then use A.var in class B and C;
    2. declare it as private in A and then passed to B when I create in A an istance of B and to C then I create in B an istance to C.
    Considerations:
    a. I don't like to declare public variables, I think is a bad way to program,
    isn'it?
    b. the second way is a problem when I have 10 variables (the constructors have too many parameters), right?
    Could anyone help?

    The problem is I tryied to find these answer in
    Intenrnet, but I don't find anything.That's fine. That's why most of us are here.
    My application works as this:
    I have a main class (A) that have a main menu in
    console style; from this class I create a new client
    class (B) that receive commands from a server; if a
    command is valid, B create an istance of C that
    rappresents a trainer machine. In C I have all
    workout variables (time, incline, speed ...).
    By menu (in class A) i could pause the trainer and by
    A and/or remote server I could ask the state of the
    machine (C).
    In your explanation above, I draw your attention to "instance". You are making instances of your classes. That being the case, your variables should probably be instance variables
    NOT
    public static int firstVariable = 0;BUT
    protected int firstVariable = 0;You would then provide get and set methods to access the protected variable.
    If you find yourself writing B b = new B() then you know you are dealing with an instance and you should avoid all static variables unless you really do mean "this value is the same across all Bs".
    I have 8 state variables I could manage in that way.
    The only way I have for now found is definite a
    public static long vars in C (and use them in A e B
    as C.state, C.time, ...) to avoid to pass 8
    parameters when I create the istances from A to C.Assuming that C has eight variables and your design isn't done yet you can still pass an instance of C to the other objects. They don't need to have their method/constructor signatures changed when you add a new variable as your C object encapsulates it already.
    >
    Is right? Any other suggestion?Yes. Don't stick to "C.time" because that's what you've got so far. Instead, you should be using
    C c = new C();
    c.getTime();That way, the time variable is unique to the instance.

  • Public int move(CDRack anotherRack)

    I have problems with method: move(CDRack anotherRack).
    It removes CDs from anotherRack, but the rack I'm trying to fill in with anotherRack's CDs is filled with a one same CD from the anotherRack not various CDs as it should.. hard to explain.:)
    Is some willing to give me tips? And is there some other way
    to use insert method with the help of the move-method?
    /**Class CDRack represents collections of compact discs. Discs are
    located in the rack in slots numbered from zero upwards.The discs are
    represented by Record objects and empty slots by null values. */
    public class CDRack extends Object { 
      private Record[] collection;
    /**Creates a new, empty CD rack. Parameters:size - the size of the new
    rack, i.e. the number of slots it has */
        public CDRack(int size) {
           collection = new Record[size];   
           this.size = size;
    /**Inserts a cd in the given rack slot if the slot in question is
    empty. Parameters: disc - the cd to be added in the rackslot - the
    number of a (hopefully empty) slot
    Returns: a boolean value indicating if the insertion was successful.
        public boolean insert(Record disc, int slot) { 
           if (collection[slot]==null)) {    
             collection[slot] = record;    
             return true; 
           else return false; 
    /** Inserts the given cd in the first empty rack slot (if there is even
    one empty slot in the rack).
    Parameters: disc - the disc to be added in the rack
    Returns:
    the number of the slot where the disc was added, or a negative number
    if the rack was already full */
        public int insert(Record disc) {
           for(slot=0; slot<collection.length; slot++) {
             if(collection[slot]==null) {
                collection[slot] = disc;
                return slot;
           return -1; //not enough place
    /** Moves all the discs from the given cd rack to this rack. The cds
    from the other rack are inserted in the empty slots of this rack (in
    ascending numerical order of slot numbers) in the order in which they
    are located in the other rack. The moved discs are removed from their
    original rack. Even if there is not enough space for all the discs in
    this rack, as many cds are moved as possible.
    Parameters:
    anotherRack - another rack whose cds are to be moved into this one
    Returns:
    the number of cds moved from the other rack to this one */
        public int move(CDRack anotherRack) {
           int howMuchPlace = this.getSize() - this.getNumberOfCDs();
             if(anotherRack.getNumberOfCDs() <= howMuchPlace) {
                for(int i=0; i<anotherRack.getNumberOfCDs()+1; i++) {
                  this.insert(disc);
                for(slot=0; slot<anotherRack.getNumberOfCDs()+1; i++) {
                  anotherRack.remove(slot);
                return anotherRack.getNumberOfCDs();
            if(anotherRack.getNumberOfCDs() > howMuchPlace) {
                for(int i=0; i<howMuchPlace+1; i++) {
                  this.insert(disc);
                for(slot=0; slot<howMuchPlace+1; i++) {
                  anotherRack.remove(slot);
                return howMuchPlace;
             return -1;

    I'm about to leave the office (it's 7PM in London and
    there at least a dozen beers with my name on them ;)
    but I'll take a look on Monday and see how you got
    on.Sheesh. Must be Christmas or something :)
    You still need to implement organize() and sortAlphabetically(), plus move the classes to their own files and modify the parameter names to match the assignment.
    But, apart form that, here's what you wanted.
    Now, I realy am going to ge those beers...
    public class Maria2
         static class Record {}
         static class CDRack
              private Record[] mRecords;
              CDRack(int size) { mRecords= new Record[size]; }
              int find(Record disk)
                   for (int i= 0; i < mRecords.length; i++) {
                        if (mRecords.equals(disk))
                             return i;
                   return -1;
              Record getCD(int index)
                   if (index < 0 || index >= mRecords.length)
                        return null;
                   return mRecords[index];
              int getNumberOfCDs() { return getSize() -available(); }
              int getSize() { return mRecords.length; }
              int insert(Record record)
                   int index= 0;
                   for (; index < mRecords.length && mRecords[index] != null; index++);
                   if (insert(record, index))
                        return index;
                   return -1;
              boolean insert(Record record, int index)
                   if (index >= mRecords.length)
                        return false;
                   if (mRecords[index] != null)
                        return false;
                   mRecords[index]= record;
                   return true;
              private int available()
                   int available= 0;
                   for (int i= 0; i < mRecords.length; i++) {
                        if (mRecords[i] == null )
                             available++;
                   return available;
              Record remove(int index)
                   Record record= getCD(index);
                   mRecords[index]= null;
                   return record;
              int move(CDRack source)
                   int moved= 0;
                   for (int i= 0; i< source.getSize(); i++) {
                        Record record= source.getCD(i);
                        if (record == null)
                             continue;
                        if (insert(record) < 0)
                             break;
                        source.remove(i);
                        moved++;
                   return moved;
         public static void main(String[] argv)
              CDRack rack1= new CDRack(32);
              CDRack rack2= new CDRack(18);
              for (int i= 0; i< rack1.getSize()/2; i++)
                   rack1.insert(new Record(), i*2);
              for (int i= 0; i< rack2.getSize(); i++)
                   rack2.insert(new Record(), i);
              System.err.println("Rack one has " rack1.getNumberOfCDs() " records");
              System.err.println("Rack two has " rack2.getNumberOfCDs() " records");
              int moved= rack1.move(rack2);
              System.err.println(moved +" records were moved");
              System.err.println("Rack one has " rack1.getNumberOfCDs() " records");
              System.err.println("Rack two has " rack2.getNumberOfCDs() " records");

  • How to show staticly decleared int's in a JLabel

    hi
    how to show staticly decleared int's in a JLabel
    i have the following code but it doesnt seem to be working
           // Declear jlabel
            JLabel statuslabel = new JLabel(" X Axis : " + x + " Y Axis : + y ");
           // position of cursor
            public static int x;
            public static int y;
           

    nicchick wrote:
    um is there a easyer way to update int's inside a JLabel:)You need a MouseMotionListener
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.Point;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    public class CursorPositionInLabel
      private static final String BAD_LABEL = "Bad Label";
      private static final String GOOD_LABEL = "Good Label";
      private JPanel mainPanel = new JPanel();
      private Point cursorP = new Point();
      private JLabel badLabel = new JLabel(BAD_LABEL + ";  [" + cursorP.x + ", " + cursorP.y + "]"); // this guy never gets updated, & so never changes
      private JLabel goodLabel = new JLabel(GOOD_LABEL + ";  [" + cursorP.x + ", " + cursorP.y + "]");
      public CursorPositionInLabel()
        mainPanel.setPreferredSize(new Dimension(600, 600));
        mainPanel.setLayout(new GridLayout(1, 2));
        JPanel badPanel = new JPanel();
        badPanel.add(badLabel);
        JPanel goodPanel = new JPanel();
        goodPanel.add(goodLabel);
        mainPanel.add(badPanel);
        mainPanel.add(goodPanel);
        mainPanel.addMouseMotionListener(new MouseAdapter()
          // this is the event that gets tripped each time the mouse moves
          public void mouseMoved(MouseEvent e)
            // get the location of the mouse curse
            cursorP = e.getPoint();
            // and then update your JLabel with the coordinates
            goodLabel.setText(GOOD_LABEL + ";  [" + cursorP.x + ", " + cursorP.y + "]");
      public JPanel getMainPanel()
        return mainPanel;
      // create the JFrame in a thread-safe manner as the Sun tutorials tell us to do.
      private static void createAndShowUI()
        JFrame frame = new JFrame("CursorPositionInLabel");
        frame.getContentPane().add(new CursorPositionInLabel().getMainPanel());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      public static void main(String[] args)
        java.awt.EventQueue.invokeLater(new Runnable()
          public void run()
            createAndShowUI();
    }Edited by: Encephalopathic on Jun 18, 2008 5:28 PM

  • Public void movePlayer

    I cant figure out what to write for my switch statement on this assignment,
    (25 spaced board game with 2 players, each taking turns rolling a die untill someone reaches 25)
    my method parameters for the movePlayer method are sapposed to be which player, (player1 or player2), moves as well as how many spaces out of 6 (rolled on the die). i am also sapposed to check if a winner can be identified in case 1 and case 2.
    i thought i was getting the hang of this but on this i'm at a total loss for ideas of how to do it,
    anyone have suggestions?
    public class GameBoard
            public static final int BOARD_LENGTH = 25;
         private int player1;
         private int player2;
         private int winner;
    public GameBoard(int player1State, int player2State)
              player1 = 0;
              player2 = 0;
              winner = 0;
              player1 = player1State;
              player2 = player2State;
    int player1State;
    int player2State;
    public int getBoardLength()
              return BOARD_LENGTH;
    public int getPlayer1State()
              return player1State;
    public int getPlayer2State()
              return player2State;
    int getWinner()
              return winner;
    public void resetBoard(int player1State, int player2State, int winner)
              player1State = 0;
              player2State = 0;
              winner = 0;
             // This method moves the specified player along
         // the game board a specified number of spaces.
         public void movePlayer( int spacesMoved, int playerMoved)
                 int spacesMoved;
                 int playerMoved;
              switch( playerMoved )
                   case 1:
                        // Your code goes here.
                   case 2:
                        // Your code goes here.
                   default:
                        System.out.println("Warning: Player " +  //Fill this in//
                                            + " does not exist!");
    }

    public class GameBoard
            public static final int BOARD_LENGTH = 25;
         private int player1;
         private int player2;
         private int winner;
    public GameBoard(int player1State, int player2State)
              player1 = 0;  // pointless! you reset its value 3 lines below
              player2 = 0;  // ditto
              winner = 0;
              player1 = player1State;
              player2 = player2State;
    int player1State;  // why do  you need a player1 variable as well as this one?
    int player2State;  // ditto
    public int getBoardLength()
              return BOARD_LENGTH;
    public int getPlayer1State()
              return player1State;
    public int getPlayer2State()
              return player2State;
    int getWinner()
              return winner;
    public void resetBoard(int player1State, int player2State, int winner)
              player1State = 0;
              player2State = 0;
              winner = 0;
             // This method moves the specified player along
         // the game board a specified number of spaces.
         public void movePlayer( int spacesMoved, int playerMoved)
                 int spacesMoved;  // pointless! You have a parameter with same name
                 int playerMoved;  // ditto
              switch( playerMoved )
                   case 1:
                        // Your code goes here.
                                   // presumably it is player1's turn so increase the player1 variable by number of spaces
                   case 2:
                        // Your code goes here.
                                    // ditto but for player2
                   default:
                        System.out.println("Warning: Player " +  //Fill this in//
                                            + " does not exist!");
    }See comments.

Maybe you are looking for