简体   繁体   English

更改JButton的文字或颜色而没有最终的?

[英]Changing JButton Text or color without final?

Hey all I can change the text of 1 single button easily with "final" but I need to create lots of buttons for a flight booking system, and when the buttons are more, final doesnt work ... 嘿,我可以通过“ final”轻松更改1个单个按钮的文本,但是我需要为航班预订系统创建许多按钮,而当按钮更多时,final不起作用...

JButton btnBookFlight;

eco = new EconomyClass();
eco.setSeats(5);
for(int i=0;i<20;i++){
    btnBookFlight = new JButton("Book" +i);
    btnBookFlight.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            btnBookFlight.setBackground(Color.RED);
            btnBookFlight.setOpaque(true);
            btnBookFlight.setText("Clicked");
        }
    });
    btnBookFlight.setBounds(77, 351, 100, 23);
    contentPane.add(btnBookFlight);
} 

I would be glad if you can suggest me any trick to get over this.I want to change a buttons color or text when it is clicked or maybe some other cool effects when mouse over but for now only text or color will be enough =).Thanks for your time! 如果您可以建议我克服任何麻烦,我将很高兴。我想在单击按钮时更改按钮的颜色或文本,或者在鼠标悬停时更改其他效果,但目前仅文本或颜色就足够了=) 。谢谢你的时间!

Use the source of the ActionEvent in the ActionListener ActionListener使用ActionEvent的源

btnBookFlight.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent event) {

      JButton button = (JButton)event.getSource();
      button.setBackground(Color.RED);
      ...
    }
});

btnBookFlight has to be final for the inner class ( ActionListener ) to access it. btnBookFlight必须是final用于内的类( ActionListener )来访问它。

From JLS 8.1.3 JLS 8.1.3起

Any local variable, formal parameter, or exception parameter used but not declared in an inner class must be declared final. 使用的但未在内部类中声明的任何局部变量,形式参数或异常参数必须声明为final。

If this is not permitted, then the JButton may be accessed using the source component of the ActionEvent itself using getSource . 如果不允许这样做,则可以使用ActionEvent本身的源组件(使用getSource)访问JButton

However, that said, the simplest solution would be to move the JButton declaration within the scope of the for loop and make it final : 但是,也就是说,最简单的解决方案是将JButton声明移至for循环的范围内并使其final

for (int i = 0; i < 20; i++) {
    final JButton btnBookFlight = new JButton("Book" + i);
    btnBookFlight.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            btnBookFlight.setBackground(Color.RED);
            ...
        }
    });
}

Just avoid using anonymous classes for your action listener and the final constraint will disappear. 只需避免为操作侦听器使用匿名类, final约束将消失。

What I mean is use: 我的意思是使用:

class MyActionListener implements ActionListener {
  public void actionPerformed(ActionEvent e) {
    JButton src = (JButton)e.getSource();
    // do what you want

  }
}

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

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