Java switch case not functioning as expected - java

I am a student of very basic Java. We did an assignment to make the background color change according to the radio button selected using several if statements. That worked fine. I decided to change the selection process to a combobox and use a switch case. It seems to me the process is failing the if statement in the switch case method. I'm trying to get a better understanding of how things work. The code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class Lab17_4combo extends JFrame implements ActionListener
{
Container container;
JComboBox colors;
public Lab17_4combo()
{
super("ComboBox ");
container = this.getContentPane();
container.setLayout(new FlowLayout());
setSize(300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String[] selectColor = {"Red", "Yellow", "Blue", "Green", "Magenta"};
JComboBox colors = new JComboBox(selectColor);
colors.setSelectedIndex(-1);
colors.addActionListener(this);
container.add(colors);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
int chgColor;
if(e.getSource() == colors)
{
chgColor = colors.getSelectedIndex();
switch(chgColor)
{
case 0:
container.setBackground(Color.red);
case 1:
container.setBackground(Color.yellow);
case 2:
container.setBackground(Color.blue);
case 3:
container.setBackground(Color.green);
case 4:
container.setBackground(Color.magenta);
}
}else
{
container.setBackground(Color.magenta);
}
}
public static void main(String[] args)
{
Lab17_4combo s = new Lab17_4combo();
}
}
I put in the else to check if it was failing the if. I'm assuming that is where the problem is, but I don't know how to fix it. Any help would be greatly appreciated. The original assignment has been completed, this is my own experimentation. I'm not asking for anyone to do my homework for me. Cheers
EDIT--
I have made the suggested changes to the code (Thanks to all for the suggestions). The background color of the container still does not change regardless of the selection I make from the combobox. I'm assuming there are mistakes elsewhere in the code, but I'm at a loss to find them. My expectation is that the background color of the container will change according to the selection I make from the combobox. This is not happening.
The revised code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
class Lab17_4combo extends JFrame implements ActionListener
{
Container container;
JComboBox colors;
public Lab17_4combo()
{
super("ComboBox ");
container = this.getContentPane();
container.setLayout(new FlowLayout());
setSize(300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String[] selectColor = {"Red", "Yellow", "Blue", "Green", "Magenta"};
JComboBox colors = new JComboBox(selectColor);
colors.setSelectedIndex(-1);
colors.addActionListener(this);
container.add(colors);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
int chgColor;
if(e.getSource() == colors)
{
chgColor = colors.getSelectedIndex();
switch(chgColor)
{
case 0:
container.setBackground(Color.red);
break;
case 1:
container.setBackground(Color.yellow);
break;
case 2:
container.setBackground(Color.blue);
break;
case 3:
container.setBackground(Color.green);
break;
case 4:
container.setBackground(Color.magenta);
break;
}
}
}
public static void main(String[] args)
{
Lab17_4combo s = new Lab17_4combo();
}
}
With my limited knowledge of Java I'm not able to see where the mistake(s) may be. Any help would be appreciated.Cheers

You forgot the break statement after each case
Try this:
switch(chgColor)
{
case 0:
container.setBackground(Color.red);
break;
case 1:
container.setBackground(Color.yellow);
break;
case 2:
container.setBackground(Color.blue);
break;
case 3:
container.setBackground(Color.green);
break;
case 4:
container.setBackground(Color.magenta);
break;
default:
//You may add a default case here.
}
EDIT:-
I think your condition
if(e.getSource() == colors)
is never true thats why you are getting this problem. You may try to compare like this:
if(e.getSource().equals(colors))
Always use .equals method when you are comparing objects.

As mentioned in my comment you forgot to add break in each of your case.
switch(chgColor)
{
case 0:
container.setBackground(Color.red);
break;
case 1:
container.setBackground(Color.yellow);
break;
case 2:
container.setBackground(Color.blue);
break;
case 3:
container.setBackground(Color.green);
break;
case 4:
container.setBackground(Color.magenta);
break;
default:
//What if none of above condition is satisfied.
}
Edit: - Check the comments in the code
class Lab17_4combo extends JFrame implements ActionListener
{
Container container;
JComboBox colors;// you declared colors.
public Lab17_4combo()
{
super("ComboBox ");
container = this.getContentPane();
container.setLayout(new FlowLayout());
setSize(300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String[] selectColor = {"Red", "Yellow", "Blue", "Green", "Magenta"};
//JComboBox colors = new JComboBox(selectColor);// You declared colors again. Change this line to
colors = new JComboBox(selectColor);
colors.setSelectedIndex(-1);
colors.addActionListener(this);
container.add(colors);
setVisible(true);
}

You should use break after each case.
case 0:
container.setBackground(Color.red);
break;
case 1:
container.setBackground(Color.yellow);
break;
....

You need to make sure and add a break; after every line in the case, like this:
switch(chgColor)
{
case 0:
container.setBackground(Color.red);
break;
case 1:
container.setBackground(Color.yellow);
break;
case 2:
container.setBackground(Color.blue);
break;
case 3:
container.setBackground(Color.green);
break;
case 4:
container.setBackground(Color.magenta);
break;
}
}else
{
container.setBackground(Color.magenta);
}

Looks like you always end up with magenta color given the if condition and the switch statement.
Use break for each case statement.
In the switch statement, for each case, you do not have a break;. So even if switch finds a valid matching case, it executes that case and, in your code (since you do not break the control to come out of that case), it eventually passes the control to the cases following the matching case and always ending up in the last case.

Related

Exit out of frame and create new frame?

switch(arg0.getKeyCode()) {
//if keycode is 'd' key
case 68:
break;
case 65:
System.out.println("stuff for left key using a");
break;
case 87:
shark.MoveUp();
break;
case 38:
shark.MoveUp();
break;
case 82:
new Game();
break;
}
So Game is the name of the class. This is not the JFrame. When I try calling the jframe, it does not recognize it. When I press "R", it creates a new game but it does not get rid of the old game. When the old game runs in the background, the new game becomes unplayable due to lag. How do I delete the old Game that is running and just run the new one I started in case 82?
i'd highly recommend on using JFrame.dispose() ONthe old Game as long as it expanding JFrame. If not you can add a method to the Game class that will dispose the JFrame it contains. A method as such will look like that:
JFrame frame = new JFrame("game");//Lets assume thats your frame in Game
//that should be your method inside of Game class:
public void gameDispose(){
if(frame != null)
frame.dispose();
}
Now the only problem you may be in is not being able to call this dispose method since your Game is not inside of a variable. Therefore when Game is created it should happen inside of a variable as follow:
Game g = new Game();//Just for understaning of g variable.
Later when needed call your method.
Therefor your code should look like this:
Game g = new Game();
switch(arg0.getKeyCode()) {
//if keycode is 'd' key
case 68:
break;
case 65:
System.out.println("stuff for left key using a");
break;
case 87:
shark.MoveUp();
break;
case 38:
shark.MoveUp();
break;
case 82:
g.dispose().
g = new Game()
break;
}

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!

Using jcombobox to return object or variable

I have 2 comboboxes and I need to make it so that when certain options are selected from the drop down list, certain results are outputted. How do I associate certain string variables or objects with multiple combobox selections. I'm not asking you to do my homework for me. Just need pointing in the right direction.
public class gui extends JFrame implements ActionListener{
String[] colour1 = {"red", "blue", "green", "orange", "brown","white", "black", "yellow", "purple", "pink"};
String[] colour2 = {"red", "blue", "green", "orange", "brown","white", "black", "yellow", "purple", "pink"};
JComboBox combo1 = new JComboBox(colour1);
JComboBox combo2 = new JComboBox(colour2);
JLabel message = new JLabel();
JFrame frame = new JFrame();
JPanel panel = new JPanel(new GridLayout(0, 1));
public gui() {
panel.add(combo1);
panel.add(combo2);
panel.add(message);
frame.add(panel);
}
I'm using actionPerformed to catch the users input, and then output specific results. At the moment it only takes the value of one combobox and outputs a string. How do i make it take 2.
public void actionPerformed(ActionEvent e){
if(e.getSource() == combo1){
JCombobox cb = (JComboBox)e.getSource();
String colours = (String) cb.getSelectedItem();
switch(colours){
case "red": message.setText("");
break;
case "blue": message.setText("");
break;
case "green": message.setText("");
break;
case "pink": message.setText("");
break;
case "purple":message.setText("");
break;
case "white": message.setText("");
break;
case "black": message.setText("");
break;
case "brown": message.setText("");
break;
case "orange": message.setText("");
break;
case "yellow": message.setText("");
break;
default: message.setText("");
}
}
}
As it was pointed out in the comments, you probably don't need both arrays. When both combo boxes should contain the same values, then you can pass the same array to both combo boxes.
The actual question seems to be aiming at how to perform a specific action depending on the combination of the selections of two combo boxes.
I think there are two options for this: You could either store the combo boxes as instance variables, or you could store the selections of the combo boxes as instance variables. Since you're already storing the combo boxes as instance variables, this should be the easier one to go here. So you could do something like this:
#Override
public void actionPerformed(ActionEvent e)
{
String color1 = (String)combo1.getSelectedItem();
String color2 = (String)combo2.getSelectedItem();
// Possibly check if either color is 'null' here
if (color1.equals("blue") && color2.equals("yellow"))
{
message.setText("green");
}
...
}
(Note: If you now intend to write a nested switch-statement like
switch(colour1)
{
case "red":
switch(colour2)
{
// 10 cases...
}
break;
// 10 x 10 cases...
}
you should think about a different approach, depending on what you want to do with these colors...)
What you want is display a Value depending on the selected Values of the two comboboxes. Make combo1 and combo2 private fields. Write a private method to respond to the action event of both combo. Switch on combo values. Note that you can access both combo directly because they are class fields

Switch statement in non-anonymous private OnClickListener class not working?

I've tried quite a few different tactics to achieve my desired result, but nothing is making these buttons do what they're 'sposed to... Basically I have 14 buttons. Four with the text "X", digitOne, digitTwo, digitThree and digitFour. Then, there are 10 with "1", "2", etc, named "one", "two", etc. All the buttons are tied to the same OnClickListener that will use a switch statement to determine which button was pressed, then find the soonest display button (buttons initially marked "X"), and change that buttons text to the entered digit. What I want to happen is:
Say someone clicks the "5" button. If its the first button pressed, the first "digit" button will change from displaying "X" to "5", and so-on, so-forth. This is not what is happening... In fact, nomatter what I've tried, nothing is happening. Not even an error... An error would be nice, at least I'd know where my logical flaw is -_-. Here's the code:
The button declarations:
one=(Button)findViewById(R.id.button1);
two=(Button)findViewById(R.id.Button2);
three=(Button)findViewById(R.id.Button3);
four=(Button)findViewById(R.id.Button4);
five=(Button)findViewById(R.id.Button5);
six=(Button)findViewById(R.id.Button6);
seven=(Button)findViewById(R.id.Button7);
eight=(Button)findViewById(R.id.Button8);
nine=(Button)findViewById(R.id.Button9);
zero=(Button)findViewById(R.id.Button0);
add=(Button)findViewById(R.id.buttonAdd);
digitOne=(Button)findViewById(R.id.Number1);
digitTwo=(Button)findViewById(R.id.Number2);
digitThree=(Button)findViewById(R.id.Number3);
digitFour=(Button)findViewById(R.id.Number4);
one.setOnClickListener(listener);
two.setOnClickListener(listener);
three.setOnClickListener(listener);
four.setOnClickListener(listener);
five.setOnClickListener(listener);
six.setOnClickListener(listener);
seven.setOnClickListener(listener);
eight.setOnClickListener(listener);
nine.setOnClickListener(listener);
zero.setOnClickListener(listener);
The OnClickListener private inner class (I guess that's what you'd call it. It's inside Activity class):
private OnClickListener listener = new OnClickListener(){
public void onClick(View button) {
switch(button.getId()){
case R.id.Button0:
addANumber(0);
break;
case R.id.button1:
addANumber(1);
break;
case R.id.Button2:
addANumber(2);
break;
case R.id.Button3:
addANumber(3);
break;
case R.id.Button4:
addANumber(4);
break;
case R.id.Button5:
addANumber(5);
break;
case R.id.Button6:
addANumber(6);
break;
case R.id.Button7:
addANumber(7);
break;
case R.id.Button8:
addANumber(8);
break;
case R.id.Button9:
addANumber(9);
break;
}
}
};
And finally, the "addANumber" method being called:
public void addANumber(int i){
if(digitOne.getText()=="X"){
digitOne.setText(i);
}else if(digitTwo.getText()=="X"){
digitTwo.setText(i);
}else if(digitThree.getText()=="X"){
digitThree.setText(i);
}else if(digitFour.getText()=="X"){
digitFour.setText(i);
}
}
I've done this before... I know I'm missing something so blatantly stupid it deserves a smack in the head...
Before all:
digitOne.getText()=="X" should be "X".equals(digitOne.getText())
you need checking for string equality in terms of content, not in term of reference.
Nothing happens because with == none of your if condition is evaluated to true and addANumber() simply results as an empty method

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