Operation translation from jCombobox in Java to Spinner in Eclipse - java

Asking a follow-up question here after solving some other problems I was having.
Essentially, I'm translating a working program from Java into Eclipse for development of an android app. I've whittled down the problems to a single block of code. In Java, it looked like this:
private void shapeDropDownActionPerformed(java.awt.event.ActionEvent evt) {
if(shapeDropDown.getSelectedIndex()==1)
diameterBox.setText("0");
if(shapeDropDown.getSelectedIndex()==1)
diameterBox.setEditable(false);
if(shapeDropDown.getSelectedIndex()==2)
widthBox.setText("0");
if(shapeDropDown.getSelectedIndex()==2)
widthBox.setEditable(false);
if(shapeDropDown.getSelectedIndex()==2)
heightBox.setText("0");
if(shapeDropDown.getSelectedIndex()==2)
heightBox.setEditable(false);}
Basically, if the user chooses a rectangle over a cylinder, the diameter input is set to "0" (so it is an integer) and is set to not editable. Or, if the user chooses cylinder, the height & width inputs were set to "0" and not editable.
However, I'm having difficulty with this method in Eclipse. Could you please show me how to implement this method in Eclipse? This is what I've got so far that is not working, thus making the entire app malfunction:
//Blank out the appropriate blanks:
private void setOnItemSelectedListener (new onItemSelectedListener() {
if (shapeDD.equals("Rectangle"))
txtDiameter.setText("0");
if (shapeDD.equals("Rectangle"))
txtDiameter.setEnabled(false);
if (shapeDD.equals("Cylinder"))
txtWidth.setEnabled(false);
if (shapeDD.equals("Cylinder"))
txtWidth.setText("0");
if (shapeDD.equals("Cylinder"))
txtHeight.setEnabled(false);
if (shapeDD.equals("Cylinder"))
txtHeight.setEnabled(false);
});
A secondary issue I'm having is with resetting the spinner once I'm done with it. In Java, it's simply:
jCombobox.setSelectedIndex(0).
What is the equivalent method in Eclipse for a Spinner?

I can answer to your second question: the equivalent method for the spinner is setSelection(index), for references see http://developer.android.com/reference/android/widget/AbsSpinner.html#setSelection(int)

Related

ActionListener and dynamic(?) GUI

