我有一个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(显然)......我怎样才能解决这个问题?
答案 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));
}