Resolving errors with comboboxes instance variables

Previously, I had double declared combobox object variables.  I then declared them as private variables cb1,cb2 and removed the double declaration.  This worked well with the sample program.  However, when I do this to my class this created a few errors of the same vaiables that I cannot resolve including the private declaration.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;

public class HelloWorld {

	private JCombobox cb1, cb2;
	
	public static void main(String[] args) {
		// START ComboBox Image Setup
	       ImageIcon[] images;
			String[] comboStrings = {"create new po", "browse and select"};
	        images = new ImageIcon[comboStrings.length];	//array size
	        Integer[] intArray = new Integer[comboStrings.length];
	        ComboBoxRenderer renderer= new ComboBoxRenderer();
	        for (int i = 0; i < comboStrings.length; i++) {
	            intArray[i] = new Integer(i);
	            images[i] = renderer.createImageIcon("images/" + comboStrings[i] + ".jpg");  // creates image; send path

	            Image img = images[i].getImage();	// scales image size   
	            Image newimg = img.getScaledInstance(30,30, java.awt.Image.SCALE_SMOOTH);
	            images[i] = new ImageIcon(newimg);
	                        
	            if (images[i] != null) {  // sets image description
	                images[i].setDescription(comboStrings[i]);
	            }
	        }
	     // END ComboBox Image Setup

	        cb1 = new JComboBox(images);
	        cb1.setRenderer(renderer);  // displays image description
	        cb1.setMaximumRowCount(2);

	        String[] xxx = {"1111111111", "222"};
	        cb2 = new JComboBox(xxx);

	        ClickListener cl = new ClickListener();
	        cb1.addActionListener(cl);
	        cb2.addActionListener(cl);

	        JFrame f = new JFrame("teerer");
	        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	        JPanel p = new JPanel();

	        p.add(cb1);
	        p.add(cb2);
	        f.add(p);
	        f.setSize(300, 300);
	        f.setVisible(true);
	}
	  private class ClickListener implements ActionListener {

		    public void actionPerformed(ActionEvent e) {
//				System.out.println(e.getSource().equals(cb1));
				if (e.getSource().equals(cb1)) {
			          System.out.println("You've seleccted - cb1");
				}
			  	if (e.getSource().equals(cb2)) {
			          System.out.println("You've seleccted - cb2");
			  	}
			  	if(cb1.getSelectedItem().equals("1111")) {
			  		System.out.println("or right "+cb1.getSelectedItem());
			  		
			  	}
		    }
		  }
}

Open in new window

Vanavah EdwardsAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

for_yanCommented:

private JCombobox cb1, cb2;


should be upper case:

private JComboBox cb1, cb2;
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
for_yanCommented:
What are the errors?

Or post ComboBoxRenderer - otherwise  I cannot compile it

0
for_yanCommented:

You should make them static in your case - in general that is not good way to do thinsg
private static JComboBox cb1, cb2;
0
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

for_yanCommented:
So it complains that you are using cb1 , cb2 nono-statoc variables inside method static main()

You can avouid this immedaiately by decalring cb1 and cb2 static
0
for_yanCommented:
In general it is definitely bad practice to do all that stuff in method main()
0
for_yanCommented:
Waht you should do - you should make a class which extends JFrame, then  instatiate, bulild and place all your elements in the
constructor of this class.

Then  usually the only styatement  you will have in main() would be  

new  MyClassExtendingJFrame();

That would be much more reasonabnle way
and woill not cause any issues with static variables in main()
0
for_yanCommented:
Each static varaibale is unique for the whole class

Instance variable exists within every instance - and its value in one instance may be different
than in another isntance.

static method  is static because it does not ddpend on any istance - therefore it is claaed with reference
only to class as a whole not to any instance - MyClass.myStaticMethod()

as ooppose to instance method which is invoked on specific instance:

MyClass instanceOfMyClass = new MyClass();
instanceOfMyClass.myInstanceMethod();

therefore static method cannot depden on the instance variables - as it should give
teh saem result for given class and is not specific to any instance

therefore you cannot use instance varaibnles within the body of your static method.

method main() is static ----> youcannot use instance variables within the main() method

That was the reason for your compiler errors



 
0
Vanavah EdwardsAuthor Commented:
You suggest is correct.  I tried them and all the errors disappear as you said but now it come up with a fatal error "java.lang.NoSuchMethodError: main
Exception in thread "main" "
I even removed the image part to make it easier but still the same problem
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;

