【问题标题】:Radio buttons don't show单选按钮不显示
【发布时间】:2016-06-22 19:31:02
【问题描述】:

我正在尝试用 java 进行调查。我有 20 个问题和 5 个可能的选择。我正在考虑制作 20 个标签和 100 个按 5 分组的单选按钮。

我设法使用 Net beans GUI 手动添加标签,但我想生成按钮,但它们不显示。这是我的代码:

public class Prikaz extends javax.swing.JFrame {

    /**
     * Creates new form Prikaz
     */
    public Prikaz() {
        initComponents();
        javax.swing.JRadioButton [][] buttons = new javax.swing.JRadioButton [20][5];
        ButtonGroup [] bg = new ButtonGroup[20];


        for (int i = 0; i < 20; ++i) {
            bg[i]= new ButtonGroup();
            for (int j = 0; j < 5; ++j) {
                buttons[i][j] = new javax.swing.JRadioButton();
                if(j==0)buttons[i][j].setSelected(true);
                buttons[i][j].setLocation(1014+(j*24) , 44+(i*31));
                buttons[i][j].setToolTipText(((Integer)(j+1)).toString());
                buttons[i][j].setVisible(true);
                buttons[i][j].setEnabled(true);
                bg[i].add(buttons[i][j]);
            }
        }

    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel19;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel21;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    // End of variables declaration                   
}

【问题讨论】:

  • 您不需要将按钮组添加到表单或面板吗?
  • 我已经尝试将它们添加到新面板和标签中,但它们都不显示

标签: java swing jframe jradiobutton


【解决方案1】:

除了ButtonGroup之外,还需要将按钮添加到父组件。

例如,要将按钮添加到jlabel1,请在创建按钮后添加:

jlabel1.add(buttons[i][j]);

编辑: 如果不起作用,请先为每个JLabel 执行jLabel.setLayout(new FlowLayout()),然后添加新按钮。

【讨论】:

  • 您是否将标签添加到框架中?
  • 我也对您的setLocation() 方法持怀疑态度。我个人会使用GridLayout
  • 我确实在框架中添加了标签,它们显示出来了,所以我不明白出了什么问题,我也尝试删除 setLocation() 然后将其添加到 jlabel,仍然没有运气
  • JLabels 有什么布局?
  • 我认为它是内部生成的
猜你喜欢
  • 2015-12-16
  • 2016-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-22
相关资源
最近更新 更多