简体   繁体   English

每当JComboBox更改时,如何更新JLabel?

[英]How do I update a JLabel everytime a JComboBox changes?

I have a JComboBox with 12 different selections, and depending on what is selected I want the question (JLabel) to change matching the selection. 我有一个带有12个不同选择的JComboBox,并且根据选择的内容,我希望问题(JLabel)更改与选择匹配的内容。 I've tried an if statement to see what is selected and if it matches what should be selected, then the question changes accordingly, but the JLabel never really changes under an circumstance. 我尝试了一个if语句来查看选择的内容,如果它与应选择的内容相匹配,则问题会相应更改,但是JLabel在任何情况下都不会真正更改。

Code

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.*;

public class Window extends JFrame{
    private static final long serialVersionUID = 1L;
    public Window(){
        super("Area Finder v1.0");
        BufferedImage image = null;

        try {
            image = ImageIO.read(getClass().getClassLoader().getResource("images/areafinder.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        super.setIconImage(image);
        setSize(400, 500);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        JLabel Instr = new JLabel("What would kind of area would you like to find?");
        String[] areaChoices = {"Circle", "Square", "Rectangle", "Triangle", "Trapezoid", "Parallelogram", "Hexagon", "Rhombus", "Pentagon", "Polygon", "Ellipse", "Sector"};
        final JComboBox<?> choiceBox = new JComboBox(areaChoices);
        final Object isSelected = choiceBox.getSelectedItem();
        choiceBox.setToolTipText("Select which one you want to find the area of!");
        choiceBox.setSelectedIndex(0);
        final JLabel q = new JLabel("");
        final JTextField inputFromUser = new JTextField("");
        JButton findArea = new JButton("Find Area");
        /* Question Changer*/

        /*End of Question Changer*/
        findArea.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent arg0){
                if(isSelected == "Circle"){
                    double radius = Double.parseDouble(inputFromUser.getText());
                    double area = 3.14 * (radius * radius);
                    JOptionPane.showMessageDialog(null, "Your Area is " + area);
                }else if(isSelected == "Square"){

                }

            }
        });
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(15,15,15,15);
        panel.add(Instr);
        panel.add(choiceBox);
        panel.add(findArea);
        panel.add(q);
        panel.add(inputFromUser);
        add(panel);
    }
}

EDIT: So I did a few tests with System.out.println(); 编辑:所以我用System.out.println()做了一些测试; and I figured out it's calling all the items at once, but the one that's selected is being called first. 我发现它可以一次调用所有项目,但是被选中的项目将被首先调用。 Example: 例:

choiceBox.addItemListener(new ItemListener(){
    @Override
    public void itemStateChanged(ItemEvent e) {
        if(e.getItem() == "Circle"){
        System.out.println("Circle selected");
        }else if(e.getItem() == "Square"){
            System.out.println("Square selected");
        }

    }

});

Prints out "Circle Selected Square Selected" if you select circle, but "Square Selected Circle Selected" if you select Square. 如果选择圆,则输出“选择圆选定的圆”,如果选择“平方”,则打印出“选定圆的选定圆”。

Add an ItemListener to the JComboBox to react when the selection changes. ItemListener添加到JComboBox以在选择更改时做出反应。

Also, when you do this: 另外,当您这样做时:

Object isSelected = choiceBox.getSelectedItem();

... you are just getting the selected value at that time; ...您当时只是获得选定的值; you aren't magically binding the isSelected variable to update whenever the combobox updates. 您不会神奇地绑定isSelected变量以在组合框更新时进行更新。 You need to call getSelectedItem() again if you want the new value. 如果需要新值,则需要再次调用getSelectedItem()

try adding an action listener to the JComboBox 尝试将动作侦听器添加到JComboBox

choiceBox.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//put the code here
}
});

Change the text of the JLabel 更改JLabel的文本

label.setText("Changed text");

Tell the container to relayout. 告诉容器重新布局。

frame.invalidate();
frame.repaint();

This makes sure that the frame is redrawn to show the changed label. 这样可以确保重新绘制框架以显示更改后的标签。 To know when the combo box has changed it's selection, add an ActionListener like this. 要知道组合框何时更改,请添加一个这样的ActionListener

combo.addActionListener (new ActionListener ()
{
    public void actionPerformed(ActionEvent e)
    {
        label.setText(combo.getText());
        frame.invalidate();
    }
});

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

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