I am doing a simple GUI painting box program. However, I have a problem with adding 2 similar separated groups to be corresponding in the same way.

enter image description here

I mean when I click the JRadioButtonMenuItem Line, then the JRadioButton Line below also has to be selected too. What should I do?

Do you need to see my code?, please let me know Thank you so much.

P/s: it says I need 10 reputation to post image

有帮助吗?

解决方案

Share the model between the two radio buttons:

JRadioButton radioButton = new JRadioButton("Line");
JRadioButtonMenuItem radioMenuItem = new JRadioButtonMenuItem("Line");
radioMenuItem.setModel( radioButton.getModel() );

Actually, you should share the Action as well between the two components. Read the section from the Swing tutorial on How to Use Actions for more information and examples.

其他提示

The exact solution depends a lot on how your code is structured right now. I bet that the standard library has some functionality to accomplish what you want to do, but if you want to go ahead and implement it then you might as well (minimal time input and you learn something).

The most direct solution that comes to my mind is to encapsulate selecting a button in a method that will manipulate all sets of corresponding buttons. I am going to assume that you are using action listeners for the buttons right now, if not you could adapt the idea. In the action listener, you can detect the mouse click and perform some work as necessary. That work should include updating the other buttons appropriately too. You could even create a method that both action listeners call and updates all necessary sets of buttons.

It is also possible to use the same action listener on both sets of the buttons, but you'll need to know which selection the user wants to be active (likely an easy task).

My Java is pretty rusty, so I am not including any example code, but if anything is unclear or you think an example would help I can do so.

Hope at least something here helps you. Good luck!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top