gpt4 book ai didi

java - 添加到面板时组件未出现

转载 作者:行者123 更新时间:2023-12-01 23:10:39 26 4
gpt4 key购买 nike

所以我尝试创建一系列单选按钮和复选框,显示如下:

          Radio Button
Check Box
Radio Button
Check Box
Radio Button

但是,我仍在学习java过程中,我想知道是否有人可以解决这个问题。目前按钮和框显示在正确的位置,但是由于某种原因第一个单选按钮(“Courier”)没有显示。如果您能描述原因和可能的解决方案,那就太好了。

谢谢

更新的代码:

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

public class Question2 {
public static void main(String[] args) {
MyFrame f = new MyFrame("Font Chooser");
f.init();
}
}

class MyFrame extends JFrame {
MyFrame(String title) {
super(title);
}

private JPanel mainPanel;
private GridBagConstraints gbc = new GridBagConstraints();
private GridBagLayout gbLayout = new GridBagLayout();

void init() {
mainPanel = new JPanel();
mainPanel.setLayout(gbLayout);
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
this.setContentPane(mainPanel);

gbc.gridx = 0;
gbc.gridy = 1;

JCheckBox cb = new JCheckBox("Bold");
gbLayout.setConstraints(cb, gbc);
mainPanel.add(cb);
gbc.gridy = 3;
gbLayout.setConstraints(cb, gbc);
cb = new JCheckBox("Italic");
mainPanel.add(cb);

gbc.gridx = 1;
gbc.gridy = 0;

JRadioButton rb = new JRadioButton("Times");
gbLayout.setConstraints(rb, gbc);
mainPanel.add(rb, gbc);
gbc.gridy = 2;
rb = new JRadioButton("Helvatica");
mainPanel.add(rb, gbc);
rb = new JRadioButton("Courier");
gbc.gridy = 4;
mainPanel.add(rb, gbc);


this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}

最佳答案

3 个问题

  • Y 坐标未重新分配给不同的值,导致最后 2 个单选按钮存在于同一位置
  • GridBagConstraints 未用于左侧组件
  • setConstraints 错误地用于设置约束

结果代码:

public class GoodGridBagApp {
public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
JFrame frame = new JFrame("Font Chooser");
frame.add(getMainPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}

private JPanel getMainPanel() {

JPanel mainPanel = new JPanel();
GridBagConstraints gbc = new GridBagConstraints();
mainPanel.setLayout(new GridBagLayout());
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));

gbc.gridx = 1;
gbc.gridy = 2;

JCheckBox cb = new JCheckBox("Bold");
mainPanel.add(cb, gbc);
gbc.gridy = 4;
cb = new JCheckBox("Italic");
mainPanel.add(cb, gbc);

gbc.gridx = 2;
gbc.gridy = 1;

JRadioButton rb = new JRadioButton("Times");
mainPanel.add(rb, gbc);
gbc.gridy = 3;
rb = new JRadioButton("Helvatica");
mainPanel.add(rb, gbc);
rb = new JRadioButton("Courier");
gbc.gridy = 5;
mainPanel.add(rb, gbc);

return mainPanel;
}
});
}
}

阅读:How to Use GridBagLayout

关于java - 添加到面板时组件未出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22078980/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com