如何将未定义的Swing组件的属性传递给方法?

时间:2017-06-30 14:49:45

标签: java swing user-interface methods

我创建了一个方法:

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));
    }
}

将取一个gui组件(a)并放置它,取决于c,我希望它与B比较,但我不能得到:X,Y,宽度,高度和我用的其他所有东西实现这一点。

我想过使用一个新类,我会将Dimension和我发送给我方法的组件的Point点,但我不想在我问之前创建任何不必要的东西。

我还想过在我的方法中使用instanceof但是我需要为每个gui组件创建代码,所以我认为应该有一个更简单的方法。

所以我的问题是:是否有一个全局类,我可以发送给我的方法获取他们的Dimension和Point的每个gui组件?

如果没有,那么这样做的正确方法是什么?

这是我的主要:

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);
}  

注意:在我的例子中我发送2个JButton,我想要的不仅仅是JButton,我希望能够发送任何我想要的东西(只要它是一个gui comp),如JPanel,Checkbox或任何东西否则就可以使用了。

1 个答案:

答案 0 :(得分:1)

尝试更改:

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

为:

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

我还没有测试过,但是如果您要提供JLabelJPanelJButton这样的组件,它应该会有效。