JCheckBoxMenuItem only one selected - java

So I want to have a JMenu Level with three JCheckBoxMenuItem like Easy, normal and expert.
Of course, only one can be checked and if one is checked, it can't be unchecked (enabled(false)) because it's the only one.
I want when one JCheck is checked, all others are unchecked.
So it seems easy, but the only solution I found is to do it with a lot of "if" conditions.
Is there a way to do it with a better algorithm ?

It sounds like you'd be better off using a JRadioButton since check boxes are generally used for multiple-choice options and radio buttons for a single selection out of many. JRadioButtons can be grouped together using a ButtonGroup which allows only one selected at a time.

public void stateChanged(ChangeEvent e) {
if (e.getSource() == cb1 && cb1.isSelected()) {
cb2.setSelected(false);
cb3.setSelected(false);
} else if (e.getSource() == cb2 && cb2.isSelected()) {
cb3.setSelected(false);
cb1.setSelected(false);
} else if (e.getSource() == cb3 && cb3.isSelected()) {
cb1.setSelected(false);
cb2.setSelected(false);
}
}

i just put all my JCheckBoxMenuItems in an array
and every time i select a JCheckBoxMenuItem i call this method
public void clearCheckBoxes(){
for (JCheckBoxMenuItem arrayCB1 : arrayCB) {
if (arrayCB1 != cb) {
arrayCB1.setSelected(false);
} else {
arrayCB1.setSelected(true);
}
}
}
The annoying part was having to manualy put them in the array,maybe the jMenu class has a method that returns the complete array but i didnt bother looking
arrayCB[0]=bridgeCB;
arrayCB[1]=swampCB;
arrayCB[2]=flowerCB;
arrayCB[3]=MountainCB;
arrayCB[4]=Mountain2CB;
arrayCB[5]=forestCB;
arrayCB[6]=parisCB;
arrayCB[7]=roadCB;
arrayCB[8]=waveCB;
arrayCB[9]=lakeCB;
just in case , this is how you create the array
JCheckBoxMenuItem [] arrayCB=new JCheckBoxMenuItem[10];
i dont know about that lots of if statements way of doing it

Related

How to write formatted text in JTextField dynamically, like Bold, Italic or with bullets and numbering?

How can i set formatted text in JTextFiled , as like when posting answer in this website we can change style of font and adding numbering etc.
Google is your best help. Steps to construct this will follow something similar.
1: Create identifier, some character combination/symbol to define what's what(bold, italicized, underlined).
2: When text is passed into your program have something that checks to see if your identifiers were used.
3: If you find and identifier, then use an if statement, switch or something to change the font to what you want and remove the identifier from your string.
4. Then display the string where you want it.
Cheers.
I don't really get your question . You need to explain in detail so that other viewers are able to help you out.
Are you making your TextField as bold inputs?
Are you trying to make your textfield accept only numbers ?
Elaborate more on
Bullets and numebering .
if you are trying to create your own inbuild function like textField accept only numbers.
You have to create a few java classes.
For an example
template.java
private JTextField createText(boolean acceptOnlyNumbers){
JTextField userInput;
if(acceptOnlyNumbers != false){
userInput.addKeyListener(new acceptNumberOnly(userInput))
}
return userInput;
}
You can create this within the same java class, but the best way is to asign your listener to a different class so that whenever you want to modify dynamically, you could just make changes to that file instead of searching it .
class acceptNumberOnly implements addKeyListener{
JTextField textField ;
public acceptNumberOnly(JTextField textField){
this.textField = textField
}
textField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (!(Character.isDigit(c) || (c == KeyEvent.VK_BACK_SPACE) || (c == KeyEvent.VK_DELETE))) {
e.consume();
}
}
});
}
I feel this is one of the best practice to use, categorised your components as class. so you can reuse this components over and over again and codes will be much neater.

doClick(), and Simon: All buttons will unpress at the same time instead of individually

Hi I'm new to stackoverflow so bear with me if I make mistakes.
I'm making this Java Simon Says Game for a class project. It works by a random number generator for each sequence#. I show the sequence through doClick() but remove the actionlisteners beforehand and add it afterwards.
The problem is the buttons won't unpress or unarm until all other buttons have been pressed. I've tried using thread.sleep to put a delay between each if...else statements yet it only stays pressed for longer. I've tried updating the gui through repaint(), revalidate(), updateUI() within the try... catch of the thread.sleep but that didn't work either.
I've realized this issue is mainly cosmetic because when I tried implementing setPressed or setArmed it said it wasn't being pressed but it looked pressed.
Here is the code snippet in it's most simplest form without thread.sleep or my previous attempts in comments.
public void sequence2() //This is where the issue happens. The buttons won't unpress until every button has been pressed.
{
level.setText(" Level 2"); //Level indicator
Green.removeActionListener(Listener);
Red.removeActionListener(Listener);
Yellow.removeActionListener(Listener);
Blue.removeActionListener(Listener);
if(sequence1 == 1)
{
Green.doClick(300); //Programmatically clicks the button
}
else if(sequence1 == 2)
{
Red.doClick(300);
}
else if(sequence1 == 3)
{
Yellow.doClick(300);
}
else if(sequence1 == 4)
{
Blue.doClick(300);
}
if(sequence2 == 1)
{
Green.doClick(300);
}
else if(sequence2 == 2)
{
Red.doClick(300);
}
else if(sequence2 == 3)
{
Yellow.doClick(300);
}
else if(sequence2 == 4)
{
Blue.doClick(300);
}
Green.addActionListener(Listener);
Red.addActionListener(Listener);
Yellow.addActionListener(Listener);
Blue.addActionListener(Listener);
}
I'm very new to java so I'm not skilled in multithreading or working on the Event Dispatch Thread for that manner. But if that's the only solution I'll need some more help with that.
I have the full code in a zip file with previous attempts commented out if that will help.
https://drive.google.com/file/d/0Bxg4WleC9jD2VFhoZmZBNjV6Vkk/view?usp=sharing
Invoking doClick() may be an awkward choice for this, as it uses a Timer internally. Instead, use a JToggleButton, which will allow you to control each button's appearance based on its selected state using setSelected(). A complete example is shown in the game Buttons. In the ActionListener of your Swing Timer, select the current button, play its note and increment the sequence index. When all notes have been played, unselect all the buttons.
Addendum: Can you show how you implement the timer?
In outline, given a suitable list of toggle buttons:
private static final int MAX = 4;
List<JToggleButton> buttons = new ArrayList<JToggleButton>(MAX);
private int i;
The timer's listener might look like this:
#Override
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
JToggleButton b = buttons.get(i);
if (i > MAX) { // reset i and all the buttons
for (JToggleButton b : buttons) {
b.setSelected(false);
}
timer.stop();
i = 0;
} else {
b.setSelected(true);
// play tone i
i++;
}
}
A toggle button's item listener should update the button's appearance as indicated by its state:
#Override
public void itemStateChanged(ItemEvent e) {
JToggleButton b = (JToggleButton) e.getItem();
if (b.isSelected()) {
// change icon, color etc.
} else {
// restore icon, color etc.
}
}

how to remove JMenu.addSeparator() after it is being called

Hello guys,
I just want to ask something if is it possible to remove JMenu.addSeparator() after it is being called? for example in my form there is a menu bar and inside the menu bar lets say there are three JmenuItems and each of it has JMenu.addSeparator(). What i want to do is, if a different user is log in I want to setVisible(false) one of JMenuItem because that particular user in not authorize to use that JMenuItem. The problem is when I setVisible(false) one of the JMenuItem the JMenu.addSeparator() still exist which kinda awkward to watch since there are no JMenuItem exist in the middle of two JMenu.addSeparator(). Hope you can help me with this problem.
Thanks in advance
You have two possible solutions...
You Could...
Remove the contents of the menu and rebuilt it based on what the user can do...
menu.removeAll();
// Add menu items back in...
// Personally, I'd have some method that could return back all
// the JMenuItems that could appear on this menu based on the
// the user...
This would be my preferred solution...
You Could...
Hide/show the menu items based on what the current user can actually do and then remove all the JSeparators that appear next to each other, for example...
Component last = null;
for (Component comp : menu.getComponents()) {
if (comp instanceof JSeparator && last instanceof JSeparator) {
menu.remove(comp);
} else {
last = comp;
}
}
Personally, I know which I would prefer and generally, which would produce consistent results...
I ran into a situation where I had to remove the separator from an existing menu. (Old code and wasn't allowed to refactor the whole mess.)
So I used the idea of MadProgrammer's 2nd solution - but rewrote it to actually work.
Component last = null;
for (int idx = 0; (idx < m_fileMenu.getMenuComponentCount()); idx++) {
Component comp = m_fileMenu.getMenuComponent(idx);
if (comp instanceof JPopupMenu.Separator && last instanceof JPopupMenu.Separator) {
m_fileMenu.remove(comp);
idx--;
} else {
last = comp;
}
}

how can I detect which combobox state changed?

I have two JComboBox in a form and I added an ItemListener to them and I should overwrite itemStateChanged(), now I wanna say if the first JComboBox items selected do something and else if the second JComboBox items selected do another thing, but I don't know how? Maybe code can help you.
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange()==ItemEvent.SELECTED)
picture.setIcon(pics[box.getSelectedIndex()]);
}
In the second line of code I don't know how to recognize which JComboBox state has changed.
You can use ItemEvent#getSource()
Example:
public void itemStateChanged(ItemEvent e) {
if(e.getSource() instanceof JComboBox){
JComboBox combo = (JComboBox) e.getSource();
//rest of code
}
Now for distinct combo1 from combo2 , you have 2 options , you can set names to that components like this.
combo1.setName("combo1");
combo2.setName("combo2");
And in the itemListener
if(e.getSource() instanceof JComboBox){
JComboBox combo = (JComboBox) e.getSource();
if("combo1".equals(combo.getName())){
// your code
}
.
.// rest of code
}
Or if you know that they are the same instance, then you can always use ==.
if(combo1 == e.getSource() ){
// your code
}else if (combo2 == e.getSource()){
//code for combo 2
}
There are two ways to do that, the first is to check the source on the event object and see which combo box it matches to.
The alternative is to add a different listener into each combo box, then you know that any calls going into one listener are from the corresponding control. This is a good use for an anonymous inner class.

weird result (java event-handling code)

public void itemStateChanged(ItemEvent event)
{
if(event.getSource() == doctorBox)
{
if (doctorBox.isSelected() == true)
JOptionPane.showMessageDialog(null, "you are a doctor");
else if (doctorBox.isSelected() != true)
JOptionPane.showMessageDialog(null, "you are not a doctor");
}
}
when the application is run... the checkbox is by default unchecked
when I check the "doctorBox" ... I get two dialog boxes popping together: "you are a doctor" and "you are not a doctor", also the checkbox doesn`t get checked!
why does that happen? how do I change the code to work correctly?
Here are some great samples. Remove all CheckBoxes except one and make sure you have a single listener to a single CheckBox per the details at the provided link. My guess is that there is strangeness occurring due to the way in which the listeners have been added in conjunction with the CheckBoxes.
Couple things to help you
for your logic, Since you know that the choice is either on or off, try the following
if(doctorBox.isSelected())
//do something
else
//do something else
with the checkbox not getting selected, change from an ItemListener to an ActionListener.
private class aListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == doctorBox){
if(doctorBox.isSelected())
JOptionPane.showMessageDialog(null, "you are a doctor");
else {
JOptionPane.showMessageDialog(null, "you are not a doctor");
}
}
}
}
If you look at your current code, and step through it using a debug you will see that your ItemListener gets fired 2 times. The first time checks it, the 2nd time it unchecks it. All on a single click. I cant explain the inner working of an itemListener in this case. ActionListener works much better

Categories

Resources