简体   繁体   English

在jlabel中显示选定的jcheckbox

[英]displaying selected jcheckbox in a jlabel

i have 10 jcheckbox and only 5 should be selected. 我有10个jcheckbox,应该只选择5个。 i already did all the coding for this one, but i don't know how to display the selected 5 into a jlabel. 我已经为这个做了所有编码,但是我不知道如何将所选的5显示到jlabel中。 i tried doing it by this code: 我试图通过此代码来做到这一点:

           JCheckBox check;
           JPanel panel=new JPanel();
           for(int i=0; i<10; i++){
                check=new JCheckBox();
                check.addActionListener(listener);
                check.setName("Select"+i);

                panel.add(check); 
            }

this is the listener 这是listener

ActionListener listener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            check = (JCheckBox) e.getSource();
            name=check.getName();
        }
    };

and this is the panel where it should be displayed into jlabel 这是应该显示在jlabel中的面板

        panel2=new JPanel(new GridLayout(5,1));
        for(int i=0; i<5; i++){
            txtVote=new JLabel(name);
            panel2.add(txtVote);
        }

but using this code, it doesn't display anything on the jlabel. 但是使用此代码,它不会在jlabel上显示任何内容。 if i change the listener into this: 如果我将listener更改为此:

ActionListener listener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                check = (JCheckBox) e.getSource();
                txtVote.setText(check.getName());
            }
        };

it will only display into the last label. 它只会显示在最后一个标签中。 other jlabels would be blank. 其他jlabel将为空白。 please help thank you so much 请非常感谢你

EDIT 编辑

here is the code that is runnable 这是可运行的代码

public class JCheckBoxtoLabel{
    JCheckBox check;
    String name;
    JLabel txtVote;

     public JCheckBoxtoLabel() {
            JFrame frame = new JFrame();
            JPanel panel = createPanel();
            JPanel panel2 = panel2();

            frame.setLayout(new GridLayout(1,2));
            frame.add(panel); frame.add(panel2);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(500, 300);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }

        private JPanel createPanel() {
               JPanel panel=new JPanel(new GridLayout(10,1));
               for(int i=0; i<10; i++){
                    check=new JCheckBox();
                    check.addActionListener(listener);
                    check.setName("Select"+i);

                    panel.add(check); 
                }

            return panel;
        }

        private JPanel panel2(){
            JPanel panel2=new JPanel(new GridLayout(5,1));
            for(int i=0; i<5; i++){
                txtVote=new JLabel();
                txtVote.setBorder(BorderFactory.createLineBorder(Color.RED));
                panel2.add(txtVote);
            }
         return panel2;
     }

        ActionListener listener = new ActionListener() {
            @Override   
            public void actionPerformed(ActionEvent e) {
                check = (JCheckBox) e.getSource();
                txtVote.setText(check.getName());
            }
        };

        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    new JCheckBoxtoLabel();
                }
            });
        }
}

Consider changing what you're doing and displaying the text in a JList and not in JLabels. 考虑更改您正在执行的操作,并在JList中而非JLabels中显示文本。 This can help you consolidate your information. 这可以帮助您合并信息。 You can also give your JCheckBoxes or JRadioButtons and ItemListener that only allows 5 of the buttons to be selected at a time -- unselecting the oldest one currently selected. 您还可以提供JCheckBoxes或JRadioButtons和ItemListener,它们一次只能选择5个按钮-取消选择当前选择的最旧按钮。 For instance: 例如:

import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;

@SuppressWarnings("serial")
public class FiveNames extends JPanel {
    private static final String[] ALL_NAMES = {"Bob", "Bill", "Frank", "Helen", 
            "Erica", "Mickey", "Donald", "Hillary", "Michael", "Peter", "Roger"};
    private static final int ALLOWED_SELECTIONS_COUNT = 5;
    private DefaultListModel<String> displayListModel = new DefaultListModel<>();
    private JList<String> list = new JList<>(displayListModel);

    public FiveNames() {
        JPanel namePanel = new JPanel(new GridLayout(0, 1, 0, 5));
        RButtonItemListener rButtonListener = new RButtonItemListener();
        for (String name : ALL_NAMES) {
            JRadioButton rButton = new JRadioButton(name);
            rButton.setActionCommand(name);
            rButton.addItemListener(rButtonListener);
            namePanel.add(rButton);
        }

        list.setVisibleRowCount(ALLOWED_SELECTIONS_COUNT);
        list.setPrototypeCellValue("                            ");
        list.setBackground(null);

        setLayout(new GridLayout(1, 0));
        add(namePanel);
        add(list);
    }

    // listener to only allow the last 5 radiobuttons to be selected
    private class RButtonItemListener implements ItemListener {
        private List<ButtonModel> buttonModelList = new ArrayList<>();

