如何在 jframe 中的 jpanel 中设置单选按钮?

How to setup radio button in jpanel within the jframe?

单选按钮似乎没有正确组合在一起,因为其中一个按钮稍微向左倾斜。我不确定错误是什么。代码中的所有内容对我来说都很好......我不确定缺少什么。 我在下面附上了一张显示问题的图片。 Ide 我使用的是 NetBeans。

提前致谢! :)

 package pizzaorder2;

 import javax.swing.*;
 import java.awt.*;
 import java.awt.event.ActionListener;
 import java.awt.event.KeyEvent;
 import java.awt.FlowLayout;
 import javax.swing.SwingUtilities;
 import javax.swing.JRadioButton;

public class PizzaOrder2 extends JFrame { 


public static void main(String[] args) {

  JFrame frame = new PizzaOrder2();


   JRadioButton tomato = new JRadioButton("Tomato");
   JRadioButton barbeque = new JRadioButton("Barbeque");  
   ButtonGroup group = new ButtonGroup();
   group.add(tomato);
   group.add(barbeque);
   JPanel radiopanel = new JPanel();
   radiopanel.add(tomato);
   radiopanel.add(barbeque);
   frame.getContentPane().add(radiopanel);
   radiopanel.setBounds(240,330,110,70);
   radiopanel.setOpaque(false);
   tomato.setForeground(Color.white);
   barbeque.setForeground(Color.white);


    frame.setLayout(null);
    frame.setSize(600, 700);
    frame.getContentPane().setBackground(new Color(40, 80, 120));
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);


    }

   }

尝试将无线电面板调整为:

JPanel radiopanel = new JPanel(new FlowLayout(FlowLayout.LEFT));

为了更好地解释,您只是将其设置为使项目在左侧对齐,而不是居中(我认为这是默认设置)。您需要为此导入 FlowLayout。