JComboBox DropDown list is not displayed - java

this might be a duplicate of JComboBox popup menu not appearing , but as it is a rather old question and not been active for quite some time, plus all the answers were not solutions, that helped with my problem. Thus I decided to create a new question.
The Problem is as follows:
I got an application of a prior colleque, that does not work at my company anymore. Now I tried adding a JComboBox to a JPanel. The JCombobox is displayed as expected, but it behaves in the same way as described by Seth in his question:
1) The first click on the expand button does nothing. The second click highlights the contents of the box, but the popup still doesn't appear.
2) Once I've clicked the button and given it focus, up/down keystrokes cycle through the entries correctly.
I have broken down the code to what I think is the minimum of needed programming, to have the problem occur. (As one comment in the mentioned question mentioned to provide SSCCE, which never happened).
Now here is the code I can provide:
public static class CreateProjectDialog extends JFrame {
private Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
public CreateProjectDialog() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
int SZ_INCR = 1;
// Passe Fontgröße an Resolution an:
if (size.width > 1920) {
SZ_INCR = 2;
}
// Initialize Glass Layer
final JPanel panelGlass = (JPanel) getGlassPane();
panelGlass.setLayout(null);
panelGlass.setVisible(true);
private static JPanel licBorrowPanel = null;
licBorrowPanel = new JPanel();
licBorrowPanel.setBounds(0, 20, 1000, 500);
licBorrowPanel.setVisible(false);
licBorrowPanel.setBackground(Color.WHITE);
panelGlass.add(licBorrowPanel);
}
public static void main(String[] args) {
hauptFrame = new CreateProjectDialog();
}
public static void licenceBorrowDialog() {
int mainWidth = hauptFrame.getSize().width;
int mainHeight = hauptFrame.getSize().height;
// pick a Date
JComboBox dayList = new JComboBox();
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Calendar calToday = Calendar.getInstance();
Date dayToday = calToday.getTime();
int weekDay = calToday.get(Calendar.DAY_OF_WEEK);
String weekDayName = "";
for (int i = 1; i <= 22; i++){
dayToday.setDate(dayToday.getDate()+1);
weekDay = dayToday.getDay();
weekDayName = translateWeekDay(weekDay);
dayList.addItem(i + " day(s) until " + weekDayName + " " + df.format(dayToday));
}
dayList.setOpaque(true);
dayList.setSelectedIndex(2);
dayList.setBounds(mainWidth / 2 - (125*SZ_INCR), (165*SZ_INCR), (250*SZ_INCR), (100*SZ_INCR));
licBorrowPanel.add(dayList);
dayList.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
int numberOfDays;
JComboBox dl = (JComboBox)e.getSource();
numberOfDays = dl.getSelectedIndex()+1;
labelSelectedDate.setText("<HTML><BODY><b>Count of days: </b>" + numberOfDays + "</HTML></BODY>");
}
});
}
//Translate weekday int to name
public static String translateWeekDay(int day){
String retDay;
switch (day) {
case 0: retDay = "Monday";
break;
case 1: retDay = "Truesday";
break;
case 2: retDay = "Wednesday";
break;
case 3: retDay = "Thursday";
break;
case 4: retDay = "Friday";
break;
case 5: retDay = "Saturday";
break;
case 6: retDay = "Sunday";
break;
default: retDay = "Invalid day";
break;
}
return retDay;
}
}
I tried popoulating with more items (as proposed by jluzwick) to see, if the DropDown is simply hidden behind anything, but no.
I definitely have never used getRootPane() instead of getContentPane(), as suspected by Sehtim.
There is also JCombobox is not displayed , where the accepted answer is to set the setVisible(true) to the end of the constructor. I tried that and it did not change any behaviour in my case.
The question I need an answer to, is: How do I make the DropDown list visible, to enable the user to easily choose an entry?

Thanks MadProgrammer for the hint regarding the code not compiling - I found a solution and will provide it here for anyone having a similar issue.
The problem was a result of mixing heavy weight and light weight components (awt / swing).
This resulted in the light weight popup being used, which was then probably occluded by other components and thus not visible.
The solution ( if the mix of both heavy and light weight has to stay ) is to disable the light weight popup forcing the application to use a backup popup. This is done by replaceing the following line:
dayList.setSelectedIndex(2);
With this line:
dayList.setLightWeightPopupEnabled (false);
I found the solution here:
http://de.comp.lang.java.narkive.com/t2GPS9vy/jcombobox-poppt-nicht-auf

Related

How do I make a selected Combobox value display different text?

