Simple Dropdown menu in Java

NoobNe0 picture NoobNe0 · Mar 19, 2014 · Viewed 75.3k times · Source

I am working on a very simple GUI in Java.

In this GUI I want to display:

  1. A label with some text on the top of the page
  2. A JComboBox under the mentioned label
  3. A JButton under the mentioned JComboBox

Here's my code:

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

public class Prova {

public static void main(String[] args) {

    JFrame frame = new JFrame("A Simple GUI");
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500, 500);
    frame.setLocation(430, 100);

    JPanel panel = new JPanel();

    frame.add(panel);

    JLabel lbl = new JLabel("Select one of the possible choices and click OK");
    lbl.setVisible(true);

    panel.add(lbl);

    String[] choices = { "CHOICE 1","CHOICE 2", "CHOICE 3","CHOICE 4","CHOICE 5","CHOICE 6"};

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

    cb.setVisible(true);
    panel.add(cb);

    JButton btn = new JButton("OK");
    panel.add(btn);

    }
}

Unfortunately, the result I get is

image

As you can see in the image, the label, the JComboBox and the JButton are on the same line!

Instead, I want them "stacked" as described above:

JLabel

JComboBox

JButton

I tried using the setLocation(int x, int y) method, but they always show in the same position.

Many thanks!

Answer

Nerakai picture Nerakai · Mar 19, 2014

use frame.setLayout(null); this will allow you to place the Label, Button etc. where you like