简体   繁体   English

摇摆Java ActionListener

[英]Swing Java ActionListener

I have been trying to show a message on the Frame saying that "Car is selected " After the I press the button OK ; 我一直试图在框架上显示一条消息,说“已选择汽车”。 i have been trying to fix this problem buti dont know how to can anyone please help me ? 我一直在尝试解决此问题,但我不知道该如何帮助任何人?

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class SelectWindow extends JFrame implements ItemListener {

    public static void main(String[] args) {
        new SelectWindow();
    }
    Map<String, String[]> cars = new HashMap<String, String[]>();
    JComboBox brands;
    JComboBox models;

    public SelectWindow() {
        initCars();
        setTitle("Select a car");
        brands = new JComboBox();
        brands.addItem("<none>");
        for (String brand : cars.keySet()) {
            brands.addItem(brand);
        }
        brands.addItemListener(this);
        models = new JComboBox();
        models.setEnabled(false);
        models.addItemListener(this);
        Container c = getContentPane();
        c.setLayout(new FlowLayout());
        c.add(new JLabel("Select a brand: "));
        c.add(brands);
        c.add(new JLabel("Select a model: "));
        c.add(models);
        c.add(new JButton("OK"));
        setVisible(true);
    }

    @Override
    public void itemStateChanged(ItemEvent e) {
        if (e.getSource() == brands && e.getStateChange() == ItemEvent.SELECTED) {
            String[] items = cars.get(e.getItem());
            if (items == null) {
                models.removeAllItems();
                models.setEnabled(false);
            } else {
                models.removeAllItems();
                models.addItem("<none>");
                for (String item : items) {
                    models.addItem(item);
                }
                models.setEnabled(true);
            }
            JLabel texte = new JLabel("car was selected");
            JButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    texte.setVisible(true);
                }
            });
        }
    }

    private void initCars() {
        cars.put("Renault", new String[]{
            "Twingo", "Clio", "Modus", "Kangoo",
            "Mégane", "Sénic", "Laguna", "Expace"});
        cars.put("Peugeot", new String[]{
            "107", "206", "207", "308", "407",
            "508", "607"});
        cars.put("Citroën", new String[]{
            "C1", "C3", "C4 Picasso", "C5", "C6", "C8",
            "Berlingo", "DS3"});
    }
}

Start by taking a look at How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listener 首先看一下如何使用按钮,复选框和单选按钮以及如何编写动作侦听器

Buttons provide notification via ActionListener s. 按钮通过ActionListener提供通知。 You need to register an instance of ActionListener with your button and perform your required actions within it 您需要使用按钮注册一个ActionListener实例,并在其中执行所需的操作

On a slightly more advance topic, but a worth while read How to Use Actions which provides a self contained ActionListener which also carries the configuration information which can be used by buttons, including menu items, and key bindings 关于一个稍微高级的主题,但值得一读的是如何使用操作 ,它提供了一个自包含的ActionListener ,还包含配置信息,按钮可以使用这些配置信息,包括菜单项和按键绑定

This... 这个...

JLabel texte = new JLabel("car was selected");
JButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        texte.setVisible(true);
    }
});

Isn't going to work for two reasons; 不能工作有两个原因;

  1. JButton does not provide a static method addActionListener , so this won't compile... JButton没有提供static方法addActionListener ,因此将无法编译...
  2. texte hasn't been added to anything, so trying to make it visible won't work... texte尚未添加到任何内容,因此尝试使其不可见...

Personally, I would initialise this in along with the rest of UI... 就个人而言,我将与其他UI一起初始化。

JLabel texte = new JLabel("car was selected");
JButton btn = new JButton("OK");
btn.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        texte.setVisible(true);
    }
});
c.add(btn);
c.add(texte);

Now, you could use your itemStateChanged method to enabled/disable the button, but you would need to make btn an instance variable... 现在,您可以使用itemStateChanged方法启用/禁用按钮,但是您需要使btn成为实例变量...

