Results 1 to 2 of 2
  1. #1
    Shargath is offline Member
    Join Date
    Apr 2011
    Posts
    1
    Rep Power
    0

    Default adding component(object?) to JFrame after actionPerformed

    Hi,

    I'm trying to make a board game called "Don't get angry" in Java and I need to generate a playing field with cells. The problem is I cant generate it right away the program starts but after user choose from optionbox the number of cells/number of players and then clicks "generate" button.

    So far I have JFrame with two JPanels - one with the option box and generate button and the other one where I want playing field....

    I've tried something like:

    Field field;

    public void actionPerformed(ActionEvent e){
    String cellsCount = (String)selectFNum.getSelectedItem();
    field = new Field(Integer.parseInt(cellsCount));
    }

    JPanel gameBoard = new JPanel(new GridBagLayout());
    gameBoard.add(field);

    but eclipse throws an exception because the field is null until actionPerformed...

    so how can I solve this? I've tried everything I came up with but since I'm new to Java & OOP, I wasnt succesfull

    while writing this post I got an idea - first create something like starter screen with menu or whatever where user has to choose the number of cells/number of players, after he clicks generate - the screen is cleared and program will paint whole new JFrame with already generated playing field, so what do You think?

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Go ahead and try our plan, you've nothing to lose. Otherwise you could perhaps allow Field to be made with out a cell count and then give it a setCellCount(int cellCount) method and use that to set the field's cell count from within the action listener. There are many ways to solve this. Just remember to revalidate and repaint any containers that have had their components changed.

    Wish you luck!

Similar Threads

  1. Adding a KeyListener to a JFrame with buttons.
    By jamhead in forum AWT / Swing
    Replies: 1
    Last Post: 12-11-2010, 08:29 PM
  2. Replies: 8
    Last Post: 02-28-2010, 09:36 AM
  3. Adding component at runtime
    By Beju in forum Java Applets
    Replies: 5
    Last Post: 06-16-2009, 12:28 PM
  4. Manually adding a component
    By djc in forum NetBeans
    Replies: 3
    Last Post: 04-01-2009, 12:51 PM
  5. Adding file contents to Choice component
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 02-07-2008, 10:06 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •