我创建了一个方法:
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、宽度、高度以及我用来的其他所有内容让这一切发生。
我想使用一个新类,我将把组件的维度和点发送到我的方法,但我不想在提出要求之前创建任何不必要的东西。
我还考虑过在我的方法中使用instanceof,但是我需要为每个gui组件创建代码,所以我认为应该有一种更简单的方法。
所以我的问题是:对于我可以发送到我的方法以获取其维度和点的每个 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 或任何内容否则还有用。
最佳答案
尝试改变:
static void align (Object a, Object b, int c) { //this needs fix
至:
static void align (JComponent a, JComponent b, int c) {
我还没有测试过它,但如果您提供诸如 JLabel
、JPanel
或 JButton
之类的组件,它应该工作。
关于java - 如何将未定义的 Swing 组件的属性传递给方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44849251/