I am new to Java and couldn't find any answers for my problem that I was able to understand.
I want to make a selected value in my ComboBox change what text is displayed in the textfield.
For example, if the user selects an artist in the combobox, then the artists' albums are displayed in the textfield.
Any help is appreciated. Thanks!
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
String a = (String)jComboBox1.getSelectedItem();
int artists = 0;
switch (artists){
case 0: jTextField1.setText("Take Care, Nothing Was The Same, Views, More Life, Scorpion");
break;
case 1: jTextField1.setText("Stoney, Beerbongs & Bentleys");
break;
case 2: jTextField1.setText("One Love, Listen, Nothing But the Beat");
break;
case 3: jTextField1.setText("Ready for the Weekend, 18 Months, Motion");
break;
case 4: jTextField1.setText("Cole World: The Sideline Story, 2014 Forest Hills Drive, 4 Your Eyez Only");
break;
case 5: jTextField1.setText("My Beautiful Dark Twisted Fantasy, Yeezus, The Life of Pablo, ye");
break;
case 6: jTextField1.setText("Parachutes, a Rush of Blood to the Head, X&Y, Viva La Vida, Mylo Xyloto");
}
}
Here is a full working example:
import java.awt.GridLayout;
import javax.swing.*;
public class ChangeTextViaCheckbox extends JFrame {
public ChangeTextViaCheckbox() {
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(3, 1));
JCheckBox cb1 = new JCheckBox("Checkbox 1");
JCheckBox cb2 = new JCheckBox("Checkbox 2");
JTextField tf = new JTextField();
cb1.addActionListener(e -> tf.setText("CB 1 is active"));
cb2.addActionListener(e -> tf.setText("CB 2 is active"));
add(cb1);
add(cb2);
add(tf);
}
public static void main(String[] args) {
ChangeTextViaCheckbox frame = new ChangeTextViaCheckbox();
frame.pack();
}
}
The both ActionListener listen on a performed action. If thats the case, they set a new Text in the JTextField.
But it would be better, if you implement it via JRadioButton and a ButtonGroup. With this there can't be a multiple choice.
Your question is lacking details and examples, you should post the important parts of your code that you've already written, for example I have no idea now what [GUI] API are you using(for example swing or AWT), so I strongly advise you to edit your question and provide more details, but either way I'm going to give you a simple example.
I'm going to assume your using the swing api, but it shouldn't be that different if your using another GUI api (like AWT).
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SwingExample extends JFrame{
public SwingExample(){
String[] artists = {"artist1","artist2","artist3"};
Map<String,String> albumOfArtists = new HashMap<String,String>();
albumOfArtists.put("artist1","album1");
albumOfArtists.put("artist2","album2");
albumOfArtists.put("artist3","album3");
JComboBox combo1 = new JComboBox<String>(artists);
JTextField field1 = new JTextField();
//You implement an action listener to define what should be done when
//an user performs certain operation. An action event occurs,
//whenever an action is performed by the user. Examples: When the user
//clicks a button, chooses a menu item, presses Enter in a text field.
//add action listener to your combobox:
combo1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
String selectedString=(String)combo1.getSelectedItem();
field1.setText(albumOfArtists.get(selectedString));
//for example if you select artist1 then the text displayed in the text field is: album1
}
}
add(combo1);
add(field1);
}
private static void createAndShowGUI() {
JFrame frame = new CreateNewJTextField();
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
createAndShowGUI();
}
}
You can use switch() for your combobox. I've written a code which has the name defined to combobox as cb1. The getSelectedItem() method is used for cb1. You can define the corresponding command for each case (starting from index 0).
String a = (String)cb1.getSelectedItem();
int i = 0;
switch (i){
case 0:
break;
}
Make sure to end each case with break; or your code will execute repeatedly.
Now if the textfield you're using is t1 then the following code is generalised,
switch (i) {
case 0: t1.setText(<whatever you want to display>);
break;
}
Hope this helps.
Here's the revisited code:
String a = (String)cb1.getSelectedItem();
int i = 0;
switch(i){
case 0: t1.setText("Take Care, Nothing Was The Same, Views, More Life, Scorpion");
// for combobox option Drake index = 0
break;
case 1: t1.setText("Stoney, Beerbongs & Bentleys");
// for combobox option post_malone index = 1
break;
case 2: t1.setText("One Love, Listen, Nothing But the Beat");
// for combobox option david_guetta
break;
}
switch is a selection statement that successively tests the value of an expression against alist of integers or characters constants. When a match is found, the statements associated with that constant are executed. Here, the variable i is the expression(the option you choose from combobox) which is evaluated.
Hope this helps again!

SwingConstants has same int value for Bottom and East?

