简体   繁体   中英

JFRAME, JPANEL. Making button and dropdown menu visible and on the right location

Im trying to create a simple welcome screen where the user can choose with how many cards he wants to play a memory game. On the top of the screen I want a text ( I created a JLabel for this). Below that I want a dropdown menu and to the right of this dropdown a button. The code I have so far doenst display anything when I run it (besides a empty JFrame). What am I doing wrong?

The code:

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

public class Main {

        public static void main(String[] args) {

            JFrame frame = new JFrame("Memory game");
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(500, 500);
            frame.setLocation(430, 100);
            frame.setLayout(null);

            JPanel panel = new JPanel();

            frame.add(panel);

            JLabel lbl = new JLabel("How many cards u want to play with?");
            lbl.setVisible(true);
            lbl.setLocation(150,150);
            panel.add(lbl);

            String[] choices = { "8","12", "16","20","24","28","32"};

            final JComboBox<String> cb = new JComboBox<String>(choices);

            cb.setVisible(true);
            cb.setLocation(200,150);
            panel.add(cb);

            JButton btn = new JButton("Start game");
            btn.setLocation(175,200);
            panel.add(btn);

        }

}

You would need to set the size of your panel. One way to do it:

    JPanel panel = new JPanel();
    panel.setSize(frame.getSize());
    frame.add(panel);

But using

frame.setLayout(null);

Will give you a lot of headache if you dont know what you are doing (if you had a layout, you wouldnt have had this problem). You should always use a layout. Have a look at the official Visual Guide to Layout Managers . Though there are more you can download from the web.

Also another advice: If you are just starting to learn how to build Desktop Applications, maybe you should skip swing and get to JavaFX directly. This will save you even more headache.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM