java swing 复选框

2025-01-08 09:58:35
推荐回答(3个)
回答1:

改下layout就行了

import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.WindowConstants;

public class NewJFrame extends javax.swing.JFrame {
private JScrollPane jScrollPane;
private JPanel jPanel;
private String[]str={"a","b","c","d","e","f","g","h","i","j","k","l"};

public static void main(String[] args) {
NewJFrame inst = new NewJFrame();
inst.setVisible(true);
}

public NewJFrame() {
super();
initGUI();
}

private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
pack();
setSize(300, 120);
setLocationRelativeTo(null);
jPanel=new JPanel();
jScrollPane = new JScrollPane(jPanel);
getContentPane().add(jScrollPane,BorderLayout.CENTER);
jPanel.setLayout(new GridLayout(str.length/3+1, 3));
for (int i = 0; i < str.length; i++) {
JCheckBox checkBox=new JCheckBox(str[i]);
jPanel.add(checkBox);
}

} catch (Exception e) {
e.printStackTrace();
}
}

}

回答2:

我想你说错了,JCheckBox没有一个构造方法可加入str[],你是不是想用JComboBox,代码如下:
import java.awt.*;
import javax.swing.*;

public class CheckBoxTest extends JFrame{

JComboBox box;

public CheckBoxTest() {
super("复选框");

setSize(300,300);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

String str[]={"a","b","c","d","e","f"};
box=new JComboBox(str);

box.setMaximumRowCount(3);
add(box);

setVisible(true);
}

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

回答3:

public void showST(String[] s){
JCheckBox jc;
JFrame jf=new JFrame("显示复选框");
JPanel jp=new JPanel();

for(int i=0;ijc=new JCheckBox(s[i]);
jp.add(jc);
}
JScrollPane js=new JScrollPane(jp);
jf.add(js);
jf.setSize(200,300);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);

}

如果需要复选框竖着排列,只需要设定jp的布局即可