While trying to get the horizontal alignment of a given JLabel, i noticed that SwingConstants.TOP has the same numeric int value as SwingConstants.NORTH (both are 1), but SwingConstants.BOTTOM has the same int value SwingConstants.EAST (both 3) instead of SwingConstants.SOUTH (5) !
if (c instanceof JLabel) {
JLabel tempLabel = (JLabel) c;
//for meaning of values see javax.swing.SwingConstants.
switch (tempLabel.getVerticalAlignment()) {
case 0:
output = VERTICAL_ALIGNMENT.CENTER;
break;
case 1:
output = VERTICAL_ALIGNMENT.TOP;
break;
case 3: //Bottom but also east instead of south!
output = VERTICAL_ALIGNMENT.BOTTOM;
break;
default:
//use default value setting
}
}
I wanted to make cases for all lower vertical alignments to (be it BOTTOM, SOUTH, SOUTH_EAST, SOUTH_WEST) to return VERTICAL_ALIGNMENT.BOTTOM - but the int values of those constants do not have the expected consistency. How can i solve this best, and maybe also why are they defined in this strange way?

Java - Passing a button click from one class to the main class

Firstly I am sure there is an answer lurking in this site and I did try and look but all the methods I tried continuously failed. I am still quite new at programming in Java so go easy on me, because what you are about to witness is some incredibly bodged code!
I am trying to learn Selenium, but before I write tests I wanted to make a simple IDE that asks what browser you'd like to run and what test you'd like to run. So far I had it running fine in a pop up for the browser but that wasn't useful if I wanted to add more options. So I am now trying to create a Jframe in my main class containing other classes which contain the content of any buttons I wish to add. Here is where things go wrong.
I have a combo box, this takes in a string of possible browsers and you pick one. (That works)
There is also a button which can read the current choice in the combo box. However this button does not seem to be passing the information back to my main class. I will post the code below.
CLASS 1 (MAIN)
public class DynamicBrowsers {
public static void main(String[] args) {
BrowserBox b = new BrowserBox();
JFrame IDE = new JFrame("IDE");
IDE.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BrowserBox newContentPane = new BrowserBox();
IDE.setContentPane(newContentPane);
IDE.setPreferredSize(new Dimension(200, 100));
IDE.pack();
IDE.setVisible(true);
WebDriver driver = null;
if(b.browserValue == 0){
//driver=new FirefoxDriver();
System.out.println("No browser Selected");
}else if(b.browserValue == 1){
driver = new ChromeDriver();
System.out.println("FF!");
}else if(b.browserValue == 2){
driver = new ChromeDriver();
System.out.println("Chrome!");
}else if(b.browserValue == 3){
driver = new InternetExplorerDriver();
System.out.println("IE!");
}
}
}
CLASS 2 (combo box and button)
public class BrowserBox extends JPanel {
public String browserPick;
String[] browsers = {"Please Select a Browser","Mozilla", "Chrome", "IE"};
public int browserValue = 0;
JButton runButton = new JButton("Run Test");
public JComboBox browserPicker = new JComboBox(browsers);
public BrowserBox() {
add(runButton);
add(browserPicker);
ActionListener cbActionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent listChoice) {
String s = (String) browserPicker.getSelectedItem();//get the selected item
switch (s) {//check for a match
case "Please Select a Browser":
System.out.println(browserPick);
break;
case "Mozilla":
browserPick = "Mozilla";
System.out.println("Could have been a worse choice than " + browserPick);
break;
case "Chrome":
browserPick = "Chrome";
System.out.println("Good choice picking " + browserPick);
break;
case "IE":
browserPick = "IE";
System.out.println("For some reason you chose " + browserPick);
break;
default:
browserPick= "Please Select a Browser";
System.out.println("No match selected, defaulting too " + browserPick);
break;
}
}
};
ActionListener bActionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent runClicked) {
if (browserPick == "Mozilla"){
browserValue = 1;
System.out.println("FF clicked " + browserValue);
}
else if (browserPick == "Chrome"){
browserValue = 2;
System.out.println("Chrome clicked " + browserValue);
}
else if (browserPick == "IE"){
browserValue = 3;
System.out.println("IE clicked " + browserValue);
}
}
};
browserPicker.addActionListener(cbActionListener);
runButton.addActionListener(bActionListener);
}
}
I imagine I am implementing it all wrong. I kind of feel like I should have made the button a seperate class or in the main class, but I'm unsure. If anyone could point me in the right direction, point out what I'm doing wrong and if possible offer a simple fix that would be great.
Thank you,
Farrell
There are a couple of things wrong here.
You declare two vars of type BrowserBox -- you use one and test the other (b and newContentPane).
You also use "==" to test whether one string is equal to another. That won't work in the general case; you need to use "String".equals(value) or some other form of the equals() method.
Good luck.
Unbelievable, It seems I had forgotten to capitalise the C in chrome at one point in a string compare and that is what cost me 2 hours of my life lol.
Thank you all for the input, now that I've worked out what was wrong I'm going to go back and try make it more object orientated by having only the JFrame in the main class. Ty again

Type of an ArrayList for Combobox and TextFields

