【问题标题】:Is it possible to use a for-loop to create radio buttons?是否可以使用 for 循环来创建单选按钮?
【发布时间】:2014-03-31 19:15:38
【问题描述】:

我正在设计一个程序,它使用输入文件来存储颜色及其十六进制值(例如,黑色 000000)。目前我有两个数组列表,一个用于颜色,一个用于十六进制值(我知道我可能应该使用地图,但我坚持将输入传输到地图中)。无论如何使用我的 colorCollection 数组的大小来使用 for 循环?我附上了一些代码,看看这是否有助于我想要完成的工作。

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());
 }
}

这是我当前的 input.txt:

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

【问题讨论】:

  • 仅供参考,我知道这不是您提出的问题,但是:您很少需要直接使用迭代器,就像您在程序结束时所做的那样。 for (String s : colorCollection)(Java 的前几个版本中没有)是实现此目的的简单方法。
  • @ajb 感谢您的提示!我在我的程序中更改了它。

标签: java swing for-loop arraylist hashmap


【解决方案1】:

是的,您可以这样做,但是您的代码中存在很多问题。我在下面只描述了一些,这里的 cmets 中有更多信息。

你有:

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

在这里,您正在为每个单选按钮创建一个新的ButtonGroup。这可能不是你想要的。 ButtonGroup 是一组单选按钮,其中的选择是互斥的,因此您的 ButtonGroup 应该包含给定概念选择的所有选项。就您而言,这听起来很简单:

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

另一个问题是您使用的是固定大小的JRadioButton[] 数组。考虑使用动态的东西,比如ArrayList&lt;JRadioButton&gt;。这样一来,您就可以继续添加任意数量的新按钮。

让我印象深刻的第三件事是,你不想setContentPane(p1); Swing 将为您提供一个内容窗格。您需要做的就是设置适当的布局并将组件添加到框架中。

有大量官方挥杆教程here。我建议浏览并阅读相关的;特别是radio buttonsbutton groupslaying out components上的那些对你很有帮助。

而不是直接解决您的 sn-p 中的所有问题;您可能想通过这些教程,再试一次,然后如果您仍然遇到问题,请返回。如果您从一个小测试程序开始玩,它可能会有所帮助,它只是在面板上创建几个单选按钮;这样你就可以感受它,而不会被你的实际程序应该做的所有其他事情所束缚。

【讨论】:

  • @JasonC Swing 组件,除了基于 windows 的类(包括JInternalFrame)默认是可见的...
  • 哦,当调用框架的构造函数时,colorCollection.size()0:P - 这意味着构造函数没有任何内容可以添加到框架中,因此没有输出......
  • @JasonC 我不记得什么java版本了,如果你add直接到jframe就像添加到contentPane一样
  • @JasonC As a conveniance add and its variants, remove and setLayout have been overridden to forward to the contentPane as necessary. This means you can write: frame.add(child); And the child will be added to the contentPane.
  • @MadProgrammer 感谢你们俩的帮助!除了在按下按钮时为按钮分配颜色外,我一切都启动并运行了。尝试用 for 循环将其击倒,但今晚没有骰子。我明天必须回来。 (仅供参考,我实际上改变了在代码中添加框架的位置,这就是最终让我的按钮出现的原因......呵呵......总是很容易。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多