对于Java Swing中的应用程序(在netbeans中开发),我们需要像单选按钮一样创建大圆圈,这意味着我们有一组圆圈,每当用户点击一个圆圈时,它就会变为一个圆圈。用户只能选择1个圆圈。
工作mechansim与radiobutton组完全相似,只是我们需要有更大的圈子。知道我们怎么做到这一点吗?
答案 0 :(得分:5)
setIcon(Icon icon)
来执行此操作。setSelectedIcon(Icon icon)
来执行此操作。例如,下面的代码创建:
..... ......
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import javax.swing.*;
@SuppressWarnings("serial")
public class CircleIconEg extends JPanel {
public static final String[] PLAYER_NAMES = {"John", "Bill", "Frank", "Andy"};
private static final int BI_WIDTH = 40;
private ButtonGroup btnGrp = new ButtonGroup();
private static Icon emptyIcon;
private static Icon selectedIcon;
// create our Circle ImageIcons
static {
// first the empty circle
BufferedImage img = new BufferedImage(BI_WIDTH, BI_WIDTH, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = img.createGraphics();
g2.setStroke(new BasicStroke(4f));
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
int x = 4;
int y = x;
int width = BI_WIDTH - 2 * x;
int height = width;
g2.setColor(Color.black);
g2.drawOval(x, y, width, height);
g2.dispose();
emptyIcon = new ImageIcon(img);
// next the filled circle
img = new BufferedImage(BI_WIDTH, BI_WIDTH, BufferedImage.TYPE_INT_ARGB);
g2 = img.createGraphics();
g2.setStroke(new BasicStroke(4f));
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.red);
g2.fillOval(x, y, width, height);
g2.setColor(Color.black);
g2.drawOval(x, y, width, height);
g2.dispose();
selectedIcon = new ImageIcon(img);
}
public CircleIconEg() {
setLayout(new GridLayout(0, 1, 0, 4));
for (String playerName : PLAYER_NAMES) {
JRadioButton radioBtn = createRadioButton(playerName);
btnGrp.add(radioBtn);;
add(radioBtn);
}
}
private JRadioButton createRadioButton(String playerName) {
JRadioButton rBtn = new JRadioButton(playerName, emptyIcon);
rBtn.setSelectedIcon(selectedIcon);
return rBtn;
}
private static void createAndShowGui() {
CircleIconEg mainPanel = new CircleIconEg();
JFrame frame = new JFrame("CircleIconEg");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}