Reputation: 1113
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Dummy{
String newSelection = null;
public void init(){
JFrame jFrame = new JFrame("Something");
jFrame.setVisible(true);
jFrame.setSize(new Dimension(600, 600));
jFrame.setLayout(null);
jFrame.setBackground(Color.BLACK);
final String[] possibleNoOfPlayers = {"Two","Three"};
final JComboBox comboBox = new JComboBox(possibleNoOfPlayers);
newSelection = possibleNoOfPlayers[0];
comboBox.setPreferredSize(new Dimension(200,130));
comboBox.setLocation(new Point(200,200));
comboBox.setEditable(true);
comboBox.setSelectedIndex(0);
comboBox.setVisible(true);
comboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
JComboBox box = (JComboBox) actionEvent.getSource();
newSelection = (String) box.getSelectedItem();
System.out.println(newSelection);
}
});
jFrame.add(comboBox);
}
}
I am trying to add combo box to the frame. but it is not visible. if you click the position it will show the options. but it is not visible. Please let me know if i am missing something in it.
Upvotes: 2
Views: 6156
Reputation: 2224
use this one..
package oops;
import java.awt.BorderLayout;
public class jframe extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
jframe frame = new jframe();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public jframe() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JComboBox comboBox = new JComboBox();
comboBox.setBounds(159, 81, 189, 41);
contentPane.add(comboBox);
}
}
Upvotes: 1
Reputation: 347334
Three things...
setVisible
on you frame BEFORE you added itnull
layouts0x0
size. (ps- setPreferredSize
is not doing what you think it should)...Advisable solution...
Call setVisible
last and use an appropriate layout manager
Upvotes: 5