0

When I run my program the Jbuttons sometimes show up but other times they don't. For example, if I change something unrelated to the JButtons it will not show them. It will just show an empty jframe. PS sorry if I made formatting error's with the code i'm new to this site. Any tips on asking questions would be appreciated.Also it wont let me show the top of the code either.

package ca.seanmckee.digcraft;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Game extends JPanel {

public static String versionnumber = "0.0.1";           //For updating game version number
public static String gamename = "Digcraft ";
public static boolean dig = true;
public static int rocks = 0;
public static int sticks = 0;
public static int logs = 0; 


public static void main(String[]a){

    JFrame frame = new JFrame(gamename + versionnumber);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setSize(800,600);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

    JPanel panel = new JPanel();
    frame.add(panel);
    JButton dig = new JButton("Dig");                           //Dig mechanic allows players to find things
    JButton stickscounter = new JButton("Sticks: " + sticks);
    JButton rockscounter = new JButton ("Rocks: " + rocks);
    JButton logscounter = new JButton("logs" + logs);
    JButton craft = new JButton("Craft");                       //uses things found by digging to create more advanced things
    panel.add(dig);
    panel.add(stickscounter);
    panel.add(rockscounter);
    panel.add(logscounter);
    panel.add(craft);

    dig.addActionListener( new ActionListener() {
        @Override
        public void actionPerformed( ActionEvent e ) {          

          dig();
        }
      });

}

public static void dig(){
    int counter = 0;
    while(counter < 5){

    Random random = new Random();
    int number;
    number = 1+random.nextInt(50);      //Gets random number to select what you dug up
    switch(number){
    case 1:
        System.out.println("You find a rock");
        rocks = rocks + 1;
        break;
    case 2:
        System.out.println("You find a log");
        logs = logs + 1;
        break;
    case 3:
        System.out.println("You find a stick");
        sticks = sticks + 1;
        break;
    default:
        System.out.println("You dig deeper...");
        break;

    }
    counter = counter + 1;
    }


}



}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
seanmckee
  • 1
  • 1

2 Answers2

2

First, take frame.setVisible and make it the last statement of the main method...