public class SelectWindow extends JFrame implements ItemListener {
    //...
    private JButton okBtn;
    //...
    public SelectWindow() {
        //...
        okBtn = new JButton("OK");
        okBtn.addActionListener(new ActionListener() {
            //...
        });
        c.add(okBtn);
        //...

This would allow you to change the state of the button in the itemStateChanged 这将允许您更改itemStateChanged按钮的itemStateChanged

public void itemStateChanged(ItemEvent e) {
    //...
    okBtn.setEnabled(...);

For example... 例如...

...Side notes and comments... 侧面注释和评论

  • Generally, it's discouraged to extend from top level containers, like JFrame and instead use a more common level container like JPanel . 通常,不建议从顶级容器(如JFrame扩展,而改用更常见的一级容器(如JPanel This increases the re-usability of you UI, as you're not locking yourself into a single top level container and you can decided when and how your component show be used, for example... 这样可以提高UI的可重用性,因为您不会将自己锁定在单个顶级容器中,并且可以决定何时以及如何使用组件显示,例如...

There is no response on the button because you did not have a reference on it you just add to the Frame without having a reference on it; 该按钮上没有任何响应,因为您没有对它的引用,只是将其添加到“框架”而不对其进行引用。

problem: 问题:

c.add(new JButton("OK")); //wont have any reference

solution

 button = new JButton("OK")
 c.add(button );

where button is a global variable . 其中button全局变量

and in your itemStateChanged method changed the 并在您的itemStateChanged方法中更改了

JButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                }
            });

to

button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
            }
        });

To register your global reference of button's actionListener 注册按钮的actionListener的全局引用

I've modified your code and it works now 我已经修改了您的代码,现在可以使用了

 import java.awt.Container;
 import java.awt.FlowLayout;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 import java.awt.event.ItemEvent;
 import java.awt.event.ItemListener;
 import java.util.HashMap;
 import java.util.Map;
 import javax.swing.JButton;
 import javax.swing.JComboBox;
 import javax.swing.JFrame;
 import javax.swing.JLabel;
 public class SelectWindow extends JFrame implements
 ItemListener {
     JButton button1;
     JLabel texte;
      Container c;
 public static void main(String[] args) {
 new SelectWindow();
 }

 Map<String, String[]> cars = new HashMap<String,
 String[]>();
 JComboBox brands;
 JComboBox models;
 public SelectWindow() {
 initCars();
 setTitle("Select a car");
 brands = new JComboBox();
 brands.addItem("<none>");
 for (String brand : cars.keySet()) {
 brands.addItem(brand);
 }
 brands.addItemListener(this);
 models = new JComboBox();
 models.setEnabled(false);
 models.addItemListener(this);
 texte = new JLabel("car was selected");
 texte.setVisible(false);
 button1 = new JButton("OK");

 button1.addActionListener(new ActionListener() {

     public void actionPerformed(ActionEvent arg0) {

         texte.setVisible(true);
        // c.add(texte);
     }
        });

 c = getContentPane();
 c.setLayout(new FlowLayout());
 c.add(new JLabel("Select a brand: "));
 c.add(brands);
 c.add(new JLabel("Select a model: "));
 c.add(models);
 c.add(button1);
 c.add(texte);
 setVisible(true);
 }
 @Override
 public void itemStateChanged(ItemEvent e) {
 if (e.getSource() == brands && e.getStateChange() == ItemEvent.SELECTED) {
   String[] items = cars.get(e.getItem());
 if (items == null) {
    models.removeAllItems();
     models.setEnabled(false);

 } else {
     models.removeAllItems();
     models.addItem("<none>");
 for (String item : items) {
     models.addItem(item);
 }
      models.setEnabled(true);

 }

 button1.setEnabled(true);



     }



 }
private void initCars() {
   cars.put("Renault", new String[] {
   "Twingo", "Clio", "Modus", "Kangoo",
     "Mégane", "Sénic", "Laguna", "Expace" });
cars.put("Peugeot", new String[] {
 "107", "206", "207", "308", "407",
 "508", "607" });
 cars.put("Citroën", new String[] {
 "C1", "C3", "C4 Picasso", "C5", "C6", "C8",
     "Berlingo", "DS3" });
   }
 }

Let me know if this was what you were looking for! 让我知道这是否是您想要的! Just changed the buttons and container and text to Global variables. 只需将按钮,容器和文本更改为全局变量。 Set the label visibility to False initially and added it to the container and later set it to True when Button clicked. 首先将标签可见性设置为False,然后将其添加到容器中,然后在单击Button时将其设置为True。

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

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