繁体   English   中英

对于 Java Swing,如何访问 (x,y) 处的元素?

[英]For Java Swing, how can I access the element at (x,y)?

假设声明的网格布局:

import java.awt.*;
import javax.swing.*;
import javax.swing.border.Border;

public class Main extends JFrame{
    public static void main(String args[]) {
        JFrame window = new JFrame();
        JButton[] b = new JButton[9];
        
        for(int i = 0; i < 9; i++) {
            b[i] = new JButton("Button " + i);
            window.add(b[i]);
        }
        
        window.setLayout(new GridLayout(3, 3));
        window.setVisible(true);
        window.setSize(300, 300);
        
    }
}

有没有办法访问(x,y)网格中的元素(在本例中为按钮)? 例如:我想访问 window(1,2) 以便获得 Button 5。

我想访问 window(1,2) 以便获得 Button 5。

做一些基本的数学运算。

您将网格定义为 3 列。

所以你的按钮的索引是:

int index = (row * columns) + column;
JButton button = b[index];

其中行 = 1,列 = 2

还:

for(int i = 0; i < 9; i++) {
    b[i] = new JButton("Button " + i);
    window.add(b[i]);
}
    
window.setLayout(new GridLayout(3, 3));
  1. 您应该在将组件添加到面板之前设置布局。
  2. 您应该使用new GridLayout(0, 3)来指定要在 3 列之后换行。 也就是说,无论您向网格添加多少组件,都会在 3 个组件之后换行

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM