[英]How to add a button group of JRadioButtons in a Panel or just JRadioButtons in a panel in Java?
[英]How to add JRadioButtons to a JPane within a loop
我有以下代碼:
public class PnlMenuRadioButtons extends JPanel {
public PnlMenuRadioButtons(String menuName) {
super();
setLayout(new BorderLayout());
Font radioButtonsFont = new Font("Arial", Font.PLAIN, 14);
JPanel titlePanel = new JPanel();
titlePanel.setLayout(new BorderLayout());
titlePanel.setBorder(new EmptyBorder(5, 5, 5, 5));
add(titlePanel, BorderLayout.NORTH);
Font menuTitleFont = new Font("Tempus Sans ITC", Font.BOLD, 16);
JLabel lblMenu = new JLabel(menuName);
lblMenu.setFont(menuTitleFont);
titlePanel.add(lblMenu, BorderLayout.WEST);
JPanel contentPanel = new JPanel();
contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
add(contentPanel, BorderLayout.CENTER);
/*
//VERSION 1
//FROM HERE
ButtonGroup btngrp = new ButtonGroup();
JRadioButton rdbtn = new JRadioButton("hi");
btngrp.add(rdbtn);
contentPanel.add(rdbtn);
JRadioButton rdbtn2 = new JRadioButton("hello");
btngrp.add(rdbtn2);
contentPanel.add(rdbtn2);
//TO HERE
*/
//VERSION 2
//FROM HERE
String[] strs = {"hi", "hello"};
ButtonGroup radioButtonsGroup = new ButtonGroup();
for(int i = 0; i < 2; i++) {
JRadioButton rdbtn = new JRadioButton((String)Array.get(strs, i));
rdbtn.setFont(radioButtonsFont);
radioButtonsGroup.add(rdbtn);
contentPanel.add(rdbtn);
}
//TO HERE
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
add(buttonPanel, BorderLayout.SOUTH);
Font buttonFont = new Font("Arial", Font.PLAIN, 14);
JButton btnBack = new JButton("Back");
btnBack.setFont(buttonFont);
btnBack.setActionCommand("Back");
buttonPanel.add(btnBack);
JButton btnGO = new JButton("Go");
btnGO.setFont(buttonFont);
btnGO.setActionCommand("Go");
buttonPanel.add(btnGO);
}
}
如果我使用版本 1, contentPanel
會正確添加JRadioButton
s。
但是我想要一個循環,因為我想用用戶選擇的多個JRadioButton
更改代碼,所以它是隨機的。
但是,如果我使用 VERSION 2, contentPanel
似乎永遠不會添加JRadioButton
。 我錯過了什么?
謝謝。
您在代碼末尾錯過了一個 }。 嘗試為 contentPanel.add() 添加不同的變量名稱,可能就是這樣。
我發現代碼工作正常。 我想要的是JRadioButton
出現在 JavaSwing 的設計選項卡中。 但是在循環中添加按鈕無法顯示。 抱歉浪費您的時間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.