简体   繁体   中英

How to add JLabel text on top of multiple Checkboxes?

I am building a Pizza form and ran into an issue with the JLabel and JCheckbox class.

I am supposed to build a panel that simulates the cooking instructions of a pizza, it should be a variety of checkboxes. In one row there should be 3 options, in the other row 2 options. For example:
Cooking Instructions
♦Cook Lite ♦Extra Sauce
♦Light Sauce ♦Well Done
♦Light Cheese

However, this is what I get:
在此处输入图片说明

public CookingInstructions() {

    JLabel label1 = new JLabel();
    label1.setText("Cooking Instructions");
    setLayout(new GridLayout(0,2));
    add(label1);
    cookLite = new JCheckBox("Cook Lite");
    extraSauce = new JCheckBox("Extra Sauce");
    lightSauce = new JCheckBox("Light Sauce");
    wellDone = new JCheckBox("Well Done");
    lightCheese = new JCheckBox("Light Cheese");

    add(cookLite);
    add(extraSauce);
    add(lightSauce);
    add(wellDone);
    add(lightCheese);
}

How can I make it so the JLabel ("Cooking Instructions") stays on top the series of checkboxes regardless of the number of checkboxes that might be there?

U need add new Jpanel that hold all JCheckBox. Then you combine Jlabel and Jpanel with BorderLayout. Here the implementation.

package javaapplication7;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.*;  
public class JavaApplication7 extends JFrame {
    JCheckBox cookLite,extraSauce,lightSauce,wellDone,lightCheese;

    JavaApplication7(){  



        JLabel label1 = new JLabel();
        label1.setText("Cooking Instructions");

        setLayout(new BorderLayout());
        add(label1,BorderLayout.NORTH);

        cookLite = new JCheckBox("Cook Lite");
        extraSauce = new JCheckBox("Extra Sauce");
        lightSauce = new JCheckBox("Light Sauce");
        wellDone = new JCheckBox("Well Done");
        lightCheese = new JCheckBox("Light Cheese");

        JPanel panel=new JPanel();
        panel.setLayout(new GridLayout(0,2));
        panel.add(cookLite);
        panel.add(extraSauce);
        panel.add(lightSauce);
        panel.add(wellDone);
        panel.add(lightCheese);

        add(panel,BorderLayout.CENTER);

        setSize(400,500); 
        setVisible(true);  

    }  
    public static void main(String[] args) {
        new JavaApplication7();  
    }

}

Hope that can help

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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