        @Override
        public void itemStateChanged(ItemEvent e) {
            JRadioButton rBtn = (JRadioButton) e.getSource();
            ButtonModel model = rBtn.getModel();
            if (e.getStateChange() == ItemEvent.SELECTED) {
                buttonModelList.add(model);
                if (buttonModelList.size() > ALLOWED_SELECTIONS_COUNT) {
                    for (int i = 0; i < buttonModelList.size() - ALLOWED_SELECTIONS_COUNT; i++) {
                        ButtonModel removedModel = buttonModelList.remove(0);
                        removedModel.setSelected(false);
                    }
                }
            } else {
                buttonModelList.remove(model);
            }
            displayListModel.clear();
            for (ButtonModel buttonModel : buttonModelList) {
                displayListModel.addElement(buttonModel.getActionCommand());
            }
        }

    }

    private static void createAndShowGui() {
        JFrame frame = new JFrame("FiveNames");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new FiveNames());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

The problem is that txtVote is only a single Jlabel and you are trying to use it for all 5. Since the fifth jlabel was the last to be created it is the one being used. 问题是txtVote只是一个Jlabel,您正在尝试将其用于所有5个。由于第五个jlabel是最后一个要创建的,因此它正在使用中。 My suggestion is that you create an arraylist field and inside panel12 add each label to the arraylist. 我的建议是创建一个arraylist字段,然后在panel12内将每个标签添加到arraylist中。 Then inside the listener it would iterate through each jlabel in the arraylist check if has text set to it, if so check the next one until it finds one with no text, then sets the text to that. 然后在侦听器内部,它将遍历arraylist中的每个jlabel,检查是否设置了文本,如果是,则检查下一个,直到找到没有文本的文本,然后将其设置为该文本。 The problem with this at the moment is that in your code you are never defining what happens when they uncheck the box. 目前的问题是,在您的代码中,您永远不会定义当他们取消选中该框时会发生什么。

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class JCheckBoxtoLabel{
JCheckBox check;
String name;
JLabel txtVote;
ArrayList<JLabel> boxLabels;

public JCheckBoxtoLabel() {
    boxLabels = new ArrayList<JLabel>();

    JFrame frame = new JFrame();
    JPanel panel = createPanel();
    JPanel panel2 = panel2();

    frame.setLayout(new GridLayout(1,2));
    frame.add(panel); frame.add(panel2);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(500, 300);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}

private JPanel createPanel() {
    JPanel panel=new JPanel(new GridLayout(10,1));
    for(int i=0; i<10; i++){
        check=new JCheckBox();
        check.addActionListener(listener);
        check.setName("Select"+i);

        panel.add(check); 
    }

    return panel;
}

private JPanel panel2(){
    JPanel panel2=new JPanel(new GridLayout(5,1));
    for(int i=0; i<5; i++){
        txtVote=new JLabel();
        txtVote.setBorder(BorderFactory.createLineBorder(Color.RED));
        panel2.add(txtVote);
        boxLabels.add(txtVote);
    }
    return panel2;
}

ActionListener listener = new ActionListener() {
    @Override   
    public void actionPerformed(ActionEvent e) {
        check = (JCheckBox) e.getSource();
        if(!check.isSelected()){
            for(JLabel label: boxLabels){
                if(label.getText().equals(check.getName())) label.setText("");
            }
        }else{
            for(JLabel label: boxLabels){
                if(label.getText().isEmpty()){
                    label.setText(check.getName());
                    return;
                }
            }
        }
    }
};

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new JCheckBoxtoLabel();
        }
    });
}
}

Your variable JLabel txtVote is a single JLabel object, not an array. 您的变量JLabel txtVote是单个JLabel对象,而不是数组。

In your panel2() function you assign 5 new JLabels to txtVote . 在panel2()函数中,将5个新的JLabel分配给txtVote Since you assign 5 in a row, it gets overriden each time so it only ever contains the final JLabel. 由于您连续分配5,因此每次都会覆盖它,因此它只包含最终的JLabel。

private JPanel panel2(){
         JPanel panel2=new JPanel(new GridLayout(5,1));
         for(int i=0; i<5; i++){
             txtVote=new JLabel();
             txtVote.setBorder(BorderFactory.createLineBorder(Color.RED));
             panel2.add(txtVote);
         }
         return panel2;
}

So when you call getText on voteTxt in the action listener, you are only getting the last labels text. 因此,当您在操作侦听器中的voteTxt上调用getText时,只会得到最后的标签文本。

To fix this, you need to make txtVote an array of JLabels, and in your action listener iterate a second time through your JLabels and call get text on each in turn. 要解决此问题,您需要使txtVote组成一个JLabels数组,并在您的动作侦听器中第二次遍历JLabel并依次调用每个文本。

ActionListener listener = new ActionListener() {
    @Override   
    public void actionPerformed(ActionEvent e) {
        check = (JCheckBox) e.getSource();
        for (int i = 0; i < txtVotes.length; i++) {
            txtVotes[i].getText(check.getName());
        }
    }
};

I don't know if you realise or want to, but each label is being set to the same value, if you don't want this you will need to store an array of check names somewhere and iterate through these as well. 我不知道您是否意识到或想要实现,但是每个标签都被设置为相同的值,如果您不希望这样做,则需要在某个地方存储一系列检查名称,并对其进行遍历。

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

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