I have a Swing form where I want to detect edited field data so I can update the data via a web service. There doesn't seem to be a simple way to do this as there are a plethora of medium to complex code examples for this, most of which are over my head! However, I think I found a simple solution that will fit my needs and I wanted to run it by the group for input / suggestions. FYI: it may not matter but know that I am using NetBeans so things like listeners are auto-coded by the app.
Step 1: When I load the form, I am saving all the data to a Class array so I know the starting point of the each field. Here is the code for that load:
public void coSetSearchDetail(String coDetail){
String[] text;
System.out.println("SingleCO Result: "+ coDetail);
text = coDetail.split("\\|");
txtName_CoDetail.setText(text[1]);
txtAddr_CoDetail.setText(text[2]);
txtAddr2_CoDetail.setText(text[3]);
txtCity_CoDetail.setText(text[4]);
txtState_CoDetail.setText(text[5]);
txtZip_CoDetail.setText(text[6]);
stringarrayCoDetails[0] = text[0];
stringarrayCoDetails[1] = text[1];
stringarrayCoDetails[2] = text[2];
stringarrayCoDetails[3] = text[3];
stringarrayCoDetails[4] = text[4];
stringarrayCoDetails[5] = text[5];
stringarrayCoDetails[6] = text[6];
java.awt.CardLayout card = (java.awt.CardLayout)pnlMain.getLayout();
card.show(pnlMain, "pnlCoDetail");
}
Step 2: I created a Lost Focus event listener for one field and am testing the current value of the field against the array:
private void txtName_CoDetailFocusLost(java.awt.event.FocusEvent evt) {
if (!(txtName_CoDetail.getText().equals(stringarrayCoDetails[1]))){
createEditBorder();
}
}
private void createEditBorder (){
Border border = BorderFactory.createLineBorder(Color.RED, 2);
txtName_CoDetail.setBorder(border);
}
Besides the general question of "is this an OK approach?", I would like to be able to pass the field name to the createEditBorder method so the listener for each data field can call it and I have one method for "edited text" formatting.
Related
I have a simple GUI that has a jTextField that waits for the user to put in something. After a button is clicked, the program:
reads the input, saves it in a String variable;
opens a new GUI (that is in a separate class file), which contains an empty jLabel, and passes the String variable to it, changing the jLabel text to it.
The problem is that no matter how hard I try to reconfigure the code, adding things like repaint(), revalidate(), etc., the jLabel in the second GUI stays empty. Using a System.out.println(jLabel.getText()) reveals that the text value is indeed changed, but not displayed. How do I "refresh" this jLabel, so it'd show what I want it to? I'm aware I could add an event, though I don't want the user to click anything to refresh the GUI, the values should be there as it's initiated. I've read trough several similar posts, but found that the solutions don't work for me.
The code of first GUI's button click event:
private void sbuttonActionPerformed(java.awt.event.ActionEvent evt) {
errortext.setText("");
Search = sfield.getText();
Transl = hashes.find(Search);
if (Transl.equals("0")) errortext.setText("Word not found in database.");
else {
ws.run(Search, Transl); // <- this opens the second GUI, with two String parameters I want to display in the second GUI;
}
}
The code of the second GUI (activeword and translation are the jLabels that are giving me trouble.):
public void run(String Search, String Transl) {
WordScreen init = new WordScreen(); //initialise the second GUI;
init.setVisible(true);
activeword.setText(Search);
translation.setText(Transl);
}
Any reply is very welcome! Please ask me for more information about the code if necessary, I will make sure to reply as soon as possible!
Best solution: change WordScreen's constructor to accept the two Strings of interest:
From this:
public void run(String Search, String Transl) {
WordScreen init = new WordScreen(); //initialise the second GUI;
init.setVisible(true);
activeword.setText(Search);
translation.setText(Transl);
}
to this:
public void run(String search, String transl) {
WordScreen init = new WordScreen(search, transl);
init.setVisible(true);
}
Then in the WordScreen constructor use those Strings where needed:
public WordScreen(String search, String transl) {
JLabel someLabel = new JLabel(search);
JLabel otherLabel = new JLabel(transl);
// put them where needed
}
Note that I cannot create a comprehensive answer without your posting a decent MRE
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.
I'm struggling to find a way to alter the TextField and Text objects of the view class from the controller class without just passing the TextField and Texts to the controller and then altering them using commands such as textField.setText() which I know is in breach of the whole separation idea. I am creating a game to guess a number between 1 and 50.
Example:
View Class:
This class will set up the stage with Labels, Texts, and TextFields for user input, as well as buttons. There is a button to guess if the number you entered into the TextField is correct. When the guess button is clicked I call for the setOnAction method in the view class which then calls a method from the controller class to handle the events. I realise that I cannot just pass in the TextField to the Controller because you need to keep the view separate from the controller so I can pass in the TextField.getText() and Text.getText() as shown bellow in order to convert it to a string first which keeps them separate. In this example enteredNumber is a TextField and result is a Text.
guessButton.setOnAction(e -> guessingGameController.guessButtonAction(enteredNumber.getText(), result.getText()));
I then read and process the data in the controller class:
public void guessButtonAction(String enteredNumber, String result) {
int enteredValue = Integer.parseInt(enteredNumber);
if (enteredValue == randomNum) {
result = ("YOU WON!!!");
}
else if (enteredValue != randomNum) {
result = ("Unlucky the number was " + randomNum);
}
}
I realise that I can simply return the String result from the controller and then have the view class make the Text resultBox set the text like this:
guessButton.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
String result = guessButtonAction(
enteredNumber.getText(), result.getText());
resultBox.setTex(result);
}
});
But There are a few buttons that would have to return more then one variables meaning I'd have to return an array which I feel complicates things too much. Is there any other way of doing this without being so messy and maintaining the separation of the GUI and the processing of data? I apologise for the long question, I hope I explained it well enough.
I am currently designing a GUI for a farm. The farm consists of three actors (Weed, Bean Plant and the Farmer). Upon running the Farm GUI, it shows the movement of the Farmer planting and removing Weed from the farm field. I have defined probabilities for the actors to ensure the field is not overpopulated.
The following are declared in the Simulator class. The probabilities are as follows:
public final double FARMER_CREATION_PROB = 0.01;
public final double BEANPLANT_CREATION_PROB = 0.01;
public final double WEED_CREATION_PROB = 0.01;
I am now designing a seperate GUI which allows the variables above (and more) to be changed based on what the user inputs. For example, I have a JTextField for the Weed creation probability, if the user enters 3, then I want the FARMER_CREATION_PROB = 3;.
This is how I have created my JTextFields for the three probabilities (Declared in FarmGUI class):
weedField = new JTextField ();
beanField = new JTextField ();
farmerField = new JTextField();
With my limited understanding of Java, I have tried the following:
public final double WEED_CREATION_PROB = weedField.getText();
However, it states "cannot find symbol". I'm pretty sure that my approach is not the correct way to go about it anyway.
Question:
How do I obtain the user input from the GUI and ensure it changes the creation probabilities to what the user has entered?
Edit:
First of all, thanks for the feedback.
This is the GUI I have designed (very basic)
[IMG]http://i57.tinypic.com/2j63668.png[/IMG]
The Logic of the GUI: The whole purpose of the Gui is to enable the user to set the values for each field. Upon clicking "Run Simulation" in the GUI above, another GUI where the simulation is run would appear on a separate frame.
Edit 2:
I have tried the following (based on #zaibi099 suggestion), just wondering if it is correct.
In the Simulator Class:
public final double WEED_CREATION_PROB;
In the Farm GUI Class:
run.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
double s = Double.parseDouble(weedField.getText());
Mistakes you are making:
these both are not type compatible. weedField.getText(); returns string and you are assigning it to double
You are trying to assign value to final(constant variable) so it'll not allow you to do that.constant can be assign to value first time.
Solution :
public final double FARMER_CREATION_PROB;
and where you want to assign do this :
FARMER_CREATION_PROB = weedField.getText(); // don't forget to convert the text field into double
I am writing a software (GWT) in which different images of soccerclubs and its names should be shown. So i wrote the following method:
public void updateClubNameHeader(String clubName, int logoNumber) {
clubLabelFrame.clear();
HTML clubLogo = new HTML();
clubLogo.setStyleName("clublogo_img");
clubLabelFrame.add(clubLogo);
Label clubNameLabel = new Label(clubName);
clubNameLabel.setStyleName("clubnameLabel"); <--- logoNumber?
clubLabelFrame.add(clubNameLabel);
}
It is no problem to change the names of the club (clubNameLabel), but if i want to have a new logo as well, this CSS-style is used: (filenames: 1.jpg, 2.jpg, ...)
.clublogo_img {
...
background-image: url("images/1.jpg") !important
}
The problem: If i want to represent every possible club, i have to write round about ~100 styles.
The question: Is it possible to pass my integer logoNumber to the CSS, so that this one style is enough the show all the chosen logos?
You cannot do it with CSS. You can do it with GWT:
clubLogo.getElement().getStyle().setBackgroundImage("url(\"images/" + imageNumber + ".jpg\")");
I got a doubt regarding pre-selecting(setSelectedIndex(index)) an item in a ListBox, Im using Spring + GWT.
I got a dialog that contains a panel, this panel has a FlexPanel, in which I've put a couple ListBox, this are filled up with data from my database.
But this Panel is for updates of an entity in my database, thus I wanted it to pre-select the current properties for this items, allowing the user to change at will.
I do the filling up in the update method of the widget.
I tried setting the selectedItem in the update method, but it gives me an null error.
I've searched a few places and it seems that the ListBox are only filled at the exact moment of the display. Thus pre-selecting would be impossible.
I thought about some event, that is fired when the page is displayed.
onLoad() doesnt work..
Anyone have something to help me out in here?
I really think you can set the selection before it's attached and displayed, but you have to have added the data before you can select an index. If this is a single select box you could write something like this:
void updateListContent(MyDataObject selected, List<MyDataObject> list){
for (MyDataObject anObject : list) {
theListBox.addItem(anObject.getTextToDisplay(), anObject.getKeyValueForList());
}
theListBox.setSelectedIndex(list.indexOf(selected));
}
If this is a multiple select box something like this may work:
void updateListContent(List<MyDataObject> allSelected, List<MyDataObject> list){
for (MyDataObject anObject : list) {
theMultipleListBox.addItem(anObject.getTextToDisplay(), anObject.getKeyValueForList());
}
for (MyDataObject selected : allSelected) {
theMultipleListBox.setItemSelected(list.indexOf(selected), true);
}
}
(Note I haven't actually compiled this, so there might be typos. And this assumes that the selected element(s) is really present in the list of possible values, so if you cant be sure of this you'll need to add some bounds checking.)
I've been happily setting both the values and the selection index prior to attachment so as far as I'm aware it should work. There's a bug however when setting the selected index to -1 on IE, see http://code.google.com/p/google-web-toolkit/issues/detail?id=2689.
private void setSelectedValue(ListBox lBox, String str) {
String text = str;
int indexToFind = -1;
for (int i = 0; i < lBox.getItemCount(); i++) {
if (lBox.getValue(i).equals(text)) {
indexToFind = i;
break;
}
}
lBox.setSelectedIndex(indexToFind);
}
Pre-selection should work also with setValue()-function. Thus, no complicated code is needed.