I've read through a dozen or so actionlistener/loop related questions here, but I'm not sure I've found my answer. I started on my first large Java project, a text RPG that's spiraled into around 5K lines of logic and game features which was functioning as intended using just the console - when I decided I'd try to build a Java swing GUI for it instead. Here's my problem:
I use a Room object which handles the description of where the player is at and also has an array of options for the player to choose next which it creates dynamically based on what cell the room's id is in on a csv file and what is beside it. I stopped outputting this to the console and instead started creating JButtons based on the options array like so:
public void showNarrate(){
add(dd,gridConstraints);
optionCopy.clear();
int i = 0;
for(JButton j : optionButtons){
//adding and formatting buttons to gridBagConstraint I also set actionCommand for each button to the triggerValue (ID of the next room which the button should take the player to)
}
//I tried using a copy of my JButton array here so I could have something to iterate over in actionListener after clearing out the original
//(Since it needs to be cleared so the next Room's buttons can be built after the player chooses an option)
for(JButton j : optionButtons){
optionCopy.add(j);
}
optionButtons.clear();
//dd is a seperate drawingComponent I used for outputting room descriptions which may be totally unnecessary at this point :/
dd.repaint();
setVisible(true);
}
Over in actionlistener (Same class) this is how I tried to swing it:
for(JButton j : optionCopy){
if(e.getActionCommand().equals(j.getActionCommand())){
Main.saveRoom = Main.currentRoom;
Main.currentRoom = j.getActionCommand();
System.out.println(Main.currentRoom);
}
}}
Then in my main class I call:
narrator.narrate(currentRoom, saveRoom); which takes care of some other logic concerning locked doors, encounters, etc.
Also in Main loop are some other methods related to autosave and tracking which rooms the player has visited. I know from other q/a i'v read on here that this is all pretty bad design, and I'm sttarting to understand that now, but my issue is this:
The first room of the game loads up fine, when I click a button it outputs to console(Just for testing) the correct trigger value of the room the button should be calling, so I'm getting that far, but how can I call the same method over again now?
-If I call narrate from actionListener it will wind up calling itself again and complain about ConcurrentModification.
-If I try to keep a loop going in my Main class it will keep looping and won't allow for the player to actually choose a button.
I've never used threads before, which I wonder might be the answer,and the closest thing to a related answer I've found is this:
Java: Method wait for ActionListener in another class
but I don't think moving actionListener to Main class would resolve my problem which is actionListener winding up calling itself recursively. And as for the observer-observable pattern... I just can't understand it :(
I appreciate any and all help, I've learned a LOT trying to make this thing work without seeking help as much as possible but this has stumped me.
Your loop in actionPerformed only checks whether a JButton exists in your optionList with the given actionCommand. However this can be done before actually doing something:
boolean contained = false;
for (JButton j : optionButtons)
if (j.getActionCommand().equals(e.getActionCommand()))
contained = true;
if (contained) {
// change room
}
now you can call narrate because you have finished iterating over the collection beforehand and will not get a ConcurrentModificationException

Can't change/modify button background from another method - JAVA

I have a problem about modify button background. I am using netbeans gui builder for build form. I am trying change button background when the second frame is open and turn it back when second frame close.
public void update(boolean x){
if(x==true){
circleButton.setOpaque(true);
circleButton.setBackground(new java.awt.Color(0, 0, 0));
System.out.println("testoutput");
}
}
this is my update method from first class.
I added window listener to second frame.
private void formWindowOpened(java.awt.event.WindowEvent evt) {
isitopen = true;
//this is first class which includes button
homework hwork = new homework();
hwork.update(isitopen);
System.out.println("testoutput2");
}
I got 2 testoutput but color of the button didn't change.
What can i do to fix this issue ?
You're creating a new homework object in your formWindowOpened(...) method, one completely unrelated to the homework object that is displayed, and changing the state of the new object will have no effect on the displayed one.
A simple and WRONG solution is to use static fields or methods.
Instead one simple solution is to give the calss with your formWindowOpened(...) method a valid reference to the displayed homework object, something that can be done with a constructor parameter or a setHomework(...) method.
A much better and even simpler solution:
Make the 2nd window a modal JDialog, not a JFrame
This way homework will know when the window is open and can set its own button colors. When the 2nd window opens, program flow in the calling class is put on hold, and only resumes when the 2nd window closes -- just like using a JOptionPane.
For more on this, please see The Use of Multiple JFrames, Good/Bad Practice?
As an aside, you will want to learn and use Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.

Java in NetBeans - Adding actionEvents with custom parameters

I'm working on something in NetBeans, and I want to create an actionListener in a jTextPane for when the user presses Enter. However, I also need to input a String array (from a different subroutine within the source code) into the listener. But in NetBeans, events are generated automatically and I'm not allowed to edit this apparently extremely sensitive code. So, then, I tried typing up my own event thing (sorry about my terminology; I'm very new to GUI programming):
private void jTextPaneEnterPressed(KeyEvent evt, String[] stringArray)
{
int key = evt.getKeyCode();
if (key == KeyEvent.VK_ENTER)
{
// do something when the user presses enter that involves the program knowing what stringArray is
}
}
But when I run the program, pressing Enter in the text pane does nothing. I understand that this is because there is no actionListener associated with jTextPaneEnterPressed, but NetBeans gives no option for such customized code.
So what I want to know is either how I can pass in my own parameters when NetBeans creates an event handler, or how I can write my own actionListener alongside this actionPerformed block.
(And for the record, this is not an import problem)
I have tried looking this up, but have found nothing specific, as all other similar issues are not relevant to NB. Any help would be greatly appreciated.
*EDIT: This may seem like a trivial problem to most, but I'm open to any actual answers that tell me how to get done what I am trying to do, though I would prefer to stick with NetBeans. All I need is for the action listener to know that this string array exists, because the program needs to deal with that array when the user presses Enter. I'm sorry I can't give any specific context, but it's too much to get into.

jcombo getSelected in drag and drop

hi i wanted to ask how to use combo boxes because i need to change a check box caption.
i got nokia,samsung on the drop down. and then 3 check boxes. so if i clicked on nokia, i want to see 3 nokia chkboxes. and so on if samsung. i know that this is simple, but its hard to know the methods. i'm a visual basic user, so its kinda hard. pls make it simple, i am using DnD. also i used action perform.
here's my code for now. but its not working, it only shows samsung chk boxes
private void
phoneComboActionPerformed(java.awt.event.ActionEvent evt) {
String Nokia;
String Samsung;
Nokia = (String)phoneCombo.getSelectedItem();
checkBox1.setText("Nokia E71");
checkBox2.setText("Nokia E72");
checkBox3.setText("Nokia E79");
Samsung=(String)phoneCombo.getSelectedItem();
checkBox1.setText("Samsung D780");
checkBox2.setText("Samsung D880");
checkBox3.setText("Samsung F480");
} `
put a condition
if phoneCombo.getSelectedItem("Nokia) then // put your code here

Almost done...one problem with an error JPaneOption box

I've almost got my asignment done. Yayy! But.... I have two problems in my handler. For one, I have a public void itemStateChanged(ItemEvent e) method that is supposed to print a registrants name to a text field, plus the type of registration he is (student, business, complimentary). I have this working, only it prints twice to the text area. I don't get that. Also, there is a 'calculate charges' button which is used to...well, calculate the charges. When the button is clicked, the action event is supposed to check to make sure that a combo box (in a class called regPanel) does not have "Please select a registration type" which is element 0 in an object array. The way I have it now, if I don't pick something from the combobox (leaving it on element 0), I get the error message, but then the program prints to the textfield anyways. It is not supposed to. It is only supposed to print the error box, then allow the user to make the proper selections. Any advice would be appreciated. Here is the class:
public class ConferenceHandler implements ActionListener, FocusListener, ItemListener
{
protected final static String ERROR_TEXT = "Please enter a name";
protected ConferenceGUI gui; //reference the ConferenceGUI panel
/**Constructor*/
public ConferenceHandler(ConferenceGUI gui) {this.gui = gui;}
if (gui.regPanel.getRegType() == "Please select a type")
JOptionPane.showMessageDialog(null, "Please select a registration type",
"Type Error",JOptionPane.ERROR_MESSAGE);
//prints to textarea if registrant will be attending keynote or not
else if (gui.regPanel.regCheckBox.isSelected())
gui.textArea.append("\nKeynote address will be attended");
else
Did a little more googling, and figured out the problem with the double firing of the itemStateChanged affair. Trimmed all of the extra code out, because I'm pretty sure that all I need is a loop of some sort around here. When I put a while or do-while loop, all that happens is the JOptionPane comes up and won't go away. I need to validate that the user has entered an appropriate checkbox selection, though.
I have this working, only it prints twice to the text area.
You still haven't posted a SSCCE that demonstrates the problem as you where asked in a previoius question.
Copying and pasting a few lines of code from your real problem does not help you isolate the problem.
As a beginner, you need to learn how to simplify problems. Once you simplify the problem it is easier to find and solve the problem.
In this case a working SSCCE will be about 20 lines of code. A couple lines to create the GUI, a few more to add the compnonents and a few more to create the ItemListener.
Post your SSCCE and I'll post the answer to your question. This is a common mistake when working with an ItemListener. I could probably give you the answer without seeing your SSCCE, but you need to learn how to create a SSCCE for when you encounter more complex problems. So this question is a good place to start.
Maybe looking at the section from the Swing tutorial on How to Write an Item Listenerwill help you understand what is happening.

Categories