简体   繁体   English

如何在jbutton中创建方法?

[英]How to make a method in a jbutton?

So, i made a button like this parameter nomor in LoadPlanet and LoadRR is parameter to show some data to textbox. 因此,我在LoadPlanet中LoadPlanet了一个类似于此参数nomor的按钮,并且LoadRR是用于向文本框显示一些数据的参数。 my code is like this the button appear correctly, but if i clicked the buttons, all of them show data from the last data which supposed to be data in last button. 我的代码是这样的,按钮正确显示,但是如果我单击按钮,它们全部显示来自最后一个数据的数据,这些数据应该是最后一个按钮中的数据。 -> a result from tblplanet.JmlPlanet() is 8, so the parameter was like LoadPlanet(8), so that every button show 8th data. ->来自tblplanet.JmlPlanet()的结果为8,因此参数类似于LoadPlanet(8),因此每个按钮都显示第8个数据。

my question is how to make the parameter in sequence, so the button can show data correctly? 我的问题是如何按顺序设置参数,以便按钮可以正确显示数据? Any ideas? 有任何想法吗?

public void createButton() {
    for (i = 0; i < tblplanet.JmlPlanet(); i++) {
        tblplanet.draw(i + 1);
        planet_name = tblplanet.getNama_planet();

        JButton PlanetJButton = new JButton();
        PlanetJButton.setBounds(10, 5 + (i * 35), 95, 26);
        PlanetJButton.setText(planet_name);
        PanelButton.add(PlanetJButton);

        PlanetJButton.addActionListener(
                new ActionListener() {

                    public void actionPerformed(ActionEvent event) {
                        for (int i = 0; i < tblplanet.JmlPlanet(); i++) {
                            nomor =  i;

                            LoadPlanet(nomor);
                            LoadRR(nomor);
                        }
                    }
                });
    }
}

Create a class which implements ActionListener and takes a parameter ( int ) of the planet that it represents 创建一个类,该类实现ActionListener并采用它表示的行星的参数( int

public class PlanetActionListener implements ActionListener {

    private final int planet;

    public PlanetActionListener(int planet) {
        this.planet = planet;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        LoadPlanet(planet);
        LoadRR(planet);
    }

}

Then simply add the ActionListener to your button 然后只需将ActionListener添加到您的按钮

PlanetJButton.addActionListener(new PlanetActionListener(i));

Depending on how you code is structured, you may need to make the PlanetActionListener an inner class so it can access the appropriate methods. 根据代码的结构方式,您可能需要使PlanetActionListener为内部类,以便它可以访问适当的方法。 See Nested Classes for more details 有关更多详细信息,请参见嵌套类

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

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