简体   繁体   English

单选按钮未按预期显示

[英]Radio buttons do not display as expected

Whenever I run this code the radio buttons display correctly until I tab in or hover into the window, then it only shows one of the radios and the only way I can see the others is by hovering over them.每当我运行此代码时,单选按钮都会正确显示,直到我进入或悬停在窗口中,然后它只显示其中一个单选按钮,而我可以看到其他单选按钮的唯一方法是将鼠标悬停在它们上方。

Why do the radio buttons not display until I hover over the window or tab into it?为什么单选按钮在我将鼠标悬停在窗口上或选项卡上时才会显示?

    JRadioButton rDollar1 = new JRadioButton("Dollars");
    JRadioButton rCDollar1 = new JRadioButton("Canadian Dollars");
    JRadioButton rMPesos1 = new JRadioButton("Mexican Pesos");
    JRadioButton rCPesos1 = new JRadioButton("Colombian Pesos");


    ButtonGroup bg1 = new ButtonGroup();
    bg1.add(rDollar1);
    bg1.add(rCDollar1);
    bg1.add(rMPesos1);
    bg1.add(rCPesos1);

    frame1.setSize(500, 500);
    frame1.setVisible(true);
    frame1.add(rDollar1);
    frame1.add(rCDollar1);
    frame1.add(rMPesos1);
    frame1.add(rCPesos1);
    rDollar1.setBounds(10, 50, 50, 20);
    rDollar1.setVisible(true);
    rCDollar1.setBounds(10, 100, 50, 20);
    rCDollar1.setVisible(true);
    rMPesos1.setBounds(10, 150, 50, 20);
    rMPesos1.setVisible(true);
    rCPesos1.setBounds(10, 200, 50, 20);
    rCPesos1.setVisible(true);

Whenever I run this code the radio buttons display correctly until I tab in or hover into the window每当我运行此代码时,单选按钮都会正确显示,直到我进入或悬停在窗口中

This is because when you "tab in" or you hover over the radio buttons, you're triggering a call to repaint() , which is responsible for painting your GUI.这是因为当您“插入”或将鼠标悬停在单选按钮上时,您会触发对repaint()的调用,它负责绘制您的 GUI。

In this case the weird behavior is due to you having this line:在这种情况下,奇怪的行为是由于你有这条线:

frame1.setVisible(true);

before you've added every other component to the JFrame .在将所有其他组件添加到JFrame But that's only the beginning of your problems, as you'll eventually find other errors such as your GUI not being painted correctly on some other computers that are not the one you used to make the program, and that's because of the calls to setBounds(...) which suggests you're using null-layout which is evil and frowned uppon .但这只是您问题的开始,因为您最终会发现其他错误,例如您的 GUI 在其他一些不是您用来制作程序的计算机上被正确绘制,这是因为调用了setBounds(...)这表明您正在使用null-layout ,这是邪恶的,并且皱起了眉头 Instead learn how to use and mix the different layout managers , or else you'll be in a situation similar to this one而是学习如何使用和混合不同的布局管理器,否则您将处于与此类似的情况

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM