Xaralabos Nikolaidhs
Xaralabos Nikolaidhs

Reputation: 49

How to pass the properties of an undefined Swing component to a method?

I have created a method:

static void align (Object a, Object b, int c){ //this needs fix
    if (c == 1){
       /* PLACED BELOW */ a.setLocation(b.getX()+( (b.getWidth()- a.getWidth())/2) , b.getY()+b.getHeight()+10);
    }
    else if (c == 2){
        /* PLACED ABOVE */ a.setLocation(b.getX()+(  (b.getWidth()- a.getWidth())/2) , b.getY()-a.getHeight()-10);
    }
    else if (c == 3){
        /* PLACED NEXT TO (LEFT) */ a.setLocation( b.getX()-a.getWidth() , b.getY()-((a.getHeight()-b.getHeight())/2));
    }
    else if (c == 4){
        /* PLACED NEXT TO (RIGHT) */ a.setLocation( b.getX()+b.getWidth(), b.getY()-((a.getHeight()-b.getHeight())/2));
    }
}

which would take a gui component (a) and place it, depending on c, where I want it to compare to B, BUT I can't get the: X,Y, Width, Height and everything else I use to make that happen.

I thought of using a new class which I would have the Dimension and the Point of the component I send to my method but I don't want to create anything unnecessary before I ask.

I also thought of using instanceof inside my method but iI would need to create code for each gui component there is, so i thought there should be a easier way.

So my question is: is there, like, a global class for every gui component I could send to my method to get their Dimension and Point?

If not, what would be the right way of doing this?

This is my Main:

public static void main(String[] args) throws IOException {

    int frame1w = 600;
    int frame1h = 400;

    JFrame frame1 = new JFrame("Foo");
    frame1.setSize(frame1w, frame1h);
    frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel contentPane = new JPanel();
    contentPane.setBackground(Color.WHITE);
    contentPane.setLayout(null);
    frame1.setContentPane(contentPane);

    JButton button1 = new JButton("B");
    button1.setSize(button1.getPreferredSize());
    button1.setLocation(100, 150); 
    contentPane.add(button1);

    JButton button2 = new JButton("A");
    button1.setSize(button1.getPreferredSize());
    contentPane.add(button1);

    align(button2, button1 ,1); 
    frame1.setVisible(true);
}  

NOTE: on my example I send 2 JButtons, what I want though isn't just for JButton, I want to be able to send anything I want (as long as it is a gui comp) like JPanel, Checkbox or anything else there is to use.

Upvotes: 0

Views: 54

Answers (1)

user7627726
user7627726

Reputation:

Try changing:

static void align (Object a, Object b, int c) { //this needs fix

to:

static void align (JComponent a, JComponent b, int c) {

I haven't tested it, but if you are giving a component such as a JLabel, JPanel, or JButton, it should work.

Upvotes: 1

Related Questions