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

时间:2015-04-22 02:16:50

标签: java swing jpanel components jbutton

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

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的组件时访问JButtons的属性(Border)

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

我得到的错误是Component没有BorderProperty(显然)......我怎样才能解决这个问题?

2 个答案:

答案 0 :(得分:1)

你应该使用更像......

的东西
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));
    }
}

答案 1 :(得分:1)

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