Search code examples
javaradio-buttonjframejpanel

How to setup radio button in jpanel within the jframe?


The radio buttons don't seem to be grouped together properly as one of them is slightly slanting towards the left. I am not sure what the error is. Everything in the code seems fine to me...I am not sure what is missing. I have attached an image below showing the problem. The Ide I am using is NetBeans.

Thank you in advanced! :)

barbeque is slightly slanted to left

 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);


    }

   }

Solution

  • Try adjusting radiopanel to this:

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

    to explain a little better, you're just setting it up so items align on the left, rather than the center (which I believe is default). You will need to import FlowLayout for this.