0

I don't know if the title is correct, but what I want to do is to write a method that adds for example the rgb of a color to a combobox. Let's assume that we have 3 panels each one with different background color and each panel has its own combo box.

int p1RGB = (Panel1.getBackground()).getRGB();
    int p1Red = (p1RGB>>16)&0xFF;
    int p1Green = (p1RGB>>8)&0xFF;
    int p1Blue = p1RGB&0xFF;
    String p1RGBStr = String.valueOf(p1Red) +", "+String.valueOf(p1Green) +", "+ String.valueOf(p1Blue); 
    String[] c1Items = { hex1, p1RGBStr };
    DefaultComboBoxModel model1 = new DefaultComboBoxModel (c1Items);
    Combo1.setModel(model1);

Instead writing again this code for each panel can I write this in a way that it loops itself for each panel? I think there is something similar in javascript.

3 Answers 3

1

Let's assume that we have 3 panels each one with different background color and each panel has its own combo box.

You have a model: Panel + combo.

I would create custom class inherited from JPanel and create list of models. It will make code clearer.

public class MyPanel extends JPanel{/* */}

MainClass

List<MyPanel> listOfPanels = new ArrayList<MyPanel>(3);

for(MyPanel model : listOfPanels ){
  doStuff(model);
} 

private void doStuff(MyPanel model){/**/}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your response but I'm not allowed to use lists in my project!
So like I posted, create 3 classes anyways it will be easy to handle and to maintain
@neto3 You don't need a list to do this, Maxim's point is just that if you have 3 near-identical items then creating a class for them is the most convenient way.
1

If you're adverse to using a class, the other obvious way is to use a factory-type method.

JComboBox createComboBoxFor(int rgb) {
    return new JComboBox(new DefaultComboBoxModel(new String[] {
        Integer.toString(rgb, 16), // not sure what hex1 is
        (rgb >>> 16 & 0xFF) + ", " + (rgb >>> 8 & 0xFF) + ", " + (rgb & 0xFF)
    }));
}

Then you do

JComboBox panel1Box = createComboBoxFor(panel1.getBackground().getRGB());

Comments

0

If you put the Panels into an array and then looped through the array instead of specifying the specific Panel eg Panel1, Panel2

2 Comments

That's good idea and i'm going to use it! But i'm curious if there is another more appropriate way to do this!
Not that I can think of, if you're thinking of concatenating strings to get the variable you want eg "Panel" + num theres nothing like that similar to what you could find in JS. And if there was it would be pretty painful compared to just using an array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.