在 JPanel.getComponents() 中循环时如何获取 JButton 属性

How to get JButton properties when looping inside a JPanel.getComponents()

我有一个 JPanel,其中填充了 JButton。

void addMealsMenuBarTitles() {

    JToggleButton test;
    int i=0;

    for (Categoria c: categories.categorias) {
        test = new JToggleButton(c.categoria);
        test.setForeground(Color.white);
        test.setBackground(new Color(52, 152, 219));
        test.setSize(new Dimension(menuMealsBar.getWidth()/categories.categorias.size(), menuMealsBar.getHeight()));
        test.setLocation(i++*(test.getWidth()), 0);
        menuMealsBar.add(test);
    }

}

我想做的是在遍历 JPanel 的组件时访问 JButton 的属性(边框)

void addClickEventCategories() {
    for (Component jtb: menuMealsBar.getComponents())

        jtb.addMouseListener(new MouseListener() {

        @Override
        public void mouseClicked(MouseEvent e) {
            //jtb.setBorder(BorderFactory.createMatteBorder(0, 0, 5, 0, Color.white));
        }

        @Override public void mousePressed(MouseEvent e) {}

        @Override public void mouseReleased(MouseEvent e) {}

        @Override public void mouseEntered(MouseEvent e) {}

        @Override public void mouseExited(MouseEvent e) {}
    });
}

我得到的错误是组件没有 BorderProperty(显然)...我该如何解决这个问题?

您可能应该使用更像...

for (Component comp: menuMealsBar.getComponents()) {
    if (comp instanceof JToggleButton) {
         JToggleButton jtb = (JToggleButton)comp;

因为您不应该假设容器实际包含什么(很多时候您会感到惊讶;))

另一个解决方案可能是在 mouseClicked 方法中做类似的事情

@Override
public void mouseClicked(MouseEvent e) {
    Component comp = e.getComponent();
    if (comp instanceof JToggleButton) {
        JToggleButton jtb = (JToggleButton)comp;
        jtb.setBorder(BorderFactory.createMatteBorder(0, 0, 5, 0, Color.white));
    }
}
    @Override
    public void mouseClicked(MouseEvent e) {
        //jtb.setBorder(BorderFactory.createMatteBorder(0, 0, 5, 0, Color.white));
    }

您可以从 MouseEvent 获取组件:

    @Override
    public void mouseClicked(MouseEvent e) {
        JToggleButton button = (JToggleButton)e.getSource();
        button.setBorder(BorderFactory.createMatteBorder(0, 0, 5, 0, Color.white));
    }