简体   繁体   English

是否可以使用for循环创建单选按钮?

[英]Is it possible to use a for-loop to create radio buttons?

I'm designing a program that uses an input file to store colors and their hexadecimal value(for example, Black 000000). 我正在设计一个程序,该程序使用输入文件来存储颜色及其十六进制值(例如,Black 000000)。 Currently I have two arraylists, one for colors and one for hex value (I know I should probably use a map but I'm stuck with getting input transferred into the map). 目前,我有两个arraylist,一个用于颜色,一个用于十六进制值(我知道我应该使用地图,但是我一直坚持将输入传输到地图中)。 Is there anyway to use a for-loop using the size of my colorCollection array? 无论如何,是否使用我的colorCollection数组的大小使用for循环? I've attached some code to see if that helps what I'm trying to accomplish. 我已经附加了一些代码,以查看是否对我要完成的工作有所帮助。

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;

import javax.swing.*;

public class ReadStoreShow extends JFrame{
private static int number;
private static ArrayList<String> colorCollection = new ArrayList<String>();
private static ArrayList<String> hexCollection = new ArrayList<String>();
private JRadioButton[] jrbColor = new JRadioButton[20];

public ReadStoreShow() {
    JPanel p1 = new JPanel();
    p1.setLayout(new GridLayout(4,5));
    for (int i = 0; i < colorCollection.size(); i++) {
        jrbColor[i] = new JRadioButton(colorCollection.get(i));
            // Is it possible to create buttons based on the size of colorCollection?
        jrbColor[i].setText(colorCollection.get(i));
        ButtonGroup group = new ButtonGroup();
        group.add(jrbColor[i]);
        p1.add(jrbColor[]);
        } 

        add(p1, BorderLayout.CENTER);
        setContentPane(p1);
        for (int j = 0; j < colorCollection.size(); j++){
        jrbColor[j].addActionListener(new ActionListener() {
            @Override
                public void actionPerformed(final ActionEvent e) {
                for (int k = 0; k < colorCollection.size(); k++){
                    final String hexColor = hexCollection.get(k);
                    getContentPane().setBackground(Color.decode(hexColor));
                    repaint();
                }
                } 
            });
        }
}

public static void main(final String[] args) throws IOException {
    final ReadStoreShow frame = new ReadStoreShow();
    frame.pack();
    frame.setLayout(new GridLayout(20, 1));
    frame.setSize(400, 300);
    frame.setTitle("Color Change");
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);

try {
     final java.io.File colors = new java.io.File("input.txt");
     final Scanner input = new Scanner(colors);
     while (input.hasNext()) {
         colorCollection.add(input.next());
         hexCollection.add(input.next());
     } // I'm assuming I should have used one Map instead of two arrays...
     input.close();
 }
 catch (final FileNotFoundException a) {
     JOptionPane.showMessageDialog(null, "File not found.");
     System.exit(0);
 }
while (number < 10 || number > 20) {
     number = Integer.parseInt(JOptionPane.showInputDialog(null, 
         "How many colors do you want? Must be between 10 and 20."));
 } // while
 System.out.println("The colors entered were:");
 for (final Iterator<String> itr = colorCollection.iterator(); itr.hasNext();)
     System.out.println(itr.next());
 System.out.println("The hexidecimal codes entered were:");
 for (final Iterator<String> itr = hexCollection.iterator(); itr.hasNext();)
     System.out.println(itr.next());
 }
}

Here is my current input.txt: 这是我当前的input.txt:

Black 0x000000 
Red 0xFF0000
Green 0x00FF00
Blue 0x0000FF
Yellow 0xFFFF00
White 0xFFFFFF 
Gray 0x707070
Purple 0x990099
Orange 0xFF6600
LightBlue 0x6666FF 

Yes you can do this, but you have a lot of issues in your code. 是的,您可以这样做,但是您的代码中有很多问题。 I'm describing just a few below, and there's more info in the comments here. 我仅在下面描述一些,这里的评论中有更多信息。

You have: 你有:

for (int i = 0; i < colorCollection.size(); i++) {
    jrbColor[i] = new JRadioButton(colorCollection.get(i));
    ...
    ButtonGroup group = new ButtonGroup();
    group.add(jrbColor[i]);
} 

Here you are creating a new ButtonGroup for every radio button. 在这里,您将为每个单选按钮创建一个新的ButtonGroup This probably isn't what you want. 这可能不是您想要的。 A ButtonGroup is a group of radio buttons in which selection is mutually exclusive, so your ButtonGroup should contain all the options for a given conceptual choice. ButtonGroup是一组单选按钮,其中选择是互斥的,因此ButtonGroup应该包含给定概念选择的所有选项。 In your case, it sounds like simply: 就您而言,这听起来很简单:

ButtonGroup group = new ButtonGroup();
for (int i = 0; i < colorCollection.size(); i++) {
    jrbColor[i] = new JRadioButton(colorCollection.get(i));
    ...
    group.add(jrbColor[i]);
} 

Another issue is you are using a fixed size JRadioButton[] array. 另一个问题是您正在使用固定大小的JRadioButton[]数组。 Consider using something dynamic, like an ArrayList<JRadioButton> instead. 考虑使用动态的东西,例如ArrayList<JRadioButton> That way you can just keep adding as many new buttons as you want to the end of it. 这样,您可以继续添加任意数量的新按钮。

The third thing that sticks out at me is, you don't want to setContentPane(p1) ; 向我伸出的第三件事是,您不想setContentPane(p1) ; Swing will provide a content pane for you. Swing将为您提供一个内容窗格。 All you need to do is set an appropriate layout and add your components to the frame. 您所需要做的就是设置适当的布局,并将组件添加到框架中。

There is a huge collection of official swing tutorials here . 有一个巨大的官方摆动教程集合在这里 I suggest browsing through and reading the relevant ones; 我建议浏览并阅读相关内容; in particular, the ones on radio buttons , button groups , and laying out components will be very helpful for you. 特别是单选按钮按钮组布局组件上的按钮将对您非常有帮助。

Instead of directly addressing all the issues in your snippet; 而不是直接解决您代码段中的所有问题; you may want to go through those tutorials, give it another shot, then come back if you're still having issues. 您可能需要阅读这些教程,再试一试,如果仍有问题,请回来。 It might also help if you start with a small test program to play around with that just creates a few radio buttons on a panel; 如果您从一个小的测试程序开始,在面板上创建几个单选按钮,这可能也会有所帮助。 that way you can get a feel for it without getting tied down by everything else your actual program is supposed to be doing. 这样一来,您就可以感受到它,而不会被实际程序应该做的其他事情所束缚。

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

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