public static void main(String[]a){

    JFrame frame = new JFrame(gamename + versionnumber);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Take this...
    //frame.pack();
    //frame.setSize(800,600);
    //frame.setLocationRelativeTo(null);
    //frame.setVisible(true);

    JPanel panel = new JPanel();
    frame.add(panel);
    JButton dig = new JButton("Dig");                           //Dig mechanic allows players to find things
    JButton stickscounter = new JButton("Sticks: " + sticks);
    JButton rockscounter = new JButton ("Rocks: " + rocks);
    JButton logscounter = new JButton("logs" + logs);
    JButton craft = new JButton("Craft");                       //uses things found by digging to create more advanced things
    panel.add(dig);
    panel.add(stickscounter);
    panel.add(rockscounter);
    panel.add(logscounter);
    panel.add(craft);

    dig.addActionListener( new ActionListener() {
        @Override
        public void actionPerformed( ActionEvent e ) {          

          dig();
        }
      });

    // Put it here...
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

You'll also find calling pack and setLocationRelativeTo last will also help, as you will now have content in the frame that will allow pack to do it's job

Second, wrap you UI inside a EventQueue.invokeLater block...

public static void main(String[]a){
    EventQueue.invokeLater(new Runnable() {
        @Override
        public void run() {
            JFrame frame = new JFrame(gamename + versionnumber);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            JPanel panel = new JPanel();
            frame.add(panel);
            JButton dig = new JButton("Dig");                           //Dig mechanic allows players to find things
            JButton stickscounter = new JButton("Sticks: " + sticks);
            JButton rockscounter = new JButton ("Rocks: " + rocks);
            JButton logscounter = new JButton("logs" + logs);
            JButton craft = new JButton("Craft");                       //uses things found by digging to create more advanced things
            panel.add(dig);
            panel.add(stickscounter);
            panel.add(rockscounter);
            panel.add(logscounter);
            panel.add(craft);

            dig.addActionListener( new ActionListener() {
                @Override
                public void actionPerformed( ActionEvent e ) {          

                  dig();
                }
            });

            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    });
}

See Initial Threads for more details

Third, get r

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Also, `frame.pack()` to be last statement, but before `setVisible()`, and replace `frame.setSize()` with `frame.setPrefferedSize()`. – nullptr Nov 09 '14 at 05:59
  • @Meraman yes to `pack`, no to `preferredSize` - See [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/questions/7229226/should-i-avoid-the-use-of-setpreferredmaximumminimumsize-methods-in-java-swi) – MadProgrammer Nov 09 '14 at 06:25
  • I completely do not agree to not use `setPreferredSize()` in JFrame. Because in whatever way jframe lays out components, but if you need to jframe of your custom dimensions, then thats only better way. – nullptr Nov 09 '14 at 06:47
  • And `setPreferredSize()` is more better than `setSize()`, because call to `setPreferredSize()` before `pack()`, the Jframe will be knowing its dimenstion. And doing `setSize()` after `pack()`, jframe has to work to layout components for second time after `pack()`. – nullptr Nov 09 '14 at 06:52
  • The override the getPreferredSize method instead...this will, to more of a greater degree, prevent the frame been sized accidentally by people calling setPreferredSize... – MadProgrammer Nov 09 '14 at 06:54
  • 1
    You can also better control the size using EmptyBorders and insets or gaps of various layouts ;) – MadProgrammer Nov 09 '14 at 06:55
  • the other things work, but for primary container like JFrame, I haven't seen any problem using `setPreferredSize()`, and that's simple way. – nullptr Nov 09 '14 at 06:58
  • 1
    Besides personally, I'd prefer to use the layout properties and borders to adjust the size of the frame (and call pack), as they automatically take into account rendering differences between platforms better then magic numbers any day – MadProgrammer Nov 09 '14 at 06:59
  • @Meraman You're doing it wrong. Use layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). Then `pack()` the frame. Not only is it the perfect right size, but we don't have to try and guess what that size is (as is being done using `setPreferredSize(..)`. – Andrew Thompson Nov 09 '14 at 07:00
  • *"I haven't see any problems using setPreferredSize"* - then you've not done multi-platform development, working between MacOS and windows, there is a ton of differences in how fonts, for instance, get rendered, I've actually seen issues between the same version of Windows with different dpi and screen resolutions...let the layout managers do there jobs...much simpler to solve and maintain – MadProgrammer Nov 09 '14 at 07:02
  • @AndrewThompson I saying about setting JFrame size of dimension I need, and the contained components will automatically resize to fill JFrame container. – nullptr Nov 09 '14 at 07:03
  • @MadProgrammer and doing things with empty borders and gaps will occupy un-necessary space in JFrame that I don't need. I have never faced problem in any platform with this method. Because if I set size less or more than contained elements, and contained elements will resize to fill JFrame, without losing appearance style. And if I don't set prefereed size, then also contained components rendered perfectly. – nullptr Nov 09 '14 at 07:10
  • My comment was just to set size of frame that I needed without extra work to add borders and gaps to make JFrame of size that I need. – nullptr Nov 09 '14 at 07:12
  • And if you face problems with setting preferred size of JFrame, I will say you didn't layout your components well. – nullptr Nov 09 '14 at 07:12
  • Because setting size of JFrame is like resizing your JFrame after it has been displayed. If you don't get same result on resizing JFrame after it has been displayed OR setting preferredSize before displaying JFrame, then you didn't lay out your components well. – nullptr Nov 09 '14 at 07:16
  • @Meraman *"I saying about setting JFrame size of dimension I need.."* What size is that, exactly? And how do you adjust it for each OS (in which the frame decorations are **different sizes for each OS)?** But we could argue like this for an eternity. If you want to pursue it further, I suggest you post a question based on *'Why is setting frame sizes wrong?'* along with an example code of how you do it. – Andrew Thompson Nov 09 '14 at 07:20
  • @AndrewThompson LOL I will post question on it. – nullptr Nov 09 '14 at 07:22
  • @AndrewThompson I have posted question: http://stackoverflow.com/questions/26826365/why-setting-setpreferredsize-on-jframe-is-bad – nullptr Nov 09 '14 at 08:20
  • @MadProgrammer I have posted question here: http://stackoverflow.com/questions/26826365/why-setting-setpreferredsize-on-jframe-is-bad – nullptr Nov 09 '14 at 08:20
0

Use frame.setVisible(true) at the end of the main(String[]) method.Also,use frame.pack() at the end of the main(String[]) method after adding all the components to it.Your main method should be something like this:-

public static void main(String[]a){

JFrame frame = new JFrame(gamename + versionnumber);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(800,600);
frame.setLocationRelativeTo(null);


JPanel panel = new JPanel();
frame.add(panel);
JButton dig = new JButton("Dig");                           //Dig mechanic allows players to find things
JButton stickscounter = new JButton("Sticks: " + sticks);
JButton rockscounter = new JButton ("Rocks: " + rocks);
JButton logscounter = new JButton("logs" + logs);
JButton craft = new JButton("Craft");                       //uses things found by digging to create more advanced things
panel.add(dig);
panel.add(stickscounter);
panel.add(rockscounter);
panel.add(logscounter);
panel.add(craft);

dig.addActionListener( new ActionListener() {
    @Override
    public void actionPerformed( ActionEvent e ) {          

      dig();
    }
  });
 frame.add(panel);
 frame.pack();
 frame.setVisible(true);

}