Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Page 1 of 2 12 LastLast
Results 1 to 25 of 35

Thread: how to put changeable value in JTextField?

  1. #1
    Member
    Join Date
    May 2012
    Posts
    34
    Thanks
    17
    Thanked 1 Time in 1 Post

    Default how to put changeable value in JTextField?

    So, i made an applet w/ Eclipse, in which after every killed brick(or block) player gets 20 points.

    In an applet points are counting well. Example there: applet in JFrame (I highlighted score values with red circles.)

    But i cant figure out how to put that score value in a JTextField.

    Main class of applet (parts where i am using value 'score'):
    public class Main extends Applet implements Runnable, KeyListener
    {
    	public int score;
     
    public void run(){
            ...
     
            if(blocks.get(i).alive == false){
    			blocks.remove(i);
    			score += 20;
             }
             ...
    }}

    JFrame class:
    public class Window extends JFrame {
     
            private JFrame PaddleBricks;	
    	public static Main app = new Main();
            public JTextField textField;
    ...
    private void initialize() {
     
    textField = new JTextField();
    textField.setBounds(21, 114, 65, 20);
    PaddleBricks.getContentPane().add(textField);
    textField.setText(Integer.toString(app.score));
    }}

    I know that I only once set a 'score' value to that text field.
    But I don't know how to make it changeable in a JTextField.
    Should i use for/while cycle?
    Maybe it is possible to make it changeable for example in every 3 seconds or something like that?

    As u can see in this picture: applet in JFrame (I highlighted score values with red circles.)

    Score on the top of an applet is ok, but in a textfield it stays at 0.
    Last edited by scorpas; May 17th, 2012 at 12:58 PM.


  2. #2
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: how to put changeable value in JTextField?

    The only proper way to change the value of a JTextField is by calling the setText() method. I believe it has to do with the fact that JTextField are not constantly redrawing themselves, so changing the Strings that it may be displaying will not change what the JTextField displays. What you should do to fix this by using something called: event-driven programming.
    To put it simply, you should create a method which updates your JTextField. Then, whenever you would like the value updated (perhaps every time the ball hits one of the squares), you would call the method.

    NOTE: It is NEVER recommended to have a never-ending loop for the purpose of updating GUI elements. Using this practice will result in your program locking up and crashing.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  3. #3
    Member
    Join Date
    May 2012
    Posts
    34
    Thanks
    17
    Thanked 1 Time in 1 Post

    Default Re: how to put changeable value in JTextField?

    Quote Originally Posted by aussiemcgr View Post
    To put it simply, you should create a method which updates your JTextField. Then, whenever you would like the value updated (perhaps every time the ball hits one of the squares), you would call the method.
    I do understand that.
    But i can't imagine how to do that
    So, i have Main class, in which 'score' value is updating, every time the ball hits a block (brick).

    And i do have a class for a GUI (JFrame).

    I tried to create a constructor of JFrame class in Main class, and then where the value is changing in Main class, i wrote:
    Window.textField.setText(Integer.toString(score)).
    And of course, I commented setText method in JFrame class. But then textfield was empty...

    I tried to create a constructor of Main class in JFrame class, and made a simple SetText method:
    public void setText(int a){
           textfield.setText(Integer.toString(a));
    }

    and use it in my Main class where the value of score is changing: window.setText(score);
    But it didn't work out...

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: how to put changeable value in JTextField?

    it didn't work out.
    Can you explain.
    Try calling repaint() after setting the text.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: how to put changeable value in JTextField?

    You need to ask the questions:
    1) What event happens that should cause the text field to update?
    2) Where in my code does the event get handled?

    Now, you said that the score is supposed to update every time the ball hits a brick. Post the section of your code that handles that event. I assume something should happen (other than the score updating) every time the ball hits a brick. That is where we want to call the setText() method from.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  6. #6
    Member
    Join Date
    May 2012
    Posts
    34
    Thanks
    17
    Thanked 1 Time in 1 Post

    Default Re: how to put changeable value in JTextField?

    Quote Originally Posted by aussiemcgr View Post
    You need to ask the questions:
    Now, you said that the score is supposed to update every time the ball hits a brick. Post the section of your code that handles that event. I assume something should happen (other than the score updating) every time the ball hits a brick. That is where we want to call the setText() method from.
    method in a ball class.
    public void CheckCollision(Block b){
    		Rectangle2D.Double ball = new Rectangle2D.Double(x-radius, y-radius, radius*2, radius*2);
    		Rectangle2D.Double block = new Rectangle2D.Double(b.x, b.y, b.width, b.height);
    		if(ball.intersects(block)){ 
    			b.alive = false;
    		}
    	}

    and then in a 'run' method of a 'Main' class i use that 'CheckCollision' method:
    public void run(){		
    		while(running){
     
    			for (int i = 0; i < blocks.size(); i++){
    				ball.CheckCollision(blocks.get(i));
    				if(blocks.get(i).alive == false){
    					blocks.remove(i);
    					score += 20;					
    					hitBlocks ++;
    					}
    			}
    			repaint();
    			try{
    				Thread.sleep(1000/fps);
    			}
    			catch(Exception e){}			
    		}		
    	}

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: how to put changeable value in JTextField?

    Where do you call any methods to change the contents of the text field where the data is displayed?
    If you don't understand my answer, don't ignore it, ask a question.

  8. #8
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: how to put changeable value in JTextField?

    Ok, so you want to call the setText() method whenever ball.intersects(block), right?
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  9. #9
    Member
    Join Date
    May 2012
    Posts
    34
    Thanks
    17
    Thanked 1 Time in 1 Post

    Default Re: how to put changeable value in JTextField?

    Quote Originally Posted by aussiemcgr View Post
    Ok, so you want to call the setText() method whenever ball.intersects(block), right?
    That's right.

    so i declare in a ball class:
    Window win = new Window();
    Main app = new Main();
    and tried to write this, right after that if:
    win.textField.setText(Integer.toString(app.score));

    but got errors when the ball hits a block (then applet freeze):
    Exception in thread "Thread-1" java.lang.NullPointerException
     
    	at Zaidimas.Ball.CheckCollision(Ball.java:61) 
    //in method CheckCollision(), on the line: win.textField.setText(Integer.toString(app.score));
     
    	at Zaidimas.Main.run(Main.java:169)  
    //in method run(), on the line: ball.CheckCollision(blocks.get(i));
     
    	at java.lang.Thread.run(Unknown Source)
    Last edited by scorpas; May 19th, 2012 at 03:18 AM.

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: how to put changeable value in JTextField?

    java.lang.NullPointerException
    at Zaidimas.Ball.CheckCollision(Ball.java:61)
    Look at line 61 and find the variable that has a null value. If you can not see which variable is null, add a println just before line 61 that prints out the values of all the variables used on line 61. If this is the line:
    win.textField.setText(Integer.toString(app.score)) ;
    print out the values of: win, textfield and app

    When you have found the variable with the null value, backtrack to see why it does not have a valid value.
    If you don't understand my answer, don't ignore it, ask a question.

  11. #11
    Member
    Join Date
    May 2012
    Posts
    34
    Thanks
    17
    Thanked 1 Time in 1 Post

    Default Re: how to put changeable value in JTextField?

    it is textfield...

    win: Zaidimas.Window[frame0,0,0,0x0,invalid,hidden,layout=java.awt.BorderLayout,title=,resizable,normal,defaultCloseOperation=HIDE_ON_CLOSE,rootPane=javax.swing.JRootPane[,0,0,0x0,invalid,layout=javax.swing.JRootPane$RootLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=16777673,maximumSize=,minimumSize=,preferredSize=],rootPaneCheckingEnabled=true]
     
    Exception in thread "Thread-1" tf: null
     
    app:Zaidimas.Main[panel0,0,0,0x0,invalid,layout=java.awt.FlowLayout]

  12. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: how to put changeable value in JTextField?

    Why is textField null?
    Check that the code gives textField a value. Make sure their is only one variable named textField.
    If you don't understand my answer, don't ignore it, ask a question.

  13. #13
    Member
    Join Date
    May 2012
    Posts
    34
    Thanks
    17
    Thanked 1 Time in 1 Post

    Default Re: how to put changeable value in JTextField?

    ok, i manage to fix that error, it was my bad in text field declaration.

    now in my Window class, that extends JFrame, i have:

    public JTextField textField;
    private void initialize() {
    		textField = new JTextField();
    		textField.setHorizontalAlignment(SwingConstants.TRAILING);
    		textField.setEditable(true);
    		textField.setBounds(21, 114, 65, 20);
    		frame.getContentPane().add(textField);
    		textField.setColumns(10);
    }

    in my ball class:
    				System.out.print("win: " + win +"\n");
    			System.out.print("tf: " + win.textField+"\n");
    			System.out.print("app: " + app + "\n");
    			System.out.print(Integer.toString(app.score) +"\n");
     
    			win.textField.setText(Integer.toString(app.score));

    Rezults of printings are:
    win: Zaidimas.Window[frame0,0,0,0x0,invalid,hidden,layout=java.awt.BorderLayout,title=,resizable,normal,defaultCloseOperation=HIDE_ON_CLOSE,rootPane=javax.swing.JRootPane[,0,0,0x0,invalid,layout=javax.swing.JRootPane$RootLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=16777673,maximumSize=,minimumSize=,preferredSize=],rootPaneCheckingEnabled=true]
    tf: javax.swing.JTextField[,21,114,65x20,invalid,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@1908ca1,flags=296,maximumSize=,minimumSize=,preferredSize=,caretColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],disabledTextColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],editable=true,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],selectionColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],columns=10,columnWidth=0,command=,horizontalAlignment=TRAILING]
    app: Zaidimas.Main[panel0,0,0,0x0,invalid,layout=java.awt.FlowLayout]
    20

    but still, i can't see 'score' value in JFrame... text field is empty.

  14. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: how to put changeable value in JTextField?

    did you try calling repaint() for the GUI that the text field is shown in?
    Otherwise you'll have to post the code for testing.
    If you don't understand my answer, don't ignore it, ask a question.

  15. #15
    Member
    Join Date
    May 2012
    Posts
    34
    Thanks
    17
    Thanked 1 Time in 1 Post

    Default Re: how to put changeable value in JTextField?

    where i should call repaint()?
    tried to put it, just after win.textField.setText(Integer.toString(app.score)) ; line:

    win.textField.repaint();

    Still, text field empty.


    If i use textField.setText method in Window class, then textField isn't empty, and first value of score are set: 0.

    edit:
    it looks like the only way is to create a cycle or a method in Window class... but that is almost impossible, cuz i need a lot of values from other classes...
    Last edited by scorpas; May 19th, 2012 at 07:45 AM.

  16. #16
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: how to put changeable value in JTextField?

    Zaidimas.Window[frame0,0,0,0x0,invalid,hidden,
    Is there more than on instance of the class that the win variable points to? One is visible and the other, where the call to setText is going, is not.
    Last edited by Norm; May 19th, 2012 at 08:04 AM.
    If you don't understand my answer, don't ignore it, ask a question.

  17. #17
    Member
    Join Date
    May 2012
    Posts
    34
    Thanks
    17
    Thanked 1 Time in 1 Post

    Default Re: how to put changeable value in JTextField?

    don't get it...
    do you mean i call Window class twice w/ the same name (win)?

  18. #18
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: how to put changeable value in JTextField?

    Add a println to your Window (Window is a java SE class???) class's constructor so you can see how many instances of the class you create by the number of times the println prints out its message.
    If you don't understand my answer, don't ignore it, ask a question.

  19. #19
    Member
    Join Date
    May 2012
    Posts
    34
    Thanks
    17
    Thanked 1 Time in 1 Post

    Default Re: how to put changeable value in JTextField?

    it's two times.
    but my project works like that:
    - firstly, the small window shows up with the button "play".
    - after that buttont is clicked, the same window becames bigger (resize method) and an applet appears in that window.

    So the first time window constructor is called when project starts, the second time when i click Play button.

    window class extends JFrame. that is my GUI class.
    Last edited by scorpas; May 19th, 2012 at 08:59 AM.

  20. #20
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: how to put changeable value in JTextField?

    I think you are looking at one window and setting the values for the hidden window.
    Change the logic so you set the values for the window you are looking at.
    If you don't understand my answer, don't ignore it, ask a question.

  21. #21
    Member
    Join Date
    May 2012
    Posts
    34
    Thanks
    17
    Thanked 1 Time in 1 Post

    Default Re: how to put changeable value in JTextField?

    ok, so i modify my Window class to minimum: no buttons, no menus, only that textfield and applet starts when Play button is clicked...

    this is how it looks:
    public class Window extends JFrame {
    	public JFrame frame;
    	Main app = new Main();	
    	public JTextField textField;
     
    	public static void main(String[] args) {
     
    		EventQueue.invokeLater(new Runnable() {
    			public void run() {
    				try {
    					Window window = new Window();					
    					window.frame.setVisible(true);			
    				} catch (Exception e) {
    					e.printStackTrace();
    				}
    			}
    		});
    	}
     
    	public void GameStart(){
     
    		JPanel panel_1 = new JPanel();		
    		panel_1.setBounds(130, 2, 440, 430);
    		panel_1.setVisible(true);
    		frame.getContentPane().add(panel_1);
    		panel_1.add(app);
     
    		app.init();		
    		app.start();
    		app.setVisible(true);
    		app.setSize(440, 400);
    		app.setBounds(0, 0, 440, 400);
     
    	}
     
    	public Window() {
    		initialize();
    		System.out.print("Window used" + "\n");
    	}
     
    	private void initialize() {
     
    		frame = new JFrame();
    		frame.setTitle("Žaidimas \"Paddle bricks\"");
    		frame.setBounds(200, 100, 600, 520);
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.getContentPane().setLayout(null);
     
    		final JButton zaisti = new JButton("PLAY");
    		zaisti.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {
    				GameStart();
    			}
    		});		
    		zaisti.setBounds(22, 11, 85, 27);
    		frame.getContentPane().add(zaisti);
     
    		textField = new JTextField();
    		textField.setBounds(21, 114, 65, 20);
    		textField.setVisible(true);
    		frame.getContentPane().add(textField);
    		}
    }

    actually, when i wrote this line "window.setVisible(true);" in a run method, another window shows up, but its empty, and that window do not call window constructor.
    only when i click Play button to activate applet, window constructor is called second time...
    Last edited by scorpas; May 19th, 2012 at 09:49 AM.

  22. #22
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: how to put changeable value in JTextField?

    Window is a Java SE class. Can you give your class a different name?

    You can create as many instances of your window class as you want. If you want to see the contents of any component that is in a window, you need to change the component that is in the instance that is being shown.

    Why extend JFrame and also have the variable: frame?

    How many windows are needed?
    Last edited by Norm; May 19th, 2012 at 09:54 AM.
    If you don't understand my answer, don't ignore it, ask a question.

  23. #23
    Member
    Join Date
    May 2012
    Posts
    34
    Thanks
    17
    Thanked 1 Time in 1 Post

    Default Re: how to put changeable value in JTextField?

    actually, i create this, by using windows builder in eclipse so most of the source code, was auto-generated by Eclipse. i just picked an element (for example JTextBox), draged it on that window, and eclipse did its job w/ code.

    so i need to rename my class? then delete 'extends JFrame'? what else?

    one window is needed. as i said, i clicked Run (Window):
    Window appears w/ a button Play.
    Then I clicked that button an applet appears in the same window.
    and the TextField (for a changeable value), also is in the same window.

  24. #24
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: how to put changeable value in JTextField?

    How the class is defined depends on how you are using it. Normally one JFrame is enough.
    an applet appears in the same window.
    What do you mean by "applet"? Applet's run from HTML pages in browsers.
    If you don't understand my answer, don't ignore it, ask a question.

  25. #25
    Member
    Join Date
    May 2012
    Posts
    34
    Thanks
    17
    Thanked 1 Time in 1 Post

    Default Re: how to put changeable value in JTextField?

    What do you mean by "applet"? Applet's run from HTML pages in browsers.
    When i run my project and select Main class as a main, only applet starts (no GUI): Example

    ok i modify that Window class, now it looks like that:
    public class baaaa {
     
    	public JFrame frame;
     
    	Main app = new Main();
     
    	public JTextField textField;
     
    	public static void main(String[] args) {
    		EventQueue.invokeLater(new Runnable() {
    			public void run() {
    				try {
    					baaaa window = new baaaa();					
    					window.frame.setVisible(true);	
    				} catch (Exception e) {
    					e.printStackTrace();}
    			}	});
    	}
    	public void GameStart(){
     
    		JPanel panel_1 = new JPanel();		
    		panel_1.setBounds(130, 2, 440, 430);
    		panel_1.setVisible(true);
    		frame.getContentPane().add(panel_1);
    		panel_1.add(app);
    		app.init();		
    		app.start();
    	    app.setVisible(true);
    	    app.setSize(440, 400);
    	    app.setBounds(0, 0, 440, 400);	    
    	}
     
    	public baaaa() {
    		initialize();
    		System.out.print("Window used" + "\n");
    	}
     
    	private void initialize() {
    		frame = new JFrame();
    		frame.setTitle("Žaidimas \"Paddle bricks\"");
    		frame.setBounds(200, 100, 600, 520); //600 520 ir 200 150		
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.getContentPane().setLayout(null);
     
    		final JButton zaisti = new JButton("Žaisti!");
    		zaisti.addActionListener(new ActionListener() {
    			public void actionPerformed(ActionEvent e) {		
    				GameStart();
    			}	
    		});		
     
    		zaisti.setBounds(22, 11, 85, 27);
    		frame.getContentPane().add(zaisti);		
     
    		textField = new JTextField();		
    		textField.setBounds(21, 114, 65, 20);
    		textField.setVisible(true);
    		frame.getContentPane().add(textField);	
    	}	
    }

    Then in a ball class i declare:
    baaaa aa = new baaaa();
    Main applet = new Main();

    and change that setText method:
    aa.textField.setText(Integer.toString(applet.score));

    Problem still remains. Textfield is empty.

Page 1 of 2 12 LastLast

Similar Threads

  1. Need help int JTextField
    By n00b in forum What's Wrong With My Code?
    Replies: 7
    Last Post: November 1st, 2011, 09:57 AM
  2. how to delete a JTextField?
    By A4Andy in forum AWT / Java Swing
    Replies: 10
    Last Post: August 31st, 2011, 11:33 AM
  3. JTextField ActionListener
    By macko in forum What's Wrong With My Code?
    Replies: 9
    Last Post: May 30th, 2011, 01:53 AM
  4. drawString and JTextField
    By that_guy in forum AWT / Java Swing
    Replies: 9
    Last Post: January 29th, 2011, 02:43 AM
  5. Jtextfield Validation
    By nimishalex in forum AWT / Java Swing
    Replies: 8
    Last Post: December 11th, 2010, 02:42 AM

Tags for this Thread