【问题标题】:My JRadioButton does not shows when I run but when I click on that area it shows我的 JRadioButton 在我运行时不显示,但是当我单击该区域时它显示
【发布时间】:2016-09-27 10:39:31
【问题描述】:

您好,当我运行简单的 swing 应用程序时,我在 netbeans 8.1 中遇到了这个问题。我的框架只显示一个单选按钮,当我在该区域上选择它显示的第二个单选按钮时,当我取消选择它时它会消失。 查看以下图片

When I run my swing application

When I click on the radio button area it shows

源代码:

import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
public class MainClass {
private JFrame mainFrame;
private JRadioButton radStudent,radTeacher;

public MainClass(){ //Constructor of main class
    prepareGUI();
}
public static void main(String arg[]){
    MainClass main = new MainClass();
}

private void prepareGUI(){ //GUI 
    mainFrame = new JFrame("Select any one");
    mainFrame.setSize(300,200);
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainFrame.setResizable(false);
    mainFrame.setVisible(true);

    //Frame position set
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int height = screenSize.height;
int width = screenSize.width;
mainFrame.setLocationRelativeTo(null);

    //radio for employee
    radStudent = new JRadioButton("Student");
    radStudent.setBounds(10,10,100,20);

    //radio for Teachers
    radTeacher = new JRadioButton("Teacher");
    radTeacher.setBounds(110,10,100,20);

    mainFrame.add(radStudent);
    mainFrame.add(radTeacher);

}
}

提前谢谢你!!

【问题讨论】:

  • 你需要add()组件然后然后调用setVisible()
  • mainFrame.setVisible(true); 这应该在添加所有组件之后完成,并且在调用 pack() 之后直接完成。

标签: java swing netbeans netbeans-8 jradiobutton


【解决方案1】:

问题是:您必须了解 JFrame 使用 LayoutManager 来组织您添加到其中的项目。

将代码更改为

mainFrame.add(radStudent, BorderLayout.PAGE_START);
mainFrame.add(radTeacher, BorderLayout.PAGE_END);

会给你一个在顶部显示一个按钮的框架;另一个在窗口底部(因为默认情况下,JFrame 使用 BorderLayout 来组织其子级)。

换句话说:一旦你想使用多个组件,你必须先坐下来思考如何组织这些组件。然后选择那个 LayoutManager,例如 BorderLayout,它提供了最简单的方法来访问您决定使用的“结构”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-19
    • 2018-12-09
    相关资源
    最近更新 更多