java JFrame - 在屏幕上添加复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28326585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JFrame - adding checkboxes to the screen
提问by Nick
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.
我想要一个显示 5 个不同复选框的 JFrame。应该可以选择多个复选框。此代码仅读取 ExchangeCard1 行并忽略所有其他复选框。当您运行它时,您将只有一个带有“A”作为字符的复选框。
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);
回答by Gilbert Le Blanc
Put the check boxes in a JPanel, then put the JPanel to the JFrame.
将复选框放入 JPanel,然后将 JPanel 放入 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());
}
}
回答by Braj
JFrame
by default use BorderLayoout
that adds items in the center by default. use proper layout.
JFrame
默认情况下,默认使用BorderLayoout
在中心添加项目。使用适当的布局。
Read more How to Use Various Layout ManagersTry FlowLayout
阅读更多如何使用各种布局管理器尝试FlowLayout