JFrame - adding checkboxes to the screen

做~自己de王妃 提交于 2019-12-12 03:23:57

问题


I want to have a JFrame that displays 5 different check boxes. Multiple checkboxes should be able to be selected. This code only reads the ExchangingCard1 line and ignores all other checkboxes. When you run it you will have only one checkbox with "A" as the character.

JCheckBox ExchangingCard1 = new JCheckBox("A");
JCheckBox ExchangingCard2 = new JCheckBox("B");
JCheckBox ExchangingCard3 = new JCheckBox("C");
JCheckBox ExchangingCard4 = new JCheckBox("D");
JCheckBox ExchangingCard5 = new JCheckBox("E");

JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.setTitle("Exchange.");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.add(ExchangingCard1);
frame.setVisible(true);
frame.add(ExchangingCard2);
frame.setVisible(true);
frame.add(ExchangingCard3);
frame.setVisible(true);
frame.add(ExchangingCard4);
frame.setVisible(true);
frame.add(ExchangingCard5);
frame.setVisible(true);

回答1:


Put the check boxes in a JPanel, then put the JPanel to the JFrame.

Here's a runnable example.

package com.ggl.testing;

import java.awt.BorderLayout;

import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class CheckBoxTest2 implements Runnable {

    private JFrame frame;

    @Override
    public void run() {
        frame = new JFrame("Check Box Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BorderLayout());

        JPanel checkBoxPanel = new JPanel();

        JCheckBox exchangingCard1 = new JCheckBox("A");
        checkBoxPanel.add(exchangingCard1);
        JCheckBox exchangingCard2 = new JCheckBox("B");
        checkBoxPanel.add(exchangingCard2);
        JCheckBox exchangingCard3 = new JCheckBox("C");
        checkBoxPanel.add(exchangingCard3);
        JCheckBox exchangingCard4 = new JCheckBox("D");
        checkBoxPanel.add(exchangingCard4);
        JCheckBox exchangingCard5 = new JCheckBox("E");
        checkBoxPanel.add(exchangingCard5);

        mainPanel.add(checkBoxPanel);

        frame.add(mainPanel);

        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new CheckBoxTest2());
    }

}



回答2:


JFrame by default use BorderLayoout that adds items in the center by default. use proper layout.

Read more How to Use Various Layout Managers Try FlowLayout



来源:https://stackoverflow.com/questions/28326585/jframe-adding-checkboxes-to-the-screen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!