Comparison of texts of a jtextfield with an autocompletion - java

I would like to know if there is a way to have a text validator, not the equals exactly, because I know if I do one by one it would take me a lifetime, but to validate all the autocompletion that I did to the jtextfield, I add text to see if they can help me.
import com.mxrck.autocompleter.TextAutoCompleter;
import java.awt.event.ActionEvent;
import java.text.SimpleDateFormat;
import javax.swing.JOptionPane;
public class Comparativa extends javax.swing.JFrame {
public TextAutoCompleter ac;
public Comparativa(){
ac = new TextAutoCompleter(jTextfield);
ac.addItem("Procesador");
ac.addItem("RAM");
ac.addItem("Disco");
}
public void ValidadorComparacion(){
if(jTextfield.getText().equals(ac.getItem)){
System.out.println("GOOD");
}else{
System.out.println("BAD");
}
}
In the final part I want to make it compare if or if the code but I don't want to use "equals" for each item , but for everything.
That code gives me an error in the .equals part.

Not sure what error you are actually getting but you should check the value of jTextField to be non-null.
public void ValidadorComparacion(){
if (jTextField.getText() != null && jTextfield.getText().equals(ac.getItem())){
System.out.println("GOOD");
}else{
System.out.println("BAD");
}
}
If you get an error during compilation, please provide more of your source code. And the exact error message.

Related

Java Assigning Value to ComboBox

public static JComboBox[] ComboBox = new JComboBox[100];
String Array[] = { "Item1", "Item2", "Item3", "Item4" };
final DefaultComboBoxModel model = new DefaultComboBoxModel(Array); // this should assign the array and it does
ComboBox[1] = new JComboBox(model); // added this as the above also didn't help
ComboBox[1].setModel(model); // added this in because the above line didn't help
The issue I'm having with this code is its returning as part of the values, "[L]java,labg.String.....". I think this relates to the fact the array has been called (as a string not a true array).
I've tried every possible method i can think of to get rid of that random entry, I've tried true arrays, lists, nothing works. If I delete out Array..
ComboBox[1] = new JComboBox();
and just call the ComboBox naturally, its still there and I can't figure out why.
Updated 18/09/17 # 7.17am
Sorry I didn't really ask the question too well, it was really late and I'm actually experienced in VBA not so much in Java (which i'm still learning forgive me).
Yes I would like to improve my syntax approach, so please feel free to review my code.
Okay to start with, here is the design of the program. The purpose of the application is assist with capturing data in different aspects of their job, as they have templates they must fill out each time they preform an action (like changes address, leaves the country etc).
They select the questionset (example change of address), and then the template they need to fill out populates onto the userform.
The issue I was having was that when adding a dynamic combobox as an array, the combobox was displaying a strange item ([L]java,labg.String.....), even when all elements of the combobox are empty (or forced to be empty).
All I want is to be able to generate a dynamic combobox in an array format, and be able to retrieve the value the user has selected.
In writing the test code for you guys that you can compile....it just works fine...so I'm thinking I need to re-evaluate how the rest of my program is designed.
Here is the code for your reference, if you could help me figure out how to pass non static method's I'd appreciate that too!
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.event.*;
import java.awt.BorderLayout;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JSplitPane;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
public class ExampleApplication {
public static JComboBox[] my_dynamic_combobox = new JComboBox[100]; // Declare my dyanmic combobox so its visible throughout the instance of this class (see my explanation as to why I use static objects)
public static JFrame userform1 = new JFrame("My UserForm"); // Creates new instance of JFrame with title 'My UserForm'
public static class my_functions { // This is what I use to hold my functions to avoid repitition in code
public static void add_dynamic_combobox(int my_combobox_array, String[] my_combobox_items) { // This is a function, it adds a new dynamic combobox based on the value passed form a loop, and assigns the relevant list to it.
my_dynamic_combobox[my_combobox_array] = new JComboBox(my_combobox_items); // This should populate the newly created combobox, with its relevant items ONLY
my_dynamic_combobox[my_combobox_array].setBounds(10, 10, 100, 20); // I'm only displaying one combobox at the moment, so positioning doesn't matter here.
userform1.add(my_dynamic_combobox[my_combobox_array]);
}
// End of my_functions class
}
public static void main(String[] args) {
// The static void won't let me pass in/out any arguments or run any class/methods that aren't static. I don't know how to get around this. Doesn't like non-static context
String the_list[] = { "Item1", "Item2", "Item3"};
userform1.setSize(900, 225); // Set 400 width and 500 height
userform1.setLayout(null); // Using no layout managers
userform1.setDefaultCloseOperation(userform1.EXIT_ON_CLOSE); // define exit behaviour
for (int i=0; i<10; i++){
my_functions.add_dynamic_combobox(i, the_list);
}
// Loop has finished display the form.
userform1.setVisible(true);
}
}
edit 2: 18/09/17 # 9.39pm - Still no luck is isolating the code that is causing the issue. It definitely seems to be an issue when referring between static and non-static methods though.
You can use some thing like this
public static JComboBox[] comboBox = new JComboBox[100];
String[] array = { "Item1", "Item2", "Item3", "Item4" };
comboBox[1] = new JComboBox(array);
to add single items use this
comboBox[1].addItem("Item goes here");
No need to declare a DefaultComboBoxModel, as JComboBox does this for you. So try something like this:
public static JComboBox<String>[] comboBox = new JComboBox[100];
String[] array = { "Item1", "Item2", "Item3", "Item4" };
comboBox[1] = new JComboBox<>(array);

Getting info from an array that is in another JPanel

I am storing some info in an ArrayList that is in a JPanel. I want to access this info from a JFrame so that I can print the contents of the ArrayList.
How do I do this?
This is what i have tried so far:
package projektarbete;
import java.awt.*;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
public class Spelet extends javax.swing.JPanel {
ArrayList<String> Resultat = new ArrayList<>();
.....
if(gameOver == true || vinst == true){
btnTillbakaTillMeny.setVisible(true);
int klick = antalKlick;
String namn = txfNamn.getText();
//Integer.toString(klick);
String klickString = klick+"";
String score = namn+"\t"+klickString;
Resultat.add(score);
That was the JPanel and the info is stored in the ArrayList called Restultat.
This is how I am trying to retrieve the info from the JFrame:
package projektarbete;
import javax.swing.JFrame;
public class Instruktioner extends javax.swing.JFrame {
//private final Meny Meny = new projektarbete.Meny();
private static void close() {
// throw new UnsupportedOperationException("Not supported yet.");
}
public Instruktioner() {
initComponents();
Spelet Resultat = new Spelet();
jTextArea1.setText(Resultat);
}
The thing is that NetBeans is underlining Resultat in jTextArea1.setText(Resultat);
Any ideas?
You cannot put a Resultat object as a parameter to setText(), because that method does not Accept a parameter of that type. If you look at the javadoc for the method, you will see what type(s) it takes (there may be more than one 'signature' for the method, each signature taking a different combination of types).
I think what you want to do is have a class and then an object that holds the data for your program. It will have the necessary methods for setting and obtaining data, and for calculating things that need calculation. Then, any object that is going to present information to the user (panel, frame, whatever) will need to have a reference to the class holding the data, and can call methods to get what it needs.
This is the very fundamental idea behind "model-view-controller" -- a *separation of concerns", where the logic for handling data is separated from the logic for displaying that data. It helps in the common cases where you need to change the presentation but the data handling itself is ok.
setText() is waiting for a string, but you gave it an ArrayList

Don't know how to fix my PropertyChangeListener on a JFormattedTextField

EDIT at end of post
Test Code and Output
import java.awt.EventQueue;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.NumberFormat;
import javax.swing.JFormattedTextField;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.text.NumberFormatter;
public class Test{
private JFormattedTextField input, input2;
private NumberFormatter formatter;
private PropertyChangeListener listener;
public Test(){
formatter = new NumberFormatter(NumberFormat.getNumberInstance());
input = new JFormattedTextField(formatter);
input2 = new JFormattedTextField(formatter);
listener = new PropertyChangeListener(){
#Override
public void propertyChange(PropertyChangeEvent evt) {
convert(evt);
}
};
input.setColumns(4);
input2.setColumns(4);
input.addPropertyChangeListener("value", listener);
input2.addPropertyChangeListener("value", listener);
input.setValue(0.0);
JPanel panel = new JPanel();
panel.add(input);
panel.add(input2);
JOptionPane.showMessageDialog(null, panel);
}
private void convert(PropertyChangeEvent evt){
if (evt.getSource()== input){
if (evt.getSource()!= null){
double temp;
temp = converter((Double)evt.getNewValue());
input2.setValue(temp);
}
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable(){
public void run(){
new Test();
}
});
}
private double converter(double value){
value = value*2;
return value;
}
}
The stack trace:
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Double
at test.Test.convert(Test.java:46)
My thoughts
Because I have a method that passes in a double (it's convert()) , and seemingly evt.getNewValue() returns the direct value, which at the time of input is technically a long, it's throwing that error.
But every attempt at parsing my evt.getNewValue() to a double hasn't worked. Perhaps a little knowledge of what I'm trying to do with this program would help.
What The Program is for
So I've got a JPanel (in a tabbedPane) that has two JFormattedTextField inputs. It's a conversion application. My conversion class method passes in a double and returns a double. I'd like the fields to be linked together, or in other words, as soon as one field's input is changed the other changes with it (as in it's the output of the conversion).
I was considering scrapping the PropertyChangListener and going for a DocumentListener instead, but opted to try the former first as the latter has 3 overrideable methods I have to take care of, one of which might cause some unexpected results (highlighting and deleting the field would trigger two events for example).
TL;DR:
Is there a better way of getting a dynamically updating, dual input field application? Input one number into one field and the other field's number automatically updates.
Still a novice at Java.
Edit1
I've found a temporary solution: Have a DecimalFormat as the format in the JFormattedTextField. But if it could work without having a decimal as well I'd love it.
Edit2
Question answered, didn't realize evt.getNewValue() was returning a Number instance.
All you know for sure is that the object returned by evt.getNewValue() is a Number object. What if you use that information to your advantage and try something along these lines:
temp = ((Number)evt.getNewValue()).doubleValue();

javafx-2 ComboBox converter: method toString(T object) not called for null values

In a javafx2 application, a ComboBox should present a list of items, in the example they are String s for simplicity.
This list contains a null item, since i want the user to be allowed to make no choice.
Since I was playing with the converter property of the ComboBox, I wondered if I could use it to provide a nice representation for the no-choice case, for example "[none]" instead of an empty line.
But i've discovered that the toString(Object object) is never called for the null item.
Here follows the shortest code that reproduces the case. Version information included.
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.stage.Stage;
import javafx.util.StringConverter;
public class T05 extends Application {
#Override public void start(Stage primaryStage) throws Exception {
System.out.println(System.getProperty("java.runtime.version"));
System.out.println(System.getProperty("javafx.runtime.version"));
System.out.println(System.getProperty("os.version"));
System.out.println(System.getProperty("os.name"));
ComboBox c = new ComboBox();
//c.setEditable(true);
primaryStage.setScene(new Scene(c));
primaryStage.show();
c.getItems().add("first");
c.getItems().add(null);
c.setConverter(new StringConverter<String>(){
#Override public String toString(String object) {
System.out.print("converting object: ");
if (object==null) {
System.out.println("null");
return "[none]";
}
System.out.println(object.toString());
return object.toString();
}
#Override public String fromString(String string) {
throw new RuntimeException("not required for non editable ComboBox");
}
});
}
}
And here it's the output, as you can see the true branch of the if (object==null) statement is never called. Is it a bug or a feature, and is it yet possible to customize null representation?
1.6.0_29-b11
2.2.3-b05
6.1
Windows 7
converting object: first
converting object: first
converting object: first
update
Adding a (just uncomment it):
c.setEditable(true);
I get another behavior, that is, clicking on the null item in the combo selection box, I get the method toString called, but the result is not presented in the selection box.
you can use setPromptText method to display "[None]" in comboBox if user make no choice.
Sample Code :
comboBox.setValue(null);
comboBox.setPromptText("[None]");

How to use BerkeleyAligner in my own java class?

I'm trying to use the wordalignment in the BerkeleyAligner.jar file from http://code.google.com/p/berkeleyaligner/ in my own java class.
I have already added the .jar file into my buildpath.
What parameters does the edu.berkeley.nlp.wordAlignment.combine.CombinedAligner take?
What does the edu.berkeley.nlp.wordAlignment.combine.CombinedAligneroutput?
What i have are 2 input files that are already sentence aligned; i.e. the sentence from line number X from the sourceFile is the same (but in a different language) as the sentence from line number X of the targetFile.
import edu.berkeley.*;
import edu.berkeley.nlp.wa.mt.Alignment;
import edu.berkeley.nlp.wa.mt.SentencePair;
public class TestAlign {
BufferedReader brSrc = new BufferedReader(new FileReader ("sourceFile"));
BufferedReader brTrg = new BufferedReader(new FileReader ("targetFile"));
String currentSrcLine;
while ((currentSrcLine = brSrc.readLine()) !=null) {
String currentTrgLine = brTrg.readline();
// Reads into BerkeleyAligner SentencePair format.
SentencePair src2trg = new SentencePair(sentCounter, params.get("source"),
Arrays.asList(srcLine.split(" ")), Arrays.asList(trgLine.split(" ")));
// How do i call the BerkeleyAligner??
// -What parameters does the CombinedAligner takes?
// -What does the function/class returns?
// I assume it returns a list of strings.
// Is there a class in BerkeleyAligner to read the output?
// Please provide some example, thank you!!
Alignment output = edu.berkeley.nlp.wordAlignment.combine.CombinedAligner
.something.something(currentSrcLine, currentTrgLine);
}
}
e.g. sourceFile:
this is the first line in the textfile.
that is the second line.
foo bar likes to eat bar foo.
e.g. targetFile:
Dies ist die erste Textzeile in der Datei.
das ist die zweite Zeile.
foo bar gerne bar foo essen.
Actual Answer
You just wanted to align text (from a target file and a source file), right?
If so, after creating a sentence pair, you did not even need to put them in a CombinedAligner.
You could get an Alignment: (SentencePair, boolean) from that. The boolean is if you want a tree alignment.
Putting it into the constructor will generate an Alignment automatically!
So simple!
This is where I got the code: http://code.google.com/p/berkeleyaligner/source/browse/trunk/src/edu/berkeley/nlp/wa/mt/Alignment.java
UPDATE
Unfortunately, I misunderstood your question, and posted an irrelevant response.
However, I downloaded the jar file, found CombinedAligner.class, and decompiled it.
Here's what I got:
package edu.berkeley.nlp.wordAlignment.combine;
import edu.berkeley.nlp.mt.Alignment;
import edu.berkeley.nlp.mt.SentencePair;
import edu.berkeley.nlp.wordAlignment.PosteriorAligner;
import edu.berkeley.nlp.wordAlignment.WordAligner;
import fig.basic.Fmt;
import fig.basic.ListUtils;
import java.util.ArrayList;
import java.util.List;
public abstract class CombinedAligner extends PosteriorAligner {
private static final long serialVersionUID = 1;
WordAligner wa1;
WordAligner wa2;
public CombinedAligner (WordAligner, WordAligner)
public String getName()
public Alignment alignSentencePair(SentencePair)
public List alignSentencePairReturnAll(SentencePair)
public void setThreshold(int)
abstract Alignment combineAlignments(Alignment, Alignment, SentencePair)
}
It seems that the Alignment class you're using is edu.berkeley.nlp.mt.Alignment.
Anyway, CombinedAligner is abstract, so you can't instantiate it. And I don't know what the .something's are, because there is no static method or field.
I think that what you want, however, is alignSentencePair(SentencePair).
To get this, you need to use a subclass of CombinedAligner, as CombinedAligner is abstract.
So, after poking around the files, I found these subclasses:
edu.berkeley.nlp.wordAlignment.combine.HardUnion
edu.berkeley.nlp.wordAlignment.combine.HardIntersect
edu.berkeley.nlp.wordAlignment.combine.SoftUnion
edu.berkeley.nlp.wordAlignment.combine.SoftIntersect
You can use these instead of CombinedAligner and insert your two sentences as a SentencePair!
After checking, I realized that WordAligner is also abstract!
package edu.berkeley.nlp.wordAlignment;
import edu.berkeley.nlp.mt.Alignment;
import edu.berkeley.nlp.mt.SentencePair;
import fig.basic.LogInfo;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public abstract class WordAligner implements Serializable {
private static final long serialVersionUID = 1;
protected String modelPrefix;
public WordAligner ()
public abstract String getName()
public void setThreshold(double)
public Alignment alignSentencePair(SentencePair)
public Map alignSentencePairs(List)
public Alignment thresholdAlignment(Alignment, double)
public String getModelPrefix()
public String toString()
}
I found a subclass, though:
edu.berkeley.nlp.wordAlignment.IterWordAligner
Unfortunately, this is still abstract.
But there's a subclass of IterWordAligner that isn't:
edu.berkeley.nlp.wordAlignment.EMWordAligner
However, the constructor is really weird.
public EMWordAligner (SentencePairState$Factory, Evaluator, boolean)
It uses an INNER CLASS in the CONSTRUCTOR!? That's terrible programming practice.
WAIT...
I found a word aligner!
http://code.google.com/p/tdx-nlp/source/browse/trunk/pa2/java/src/cs224n/assignments/WordAlignmentTester.java?r=67
Maybe that helps and you can resolve your problem with it.

Categories