I have an ArrayList<JTextField> that has N positions. However, I have to make a change, I need to add a JComboBox to that array so my question is:
What type of data do I need to declare on my ArrayList?
I've tryed with an ArrayList<Object> and ArrayList<JComponent> but it doesn't work because the lines, where I set the horizontal alignment report errors.
private ArrayList<JTextField> jTextFieldAL;
for (int i = 0; i < size; i++) {
jLabelAL.add(new JLabel("" + tagNamesAL.get(i)));
if (tagNamesAL.get(i).equals("AGENT_NAME")) {
jTextFieldAL.add(new tools.AgentNameTextField());
jTextFieldAL.get(i).setHorizontalAlignment(SwingConstants.RIGHT);
} else {
switch (tagContentAL.get(i).toString().toLowerCase()) {
case "int":
jTextFieldAL.add(new tools.IntegerTextField(this.simul));
jTextFieldAL.get(i).setHorizontalAlignment(SwingConstants.RIGHT);
break;
case "double":
case "float":
jTextFieldAL.add(new tools.DoubleTextField(this.simul));
jTextFieldAL.get(i).setHorizontalAlignment(SwingConstants.RIGHT);
break;
default:
jTextFieldAL.add(new JTextField());
jTextFieldAL.get(i).setHorizontalAlignment(SwingConstants.RIGHT);
break;
}
}
jTextFieldAL.get(i).addKeyListener(keyEvent);
p1.add(jLabelAL.get(i));
p1.add(jTextFieldAL.get(i));
}
I've tryed with an ArrayList and ArrayList but it doesn't work because the lines, where I set the horizontal alignment report errors : this is expected because Object/JComponent does not have setHorizontalAlignment method.
So you need to down caste it to JTextField and than call this API.
I am not sure if this is a good idea to use, as to down caste the object, you need to know at each index what type is the actual type of the object stored(JTextFild or JComboBox), otherwise you will land up with ClassCasteException.
I've found a solution to my problem. I don't need to add the ComboBox to the ArrayList. I just add the ComboBox directy to the panel.
Like this:
for (int i = 0; i < size; i++) {
jLabelAL.add(new JLabel("" + tagNamesAL.get(i)));
if (tagNamesAL.get(i).equals("BEHAVIOUR")){
addCSPComboBox(p1);
break;
}
And the addCSPComboBox method:
public void addCSPComboBox(JPanel p1){
CSPComboBox cspComboBox = new tools.CSPComboBox();
JLabel behaviour = new JLabel("BEHAVIOUR");
p1.add(behaviour);
p1.add(cspComboBox);
}
This works just fine for my problem. I hope I can help anyone with the same problem ;)

Java: GridLayout cells appear to merge

First, I am new to programming and this is my first major assignment in java and programming in general so if I am doing some incredibly stupid please tell me so I can correct the bad habit.
Anyway to the problem, I am currently trying to create a gridLayout that has a variable number of rows which will be filled with a label that has text that comes from a file. My problem is specifically on gridLayout were the labels that I do add and are constants seem to be disappearing into one giant cell. So far none of the reasearch I have done has lead to anything so I thought I may as well pose the question.
public void fillTimetablePane(JPanel pane){
int noOfRows = pref.getNoOFPeriods()+1;
pane.setLayout(new GridLayout(noOfRows,4));
pane.setBorder(BorderFactory.createLineBorder(Color.black));
JLabel label = new JLabel();
int i=0;
while (i<4){
switch (i) {
case 0: label.setText("Lesson");
break;
case 1: label.setText("Period");
break;
case 2: label.setText("Room");
break;
case 3: label.setText("Teacher");
break;
}
i++;
pane.add(label);
}
}
here is an image of what happens when I add run the following code:
http://www.freeimagehosting.net/1hqn2
public void fillTimetablePane(JPanel pane){
int noOfRows = pref.getNoOFPeriods()+1;
pane.setLayout(new GridLayout(noOfRows,4));
pane.setBorder(BorderFactory.createLineBorder(Color.black));
//JLabel label = new JLabel(); // from here
int i=0; // V
while (i<4){ // V
JLabel label = new JLabel(); // to here
switch (i) {
case 0: label.setText("Lesson");
break;
case 1: label.setText("Period");
break;
case 2: label.setText("Room");
break;
case 3: label.setText("Teacher");
break;
}
i++;
pane.add(label);
}
}
Ok, why is it not working in your case but works fine in my case? The problem is that you add your label 4 times and change the text inbetween. In a Layout, a single component can only be existing once. So what happens is that when you add your label a second/third/fourth time, its location in the grid will be updated and not added again.
In my case, I actually create a new JLabel in every iteration of the loop and therefore adding a different label to the JPanel.
Hope this is clear enough. Just ask if something is not clear.
You added the same label 4 times. Move the new JLabel inside your while loop

Categories

Resources