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.

Results 1 to 15 of 15

Thread: How to display a Java method using Java Swing

  1. #1
    Member
    Join Date
    May 2011
    Posts
    61
    My Mood
    Busy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default How to display a Java method using Java Swing

    Hi, ppl, here's my problem. I want to be able to display my function using Java Swing. I tried using JLabel and passing in the method, but that doesn't work.

    Eg: JLabel label=new JLabel(dog.makeSound);

    so makeSound could be like:

    public void makeSound()
    {
    System.out.println("bark");
    }

    This isn't my actual program, but I just want to know HOW to call a function to be used with Java Swing. Please help ppl! Thanks.


  2. #2
    Junior Member
    Join Date
    May 2011
    Posts
    5
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: How to display a Java method using Java Swing

    Swing is a framework that enables you to create graphical user interfaces. It's not a different way of calling methods. Remember that, when calling a method, you must append the suffix '()'.

    Seems like you need to go back to the basics of Java.

    Trail: Learning the Java Language (The Java™ Tutorials) is an excelent place to start.

  3. #3
    Member
    Join Date
    May 2011
    Posts
    61
    My Mood
    Busy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to display a Java method using Java Swing

    But what if I add a JButton and then the action event would be that after it is clicked, it will perform that function. See, I got a JButton I created to do this action, BUT it shows up in the console window, so is there a way for it to redisplay in the Java Swing window instead of the console. My project is a text based word search, so the user types the word they wish to find, and since it is text based, I can't give out the word list to find except a hint that it all animal words for eg. Anyways, each time they type in a word, the console will have to scroll down to redisplay my wordsearch board of characters, and of course it just looks messy and that's why I wanted to somehow have just one wordsearch board displayed using Java Swing and a textfield below with an Enter button to submit the word the user finds on the board. Please let me know how I can go about displaying this word search board which which is a void method I made. Thanks.

  4. #4
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: How to display a Java method using Java Swing

    I don't really know what you're saying. Perhaps you should draw out a picture of what you want. I recommend you read through the Swing tutorial to get a handle on the different components at your disposal: Trail: Creating a GUI With JFC/Swing (The Java™ Tutorials)
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  5. #5
    Member
    Join Date
    May 2011
    Posts
    61
    My Mood
    Busy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to display a Java method using Java Swing

    Console output:
    ________________
    |
    |# p # # # #
    |
    |# i # r a t
    |
    |# g # # # #
    |
    |# # k c u d
    |
    |# t a b # #
    |________________

    Explanation:
    ==================================================
    Note: please see the attach jpg file, I outlined the words to find, but in my actual displayBoard() function, it just shows this same board on the console. So to put the explanation below simply, I just want to know how to incorporate this one Word Search board to be shown using Java Swing.

    So this would be an eg of my displayBoard() method, so it's a 2D array of characters for the word search, I put the # symbols so that I can see my words for my testing. The words the user can type in to find are only column words and row words, I have yet to write methods for diagonal words. So the idea is that I want the to use Java Swing so that each time the user finds a word on the board, they type it in, press Enter and then I would have some status to indicate the number of words remaining to find, so using Java Swing is easier and cleaner, since I just have the one board at all times regardless of how many inputs user types in when they find a word on the board. Please see the right attached jpg with what I intend to use Java Swing for.

    So the idea for what I want to do as to integrating my WordSearch program with Java Swing is this: I have this wordSearch display that is made by the displayBoard() function (which is void by the way) and then below it a textfield to type in the word, then an Enter button, then other Java Swing components would be a status to show how man words remaining and also another textfield or textbox (I don't know the right term) that displays for eg: "pig" was found or "mouse" was not found etc. I hope I am more clear as to what I want to do involving Java Swing.

    So I already have some WordSearch class that has all the methods: so displayBoard(), updateWordList(), findRowWords(), findColWords() etc and a main class called WordSearchDemo and in my main function, I create a WordSearch constructor, so eg: WordSearch game=new WordSearc(), then I would call the displayBoard() method and it would show up on the console with game.displayBoard(), BUT now that I know about Java Swing, I need someone to help me out as how to use my existing displayBoard() method to show up just ONCE in Java Swing. So do I put it in a JPanel or what. I am not experienced with Java Swing. If anyone can help a fellow programmer out, I would really appreciate it. Thanks.
    Attached Images Attached Images
    Last edited by IHeartProgramming; May 10th, 2011 at 08:47 PM. Reason: mistake

  6. #6
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: How to display a Java method using Java Swing

    Honestly, your best bet is to read through the Swing tutorial.

    But it sounds like you want to extend JPanel and override paintComponent() to do the drawing, then have a JTextField for user input, and then maybe a JLabel to display messages. Also, you'd need a JButton with an ActionListener that searched for the typed word and displayed the appropriate message.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  7. #7
    Member
    Join Date
    May 2011
    Posts
    61
    My Mood
    Busy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to display a Java method using Java Swing

    Hi, I decided to go with an image by taking a screenshot of the console word search board but now I have questio another question about a different method for my word search program. I have a method that returns an int, specifically the words remaining that user has to find, so my question is how do I link it with the word a user types in the textfield. Do I have to add an ActionListener to my wordsRemainingToFind method? To clarify, I have two classes, the wordSearch class has all the methods for finding words, and then the main class, so my problem is that in my main class, in the constructor, I create a new wordSearch constructor but it doesn't work, so I can never use stuff like wordSearchExample.getWordsRemaining to redisplay in a TextField each time a user finds a word. Please help ppl, do I have to add some ActionListener to my wordSearch class in order to use with the main class?

  8. #8
    Member
    Join Date
    Mar 2011
    Posts
    198
    My Mood
    Daring
    Thanks
    7
    Thanked 4 Times in 4 Posts

    Default Re: How to display a Java method using Java Swing

    hmm im guessing you could use a counter.. and have you tryed

    textboxName.setText("TEXT or string variable name");

    If your calling the string variable from another class you would simply put

    Classname.StringVariableName

    Or is it the method you want linked in your main file?

  9. #9
    Member
    Join Date
    May 2011
    Posts
    61
    My Mood
    Busy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to display a Java method using Java Swing

    Ok, I'll just show you what I am stuck with: So below are a simplified version of my two classes:

    WordSearch class:
    =============

    public class WordSearch
    {
    private String board[][]={{"p","p","o"},
    {"i","p","o"},
    {"g","p","o"},
    };
    private int wordsRemaining=8;


    public void findRowForwardWords(String userWordToFind)
    {
    //algorithm to find words that you read horizontally from left to right
    if the word is found on board, then:
    wordsRemaining-=1;

    }

    public int wordsRemaining()
    {
    return wordsRemaining;
    }
    }//END WordSearch clas
    =======================================

    WordSearchDemo class:
    ==================
    import java.awt.*;
    import javax.swing.*;


    public class WordSearchDemo extends JFrame implements ActionListener
    {
    public WordSearchDemo()
    {
    setTitle("Word Search!");
    JPanel panel=new JPanel();
    getContentPane().add(panel);
    getContentPane().setLayout(new FlowLayout());
    panel.setLayout(new FlowLayout());

    try
    {
    BufferedImage myPicture = ImageIO.read(new File("WordSearchGUIDisplay.png"));
    JLabel wordSearchBoard = new JLabel(new ImageIcon( myPicture ));
    add(wordSearchBoard);
    }
    catch (Exception e)
    {
    System.out.println("There was a problem loading the image.");
    }

    JTextField textField=new JTextField("Type the word found on the board and press OK");
    JButton button=new JButton("Search");

    button.setBackground(Color.CYAN);
    JLabel label=new JLabel("Find all 8 animals");
    button.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent event)
    {
    //how do I link to my wordsRemaining method in the WordSearch class
    }
    }
    );

    //getContentPane().add(button);
    panel.add(label);
    panel.add(textField);
    panel.add(button);
    //panel.setBorder(BorderFactory.createEmptyBorder(10 , 10, 10, 10));
    add(panel);//same as: getContentPane().add(panel)



    }//END WordSearchDemo CONSTRUCTOR


    public static void main(String[] args)
    {
    SwingUtilities.invokeLater(new Runnable()
    {
    public void run()
    {
    WordSearch2011Demo gui = new WordSearch2011Demo();
    gui.setVisible(true);
    }
    });

    }//END main FUNCTION
    }
    //END WordSearchDemo
    ============================
    I hope that my code is clear enough, so my problem is how do I link my wordsRemaining method from my WordSearch class with a new WordSearch constructor in the WordSearchDemo class. Do I need to add an ActionListener to wordsReamining method, please help, ppl!!
    Last edited by IHeartProgramming; May 13th, 2011 at 12:32 PM.

  10. #10
    Member
    Join Date
    Mar 2011
    Posts
    198
    My Mood
    Daring
    Thanks
    7
    Thanked 4 Times in 4 Posts

    Default Re: How to display a Java method using Java Swing

    WordSearch ChooseName = new WordSearch();
    ChooseName.METHOD();

    import this in WordSearchDemo.java
    ChooseName = pick a name you would like to call it.
    METHOD = Choose the method in the WordSearch Class and put the name here.

    and to make it simple, Where ever you would like to start to run the method display
    WordSearch();

    make sure the code at the top is in the new WordSearch method you make in word search demo..

  11. #11
    Member
    Join Date
    Mar 2011
    Posts
    198
    My Mood
    Daring
    Thanks
    7
    Thanked 4 Times in 4 Posts

    Default Re: How to display a Java method using Java Swing

    Quote Originally Posted by IHeartProgramming View Post

    WordSearch class:
    =============

    public class WordSearch
    {
    private String board[][]={{"p","p","o"},
    {"i","p","o"},
    {"g","p","o"},
    };
    private int wordsRemaining=8;


    public void findRowForwardWords(String userWordToFind)
    {
    //algorithm to find words that you read horizontally from left to right
    if the word is found on board, then:
    wordsRemaining-=1;

    }

    public int wordsRemaining()
    {
    return wordsRemaining;
    }
    }//END WordSearch clas
    =======================================

    WordSearchDemo class:
    ==================
    import java.awt.*;
    import javax.swing.*;


    public class WordSearchDemo extends JFrame implements ActionListener
    {
    public WordSearchDemo()
    {
    setTitle("Word Search!");
    JPanel panel=new JPanel();
    getContentPane().add(panel);
    getContentPane().setLayout(new FlowLayout());
    panel.setLayout(new FlowLayout());

    //display the method from other class where you would like it to execute
    WordSearch();

    try
    {
    BufferedImage myPicture = ImageIO.read(new File("WordSearchGUIDisplay.png"));
    JLabel wordSearchBoard = new JLabel(new ImageIcon( myPicture ));
    add(wordSearchBoard);
    }
    catch (Exception e)
    {
    System.out.println("There was a problem loading the image.");
    }

    JTextField textField=new JTextField("Type the word found on the board and press OK");
    JButton button=new JButton("Search");

    button.setBackground(Color.CYAN);
    JLabel label=new JLabel("Find all 8 animals");
    button.addActionListener(new ActionListener()
    {
    public void actionPerformed(ActionEvent event)
    {
    //how do I link to my wordsRemaining method in the WordSearch class
    }

    // Creates the WordSearch method and imports the WordSearch method from the other class
    public void WordSearch(){
    WordSearch ws = new WordSearch();
    ws.WordSearch();
    }

    }
    );

    //getContentPane().add(button);
    panel.add(label);
    panel.add(textField);
    panel.add(button);
    //panel.setBorder(BorderFactory.createEmptyBorder(10 , 10, 10, 10));
    add(panel);//same as: getContentPane().add(panel)



    }//END WordSearchDemo CONSTRUCTOR


    public static void main(String[] args)
    {
    SwingUtilities.invokeLater(new Runnable()
    {
    public void run()
    {
    WordSearch2011Demo gui = new WordSearch2011Demo();
    gui.setVisible(true);
    }
    });

    }//END main FUNCTION
    }
    //END WordSearchDemo
    ============================
    Sorry for double post, I figured it would be easier to show a demo lol, Hope this helps..
    Last edited by macko; May 13th, 2011 at 05:52 PM. Reason: Spelling mistake

  12. #12
    Member
    Join Date
    May 2011
    Posts
    61
    My Mood
    Busy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to display a Java method using Java Swing

    I think I found my mistake, thanks

  13. #13
    Member
    Join Date
    May 2011
    Posts
    61
    My Mood
    Busy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to display a Java method using Java Swing

    Ok, now I have a new problem, after the user finds all the words, I want to change the word search board a congratulatory image I made. I tried to use the repaint() method in my else if part of the actionlistener where when a user types in the last word to find, the else if will show "good job!" in a JTextArea, BUT I also want the word search display to change to my congratulatory image. This is what I did:

    else if(game.wordsRemaining()==0)
    {
    statusMessage="You've found all the words!";
    statusTextArea.setText(statusMessage);

    try
    {
    BufferedImage myPicture = ImageIO.read(new File("congratulationsGUIDisplay.jpg"));
    JLabel wordSearchBoard = new JLabel(new ImageIcon( myPicture ));
    add(wordSearchBoard);
    }
    catch(Exception e)
    {
    System.out.println(e.getMessage());
    }

    }//END congratulatory ELSE IF

    **BUT NOTHING HAPPENS, does anyone know why it doesn't update, I tried putting repaint() inside this else if as the last statement and I've tried putting the repaint() at the end of the WordSearch constructor. Please help, anyone!!
    Last edited by IHeartProgramming; May 18th, 2011 at 12:25 PM.

  14. #14
    Member
    Join Date
    May 2011
    Posts
    61
    My Mood
    Busy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to display a Java method using Java Swing

    **Please can someone help me out and let me know what's wrong with my code for my post above this one. I'd appreciate it, thanks.

  15. #15
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: How to display a Java method using Java Swing

    Try calling invalidate() or validate() or revalidate() after you add the JLabel. It's in the API, but I'm too lazy to look it up right now (just had a big lunch of Indian food, feeling fat and sleepy).
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

Similar Threads

  1. how to implement method to add new Student and display it
    By exose in forum What's Wrong With My Code?
    Replies: 6
    Last Post: February 10th, 2011, 11:39 AM
  2. Replies: 6
    Last Post: January 28th, 2011, 01:13 AM
  3. Display prime numbers from 100 to 200 in Java
    By c.P.u1 in forum What's Wrong With My Code?
    Replies: 8
    Last Post: January 25th, 2011, 03:14 PM
  4. How to display ppt slides through java????
    By jj_crazy_1 in forum Java Theory & Questions
    Replies: 0
    Last Post: April 5th, 2010, 10:52 PM
  5. How to display the contents of my queue?
    By rocafella5007 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 30th, 2009, 11:46 AM