public class HelloWorld {

	private static JComboBox cb1, cb2;
	
	public void main(String[] args) {

			String[] aaa = {"aaa", "bbb", "ccc"};
			cb1 = new JComboBox(aaa);
//	        cb1.setRenderer(renderer);  // displays image description
//	        cb1.setMaximumRowCount(2);

	        String[] xxx = {"1111111111", "222"};
	        cb2 = new JComboBox(xxx);

	        ClickListener cl = new ClickListener();
	        cb1.addActionListener(cl);
	        cb2.addActionListener(cl);

	        JFrame f = new JFrame("teerer");
	        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	        JPanel p = new JPanel();

	        p.add(cb1);
	        p.add(cb2);
	        f.add(p);
	        f.setSize(300, 300);
	        f.setVisible(true);
	}
	  private class ClickListener implements ActionListener {

		    public void actionPerformed(ActionEvent e) {
//				System.out.println(e.getSource().equals(cb1));
				if (e.getSource().equals(cb1)) {
			          System.out.println("You've seleccted - cb1");
				}
			  	if (e.getSource().equals(cb2)) {
			          System.out.println("You've seleccted - cb2");
			  	}
			  	if(cb1.getSelectedItem().equals("1111")) {
			  		System.out.println("or right "+cb1.getSelectedItem());
			  		
			  	}
		    }
		  }
}

Open in new window

0
for_yanCommented:
I did not tell you to make main() non- static

      public void main(String[] args) {


you MUST have main() static:

public  static void main(String[] args) {


0
Vanavah EdwardsAuthor Commented:
I accidentally changed that but chagned it back.  However, after I did that the attached line of code comes up with this error "No enclosing instance of type HelloWorld is accessible. Must qualify the allocation with an enclosing instance of type HelloWorld (e.g. x.new A() where x is an instance of HelloWorld)."

ClickListener cl = new ClickListener();

Open in new window

0
for_yanCommented:
change this:
private class ClickListener implements ActionListener


to this:

 private static class ClickListener implements ActionListener
0
for_yanCommented:
so make your inner class static

Once again, as I told you all this is incorrect approach.

You shoudl craete all your elements and listemers etc in constructor of the
class which extends JFrame

Method main() should usually conatins only  few lines and careate instance of  your class
new FrameClassname();  
Then you would not have all these problems and that would be much more logiacal
0
for_yanCommented:
It is actually very simple - take one simple application as an example and
just do mostly all using taht template - modify only what you actually need to modify, when you need some difference in functionality -
but the prats which finction the sesame, like window creation, population
of top-level windows with elements, etc. will follwo the same pattern,  then you'll not be inventing every time
stuff and will avoid all these weird situations where all that stuff is created in main() like here,  or when you
write something liike cb1.main(),  like yesterday, or any other weird stuff.
There is definitely no reasion to invent these things every time.
0
for_yanCommented:

This is very basic template which should work for you for 90% simple applications:

Use it and you'll never have these kind of problems with static main, etc.

public class MyFrame extends JFrame implements ActionListener {

private JComboBox cb1;
private JTextField tf;

public MyFrame(...) {
super("My Frame");

tf = new JTextField(10);
cb1 = JComboBox(..);
cb1.addActionListener(this);

JLabel lbl = new JLabel("tratatat");

....

//set layouts, carete panels, populate panels, add papnels to top window, specify size of window, make it all visible
this.setVisible(true);

}  // end of constructor


public void myMtehod(...) {

// some methods 

}

public void actionPerformed (ActionEvent ae) {
if(ae.getSource().equals(cb1)){

// handle evbent

}

public static void main(String [] args){
//perhaps read some paerameters form args or from user input

new MyFrame(soe parameters here...);

}


}

Open in new window







0
Vanavah EdwardsAuthor Commented:
I was checking it.  It works perfect.  I have to check and see if I receive more messages from you.  Thanks for your patients and talent.  I will check my messages and award you and post more problems now.
0
for_yanCommented:

  And of course remove that:
      if(cb1.getSelectedItem().equals("1111")) {

I alreday explained to you that cb1 is an object of type JComboBox
"1111" is obnject of type String

they cannot be equal - and makes no sense to caompare them
0
Vanavah EdwardsAuthor Commented:
prompt, fast, understands problems well, can read java code very, very quickly, gives suggestions, gives code examples, direct users to the site with documents of solutions, patient, offers multiple solutions
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.