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
Related
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.
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);
Hello Guys I have my swing application running but I need to create an "initialization class" where I create instances with data to populate the program when I run it
If I create an instance with data in the MainJFrame constructor it's working perfectly but I need to populate the MainJFrame that will send it through all the panels from ANOTHER CLASS
Here is my MainJFrame Code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package UserInterface;
import Business.Initialization;
import Business.Inventory;
import Business.InventoryList;
import Business.Product;
import Business.ProductCatalog;
import Business.Store;
import Business.StoreDirectory;
import UserInterface.StarMarketAdmin.MarketAdminWorkArea;
import UserInterface.StoreAdmin.LoginStoreAdmin;
import java.awt.CardLayout;
import java.util.Collections;
import javax.swing.SwingUtilities;
public class MainJFrame extends javax.swing.JFrame {
/**
* Creates new form MainJFrame
*/
private StoreDirectory storeDirectory;
private InventoryList inventoryList;
private ProductCatalog productCatalog;
private Store store;
public MainJFrame() {
initComponents();
this.storeDirectory = new StoreDirectory();
this.inventoryList = new InventoryList();
this.productCatalog = new ProductCatalog();
this.store = new Store();
}
private void btnMarketAdminActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
MarketAdminWorkArea panel = new MarketAdminWorkArea(userProcessContainer,storeDirectory,inventoryList,productCatalog,store);
userProcessContainer.add("MarketAdminWorkArea", panel);
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.next(userProcessContainer);
}
private void btnStoreAdminActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
LoginStoreAdmin panel = new LoginStoreAdmin(userProcessContainer,storeDirectory,inventoryList,productCatalog);
userProcessContainer.add("LoginStoreAdmin", panel);
CardLayout layout = (CardLayout) userProcessContainer.getLayout();
layout.next(userProcessContainer);
}
}
Now if I create an instance like:
Store s = storeDirectory.addStore();
s.setStoreName("Eddie's Market");
s.setStreet("Plainfield Pike");
s.setCity("Johnston");
s.setState("RI");
s.setCountry("USA");
in the MainJFrame it's working 100% but I need to create it in another class and call it in the MainJFrame to send it from there to all the other pannels.
How can I do this ?
create public functions to acces the private class from outside
not sure what you want exactly, but the options are endless
like
public void initStore(){
}
or just get it
public Store getStore(){
retturn store;
}
or even create and return it from there:
public Store storeFactory(){
// code here
return store;
}
or if you want another store and return it
public Store storeFactory(){
// code here to create a new store
return store2;
}
* NOT ADVISED but also an option: static *
you can also create a static one, even make it public, however public access is not the nicest way. Better keep it private and work with function as above to get it. In normally would not advice static usage like this... but assuming the MainFrame is the main program... in this case there might be an exception on the not to use static ....
private static Store store;
or
public static Store store;
than you can access it from everywhere by:
MainJFrame.store
* end static remark *
but maybe you just meant this:
public putStore(Store store){
this.store=store;
}
so you can create it in other class, and get it from other classes
in the other class to create it you migth even first get it (init it in the mainFrame with null:
private Store store=null;
in the other class:
Store store = mainframe.getStore();
// code to create it
or only create it if not yet created:
if (store==null){
// Only create if still null
// code to create it here
}
// and here use it, just created or not
Migth be a weird and 'know it all' like advice, but:
all of the above is basic java knowledge about public, private, static and so on.... might look in to some tutorials, to understand the basic things.
Java can be a pain in the... in case you do not understand it (memory leaks and so on...) so please be sure you know what you do.... (in case you want to use it professionaly)
In java there is a big difference in declaring it, and initialising it:
this is a declaration:
private Store store:
this is the init:
store = // something, even putting it to null is an init
and the combination of declare and init:
private Store store=null;
the last one you need before you can call it from other classes, because you actually will not get the object, but a pointer tot the object.
To have a pointer, you need tot init it, than init to null is enough.... so there is at least a pointer.
Understanding the way of pointers and how things are passed in java, will save some memory issues in bigger programs.
Inject this Store instance into the MainJFrame constructor.
The Store class will hold the data and you can access it through get methods.
Have you thought about that?
I have a general question about java. Because I want to create StronaGlowna.java (class) where I have place all buttons, check box and other GUI component which I want to display in main class. The first question is this right way, it's correct ? or maybe is better way to do this thing. My code look this:
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class Main extends JFrame {
private static final long serialVersionUID = -4575271483481196192L;
Container pane;
CardLayout layout;
public Main() throws FileNotFoundException, IOException {
layout = new CardLayout();
setLayout(layout);
pane = this.getContentPane();
/*Page: Strona główna */
JPanel newPanel = new JPanel();
pane.add("New", newPanel);
JButton przycisk = new JButton("Przycisk");
newPanel.add(przycisk);
...
In "pane.add("New", newPanel);" I want to display elements from:
package aplikacja.glowna;
import javax.swing.JButton;
import javax.swing.JPanel;
public class StronaGlowna {
public void StronaGlownaDisplay() {
JPanel newPanel = new JPanel();
JButton przycisk2 = new JButton("Przycisk");
newPanel.add(przycisk2);
}
}
Can I import/display all class StronaGlowna in main() something like a include in PHP ? What do You thing about my idea, it's correct or I'm wrong ? Thanks for help and discussion.
It sounds like the way Netbeans handling GUI. You may view the article in http://netbeans.org/kb/docs/java/quickstart-gui.html, it may help you understand how the GUI works since Netbeans can generate code for you. You can always import class and create object to access methods (often public methods) . I think it is not like a include in PHP. PHP include is like to directly include the source code, but jave is not.
First - Never, never, never, code in Main class. Call a method from it and then start your staff in another class. And, of course, don't extend it. And the constructor is neither a good idea. All of these are bad practices. Now, going into your problem, my suggestion is that you make StronaGlowna extend JPanel, and then obtain an instance of it through a public constructor, and use that instance as the parameter for the constructor of JScrollPane. That will make the scrollPane act as a 'screen' inside which you can see the contents of StronaGlowna, which is what I understand you're after.
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.