简体   繁体   English

如何在JFrame上组织单选按钮?

[英]How can I organize my radio buttons on my JFrame?

In my code below, I couldn't organize my interface to look like the attached photo. 在下面的代码中,我无法将界面组织得看起来像所附的照片。 I've tried grid and flow layouts, and I have been unable to solve the problem. 我已经尝试了网格和流布局,但无法解决该问题。

GUI应该看起来像这样

        package app;
        import javax.swing.*;
        import java.awt.*;

        public class app{
        JFrame f1;
        JButton buttton_1,buttton_2;
        JLabel label_1,label_2;
        JRadioButton radio_1,radio_2,radio_3,radio_4,radio_5,radio_6,radio_7;

         app(){

        JFrame f1 = new JFrame ("MathTest - Main Menu");
        f1.setVisible(true);
        f1.setSize(500,500);
        f1.setLayout(new GridLayout(0,1));
        f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


        label_1 =new JLabel("select test type ");
        radio_1=new  JRadioButton("addition ");
        radio_2=new  JRadioButton("subtraction");
        radio_3=new  JRadioButton("mulitipcation");
        radio_4=new  JRadioButton("division");

        label_2 =new JLabel("select a diffculty level");
        radio_5=new  JRadioButton("easy ");
        radio_6=new  JRadioButton("moderate");
        radio_7=new  JRadioButton("hard");

        buttton_1=new JButton("start test");              
        buttton_2=new JButton("exit");

        f1.add(label_1); 
        f1.add(radio_1);
        f1.add(radio_2);
        f1.add(radio_3); 
        f1.add(radio_4); 

        f1.add(label_2);
        f1.add(radio_5);
        f1.add(radio_6); 
        f1.add(radio_7);
        f1.add(buttton_1); 
        f1.add(buttton_2);   

        }

        public static void main(String[] args)
        {
            app xyz =new app();
        }
        }

Without doing the whole thing for you, here is how you can achive one of those radio button panels: 在不为您做全部事情的情况下,您可以通过以下方法实现单选按钮面板之一:

JPanel typePanel = new JPanel(new GridLayout(0, 2));
typePanel.setBorder(BorderFactory.createLineBorder(Color.black, 1));
typePanel.add(new JLabel("Select a test type"));
typePanel.add(new JRadioButton("Addition"));
typePanel.add(new JLabel(""));
typePanel.add(new JRadioButton("Substraction"));
typePanel.add(new JLabel(""));
typePanel.add(new JRadioButton("Multiplication"));
typePanel.add(new JLabel(""));
typePanel.add(new JRadioButton("Division"));

For the buttons at the bottom, remember that a flow layout can be set to align things on the right side with the constructor: 对于底部的按钮,请记住,可以设置流布局以使右侧的内容与构造函数对齐:

new FlowLayout(FlowLayout.RIGHT)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM