我不知道为什么每个按钮都没有显示我想要的文字,以及为什么显示“...”
ButtonGroup operations = new ButtonGroup();
JRadioButton[] buttons = new JRadioButton[2];
String[] buttonLabels = {"Male", "Female"};
for (int i=0; i<2; i++) {
buttons[i] = new JRadioButton(buttonLabels[i], true);
buttons[i].setLocation(400 + (i * 50) , 170);
buttons[i].setSize(35, 30);
add(buttons[i]);
operations.add(buttons[i]);
}
我希望按钮[0]说男性,按钮1说女性
答案 0 :(得分:8)
当没有足够的空间显示整个文本时会发生这种情况。您可以尝试将它们放在彼此之下或稍微拉伸宽度。
答案 1 :(得分:7)
您的主要问题是您使用的是null布局和绝对定位。如果您使用体面的布局管理器,他们会为您处理这个问题。此外,您可以更轻松地维护在 所有 平台和屏幕分辨率上看起来不错的GUI。
如,
import java.awt.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class LayoutEg extends JPanel {
public LayoutEg() {
setBorder(BorderFactory.createTitledBorder("Personal Information"));
setLayout(new GridBagLayout());
addLabelWithComponent("First Name:", new JTextField(10), 0, 0);
addLabelWithComponent("Last Name:", new JTextField(10), 0, 1);
addLabelWithComponent("City:", new JTextField(10), 0, 2);
addLabelWithComponent("Street:", new JTextField(10), 0, 3);
addLabelWithComponent("Province:",
new JComboBox<>(new String[] { "Foo", "Bar" }), 0, 4);
addLabelWithComponent("Home Phone:", new JTextField(10), 2, 0);
addLabelWithComponent("Cell Phone:", new JTextField(10), 2, 1);
addLabelWithComponent("Email Address:", new JTextField(10), 2, 2);
addLabelWithComponent("Age", new JSpinner(
new SpinnerNumberModel(18, 17, 100, 1)), 2, 3);
JPanel radioPanel = new JPanel(new GridLayout(1, 0));
radioPanel.add(new JRadioButton("Male"));
radioPanel.add(new JRadioButton("Female"));
addLabelWithComponent("Gender:", radioPanel, 2, 4);
}
private void addLabelWithComponent(String text, JComponent component, int x, int y) {
addLabel(new JLabel(text), x, y);
addComponent(component, x + 1, y);
}
private void addComponent(JComponent component, int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5, 5, 5, 5);
add(component, gbc);
}
private void addLabel(JComponent component, int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.BOTH;
int left = x == 2 ? 35 : 5;
gbc.insets = new Insets(5, left, 5, 5);
add(component, gbc);
}
private static void createAndShowGui() {
LayoutEg mainPanel = new LayoutEg();
JFrame frame = new JFrame("LayoutEg");
frame.setDefaultCloseOperation(JFrame.EXIT_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();
}
});
}
}
如果你只是让你的JRadioButtons更大,然后在另一个平台上运行这个应用程序,名称就会消失,那么呢?这就是布局的用途。
例如,以上显示为:
答案 2 :(得分:3)
您需要增加JRadioButton
的宽度。
答案 3 :(得分:0)
原来我必须使.SetSize更大