Good evening.
I have a problem using NetBeans v 11.1 for Windows.
I try to open two Frame Forms when the user select an item from a Combo Box.
The forms I want open have a string param in their constructors.
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
// TODO add your handling code here:
Visualizza visualizza = new Visualizza(this.auth);
Inserisci inserisci = new Inserisci(this.auth);
var getItem = jComboBox1.getSelectedItem();
switch(getItem.toString()){
case ("Visualizza Iscritti nel Sistema"):
visualizza.setVisible(true);
break;
case ("Inserisci Atleti nel Sistema"):
inserisci.setVisible(true);
break;
default:
break;
}
} catch (IOException ex) {
Logger.getLogger(Select.class.getName()).log(Level.SEVERE, null, ex);
}
}
The constructors code is:
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ButtonGroup;
import org.json.*;
public class Visualizza extends javax.swing.JFrame {
//Attributes declaration
...
public Visualizza(String auth) throws IOException {
initComponents();
btnRicerca.setVisible(false);
txtField.setVisible(false);
this.auth = auth;
Player[] player;
Requests r = new Requests("https://www.kingofthecage.it/API/getAllPlayers.php", auth);
r.sendGet();
if (r.res.equals("Errore") || r.res.equals("[]"))
{
List.removeAll();
List.add(errorMessage);
}
else
{
JSONArray arr = new JSONArray(r.res);
player = new Player[arr.length()];
String[] list = new String[arr.length()];
for (int i = 0; i < arr.length(); i++)
{
String id = arr.getJSONObject(i).getString("ID");
String name = arr.getJSONObject(i).getString("NOME");
String surname = arr.getJSONObject(i).getString("COGNOME");
String date = arr.getJSONObject(i).getString("DATA_NASCITA");
String birthplace = arr.getJSONObject(i).getString("LUOGO_NASCITA");
String residence = arr.getJSONObject(i).getString("RESIDENZA");
String cf = arr.getJSONObject(i).getString("CODICE_FISCALE");
String mail = arr.getJSONObject(i).getString("MAIL");
String mobile = arr.getJSONObject(i).getString("CELLULARE");
String team = arr.getJSONObject(i).getString("NOME_SQUADRA");
player[i] = new Player(id, name, surname, date, birthplace, residence, cf, mobile, mail, team);
List.add(list[i] = player[i].getPlayerString());
}
}
I import the library org.json to parse and interact with a response from a server, called with an HTTP Request and in the for cycle I returned params in a class called Player.
If I run the project from NetBeans works perfectly, the issue come when I build the project and I try to execute the .jar file saved in "./dist" folder. Substantially when I select a value from the ComboBox nothing happens but, as i've said, if I try to run the same code in NetBeans IDE it works.
I specify that I never change any setting from NetBeans IDE.
I hope you can solve my problem!
I'm new to programming and I've, like an idiot, decided to have my first project to be one way beyond my level. I haven't had much success trying to find a solution to this problem on the site yet, so I'm asking.
So, I have a button that creates a file with a name from user input and then creates directories that include that file. It's in class "NewProject".
JButton btnNewButton = new JButton("Create");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String projectName = textPane.getText();
File projectFolder = new File("C:\\Jibberish\\" + projectName);
File projectStart = new File("C:\\Jibberish\\" + projectName +
"\\" + "Project" + "\\" + "text.rtf");
Now, in another class, "workspace", I have a JTree and a JEditorPane. I want to know how I can get a variable like "projectStart" in the "workspace" class so I could use the directory as a model for the JTree and the file "text.rtf" as the default text in the JEditor.
If more info is needed, I'll try to provide it.
Please answer as if I don't know anything because I don't. Thanks in advance.
Not sure if I got you correctly but for handing projectStart over into workspace.class you could create a private class-variable and create a getter-method for it.
private File projectStart = null;
private void buttonAction(){ //this is where your ActionListener stuff happens
JButton btnNewButton = new JButton("Create");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String projectName = textPane.getText();
File projectFolder = new File("C:\\Jibberish\\" + projectName);
projectStart = new File("C:\\Jibberish\\" + projectName +
"\\" + "Project" + "\\" + "text.rtf");
}
public File getProjectStart(){ //this method makes your projectStart-variable accessible for other classes
return projectStart;
}
In your workspace class you can then use this variable by calling it similar to this:
private void foo(){
NewProject np = new NewProject();
File copyOfProjectStart = np.getProjectStart();
}
Hope this helps you.
Background :
I started playing with Groovy recently and am trying to embed a groovy script engine in an eclipse plugin to let my customers develop their own GUI extensions inside my eclipse-based product. This is very similar to the success story published on codehaus's website.
Problem
The groovy script (let's call it "main_eclipse.groovy") run from the eclipse plugin by a GroovyScriptEngine throws when trying to load a groovy class ("SwtGuiBuilder"), with the following error :
BUG! Queuing new source whilst already iterating. Queued source is 'file:/home/nicolas/workspace/groovy-test/src/gui/SwtGuiBuilder.groovy'
Question
Did anyone run into the same problem ? How can it be fixed ?
Any help will be highly appreciated !
Some observations :
When using the groovy interpreter instead of a GroovyScriptEngine java object, I have no problem using my SwtGuiBuilder class (see script "main_groovy" here below).
My problem does not seem to be a classpath issue, since the file containing my SwtGuiBuilder class is mentioned in the thrown exception.
The error message is mentioned in two reported groovy bugs, GRECLIPSE-429 and GRECLIPSE-1037. I did not fully get the technicals details, but those bugs seemed to be related to performance issues when loading lots of classes, which is not relevant in my situation...
Details
SampleView.java
public class SampleView
{
public SampleView() { super(); }
public void createPartControl(Composite parent)
{
String groovyScript = null;
String [] groovyPath = null;
boolean shall_exit = false;
do
{ // ask user for params
GroovyLocationDialog groovyLocationDialog= new GroovyLocationDialog(parent.getShell() );
int return_code = groovyLocationDialog.open();
if ( return_code != Window.OK )
shall_exit = true;
else
{
groovyScript= groovyLocationDialog.getInputScriptName();
groovyPath = groovyLocationDialog.getInputScriptPath();
// run it
ScriptConnector scriptConnector = new ScriptConnector(parent);
try { scriptConnector.runGuiComponentScript( groovyPath, groovyScript); }
catch (Exception e) { e.printStackTrace(); }
System.out.println("script finished");
}
}
while ( ! shall_exit );
}
ScriptConnector.java
public class ScriptConnector
{
private String[] roots;
private Composite window;
private Binding binding;
public ScriptConnector( Composite window )
{
this.window = window;
Binding scriptenv = new Binding(); // A new Binding is created ...
scriptenv.setVariable("SDE", this);
scriptenv.setVariable("WINDOW", this.window); // ref to current window
this.binding = scriptenv;
}
public void runGuiComponentScript(final String[] groovyPath, final String scriptName)
{
GroovyScriptEngine gse = null;
this.roots = groovyPath;
try
{
// instanciating the script engine with current classpath
gse = new GroovyScriptEngine( roots, this.getClass().getClassLoader() );
gse.run(scriptName, binding); // ... and run specified script
}
catch (Exception e) { e.printStackTrace(); }
catch (Throwable t) { t.printStackTrace(); }
}
}
main_eclipse.groovy
package launcher;
import org.eclipse.swt.SWT
import org.eclipse.swt.widgets.*
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.RowLayout as Layout
// This import will fail...
import gui.SwtGuiBuilder;
WINDOW.layout = new Layout(SWT.VERTICAL);
def builder = new SwtGuiBuilder(WINDOW);
builder.Label ( style=SWT.NONE, text = 'Simple demo of Groovy and SWT')
builder.Button( style=SWT.PUSH, text = 'Click me' , action = { println "Click !" } )
SwtGuiBuilder.groovy
package gui;
import org.eclipse.swt.events.*
import org.eclipse.swt.widgets.Button
import org.eclipse.swt.widgets.Composite
import org.eclipse.swt.widgets.Label
class SwtGuiBuilder
{
private Composite _parent
public SwtGuiBuilder(Composite parent) { _parent = parent }
public void Button( style = SWT.PUSH, text= null, action = null )
{
def btn = new Button(_parent, style)
if ( text != null )
btn.text = text
if (action != null)
btn.addSelectionListener( new SelectionAdapter() { void widgetSelected( SelectionEvent event ) { action(); } } );
}
public void Label( style = SWT.NONE, text = '' )
{
def lbl = new Label(_parent, style)
lbl.text = text
}
}
main_groovy.groovy
package launcher;
import org.eclipse.swt.SWT
import org.eclipse.swt.widgets.*
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.RowLayout as Layout
// ... But this import is handled properly !
import gui.SwtGuiBuilder;
def display = new Display()
def WINDOW = new Shell(display)
WINDOW.text = 'Groovy / SWT Test';
WINDOW.layout = new Layout(SWT.VERTICAL);
def builder = new SwtGuiBuilder(WINDOW);
builder.Label ( style=SWT.NONE, text = 'Simple demo of Groovy and SWT')
builder.Button( style=SWT.PUSH, text = 'Click me' , action = { println "Ya clicked me !" } )
WINDOW.pack();
WINDOW.open();
while (!WINDOW.disposed) {
if (!WINDOW.display.readAndDispatch())
WINDOW.display.sleep();
}
Stack trace
BUG! Queuing new source whilst already iterating. Queued source is 'file:/home/nicolas/workspace/groovy-test/src/gui/SwtGuiBuilder.groovy'
at org.codehaus.groovy.control.CompilationUnit.addSource(CompilationUnit.java:460)
at org.codehaus.groovy.control.CompilationUnit.addSource(CompilationUnit.java:433)
at groovy.util.GroovyScriptEngine$ScriptClassLoader$3.findClassNode(GroovyScriptEngine.java:195)
at org.codehaus.groovy.control.ClassNodeResolver.resolveName(ClassNodeResolver.java:124)
at org.codehaus.groovy.control.ResolveVisitor.resolveToOuter(ResolveVisitor.java:863)
at org.codehaus.groovy.control.ResolveVisitor.resolve(ResolveVisitor.java:377)
at org.codehaus.groovy.control.ResolveVisitor.visitClass(ResolveVisitor.java:1407)
at org.codehaus.groovy.control.ResolveVisitor.startResolving(ResolveVisitor.java:202)
at org.codehaus.groovy.control.CompilationUnit$1.call(CompilationUnit.java:713)
at org.codehaus.groovy.control.CompilationUnit.applyToSourceUnits(CompilationUnit.java:1015)
at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:647)
at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:596)
at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:279)
at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:258)
at groovy.util.GroovyScriptEngine$ScriptClassLoader.doParseClass(GroovyScriptEngine.java:247)
at groovy.util.GroovyScriptEngine$ScriptClassLoader.parseClass(GroovyScriptEngine.java:229)
at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:244)
at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:202)
at groovy.util.GroovyScriptEngine.loadScriptByName(GroovyScriptEngine.java:514)
at groovy.util.GroovyScriptEngine.createScript(GroovyScriptEngine.java:564)
at groovy.util.GroovyScriptEngine.run(GroovyScriptEngine.java:551)
My configuration :
Linux Ubuntu 14.04 x86
Groovy Version: 2.3.2
JVM: 1.7.0_55
Eclipse Kepler SR2 - Build 20140224-0627
Eclipse Groovy plugin v2.0.7
Instead of GroovyScriptEngine, I've used the GroovyShell class (groovy code below but easy enough to change back to java), CompilerConfiguration allows you to specify the classpath.
def config = new CompilerConfiguration(classpath: classpath)
def binding = new Binding()
def result = new GroovyShell(binding, config).evaluate("""
def foo='bar'
""")
I have developed a small JApplet for a site.
It's the first time I do such a thing, so it's probably a stupid error or misundestanding, but I can't find out what it is.
Here is the first class called from the HTML:
public class MapGenerator extends JApplet {
private static final long serialVersionUID = 1L;
private int numero_immagini;
private BufferedImage[] images;
private int[] floors;
private static final String N_IMMAGINI = "numero_immagini";
private static final String IMMAGINE = "immagine";
private static final String PIANO_IMMAGINE ="numero_piano";
public void init() {
numero_immagini = Integer.parseInt(this.getParameter(N_IMMAGINI));
images = new BufferedImage[numero_immagini];
floors = new int[numero_immagini];
for(int i=0; i< numero_immagini; i++) {
try {
URL url = new URL(this.getParameter(IMMAGINE+i));
images[i] = ImageIO.read(url);
floors[i] = Integer.parseInt(this.getParameter(PIANO_IMMAGINE+i));
} catch (IOException ioe) {}
}
}
public void start() {
Editor ed = new Editor(this.getContentPane(), images, floors);
this.setSize(400, 400);
this.add(ed.getPanel());
Toolkit kit = this.getToolkit();
Dimension dim = kit.getScreenSize();
this.setBounds(dim.width/4, dim.height/4, dim.width/4, dim.height/4);
this.setVisible(true);
this.repaint();
}
}
And here is the HTML:
<applet code="MapGenerator.class"
archive="MapGenerator.jar"
width= 400 height = 200>
<param name=numero_immagini value=1>
<param name=immagine0 value="IMG_20111009_171138.jpg">
<param name=numero_piano0 value=0>
</applet>
In Eclipse I haven't any problem at all, but when I tried with Chrome the page show only a gray box.
Thank to all for help.
EDIT
The app cannot load images from the link that I pass.
It trows, testing with a random link image
java.security.AccessControlException: access denied (java.net.SocketPermission www.hyros.net:80 connect,resolve)
java.lang.NullPointerException
The problem is the code, and not the way I use HTML, the jar file or other things, so I opened a new question here, to describe the problem in a more correct way.
Thank you for your answers.
here is my entire class. I read data from a text file, put them into an aeeaylist. then from that array list i want to show the data on a JTable, when the specific method is called.But is doesnt show anything
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author George
*/
import java.awt.*;
import java.util.ArrayList;
//import java.io.FileInputStream;
//import java.io.FileNotFoundException;
//import java.io.EOFException;
//import java.io.IOException;
//import java.io.ObjectInputStream;
/*import java.io.File;
import java.lang.IllegalStateException;
import java.util.NoSuchElementException;
import java.util.Scanner;
import javax.swing.JOptionPane;*/
import java.io.*;
//import java.util.Locale;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class Company extends JFrame {
private ArrayList<Employee> emp=new ArrayList<Employee>();
//Employee[] list=new Employee[7];
public void getEmployees(Employee emplo){
emp.add(emplo);
}
/*public void openTxt(){
try {
Scanner input=new Scanner(new File("Employees.txt"));
}
catch(FileNotFoundException e){
JOptionPane.showMessageDialog(null, "File Not Found.");
System.exit(1);
}
}*/
public void doRead() throws Exception{
//ArrayList<Employee> emp=new ArrayList<Employee>() ;
//Employee[] emp=new Employee[7];
//read from file
File data = new File("src/Employees.txt");
BufferedReader read = new BufferedReader(new FileReader(data));
String input;
int i = 0;
//int salesmen = 0;
while ((input = read.readLine()) != null) {
String [] lineParts = input.split(",");
/**
* the following block converts some of the strings inputted to
* the appropriate vartypes.
*/
String EmpNo=(lineParts[0]);
String type=lineParts[10];
String PostalCode = (lineParts[5]);
int phone = Integer.parseInt(lineParts[6]);
short DeptNo = (short) Integer.parseInt(lineParts[8]);
double Salary;
short card = (short) Integer.parseInt(lineParts[11]);
int dtype=0;
if(type.equals("FULL TIME")){
dtype=1;
}
else if(type.equals("SELLER")){
dtype=2;
}
else
dtype=3;
/**
* Creates employee instances depending on their type of employment
* (fulltime=1, parttime=3, salesman=2)
*/
switch (dtype) {
case 1 :
//empNo,firstname, lastname, address, city, PostalCode, phone,
//email, deptcode,Jobtype, salary, TimecardId, hoursW
Salary = Double.parseDouble(lineParts[10]);
emp.add(new FullTimeEmployee(EmpNo,lineParts[1], lineParts[2], lineParts[3],
lineParts[4], PostalCode, phone,
lineParts[7], DeptNo,type,Salary, card, 0.0));
i++;
break;
case 2 :
Salary = Double.parseDouble(lineParts[10]);
ArrayList<Orders> orders=new ArrayList<Orders>();
Salary = Double.parseDouble(lineParts[10]);
emp.add(new Salesman(EmpNo,lineParts[1], lineParts[2], lineParts[3],
lineParts[4], PostalCode, phone,
lineParts[7], DeptNo,type,Salary, card, 0.0, orders));
i++;
break;
case 3 :
Salary = Double.parseDouble(lineParts[10]);
emp.add(new PartTimeEmployee(EmpNo,lineParts[1], lineParts[2], lineParts[3],
lineParts[4], PostalCode, phone,
lineParts[7], DeptNo,type,Salary, card, 0.0));
i++;
break;
default :
break;
}
}
}
public ArrayList<Employee> getArray(){
return emp;
}
//test methodos gia tin proti epilogi-den deixnei tipota omws sto JTable ????
public /*JTable */ void getOptionA(){
ArrayList<Employee> list=getArray();
/*String[] columnNames = {"Code","First Name","Last Name","Address","Cisty","Postal Code","Phone","Email",
"Dept Code","Salary","Time Card","Hours"};*/
/* Object[][] data;
*/
JTable table = new JTable();
DefaultTableModel model = new DefaultTableModel();
table.setModel(model);
model.setColumnIdentifiers(new String[] {"Code","First Name","Last Name","Address","City","Postal Code","Phone","Email",
"Dept Code","Salary","Time Card","Hours"});
for( Employee current : list){
model.addRow(new Object[] {current.getCode(),current.getName(),current.getSurname(),
current.getAddress(),current.getCity(),current.getTK(),
current.getPhone(),current.getMail(),current.getDeptCode(),
current.getSalary(),current.getCard(),current.getHours()
});
}
/*JScrollPane scrollPane = new JScrollPane(table);
table.setFillsViewportHeight(true);*/
//return table;
table.setPreferredScrollableViewportSize(new Dimension(500,50));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}
public void showOptionA(){
getOptionA();
Company gui =new Company();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setVisible(true);
gui.setSize(600, 400);
}
}
I call showOptionA() from a JButton located on another JFrame Class.
private void showEmployeesActionPerformed(java.awt.event.ActionEvent evt) {
Results showEmp=new Results();
//showEmp.setVisible(true);
//showEmp.setOptions(1);
Company company=new Company();
/*JTable table=company.getOptionA();
JScrollPane scrollPane = new JScrollPane(table);
table.setFillsViewportHeight(true);
scrollPane.setViewportView(table);
table.setVisible(true);*/
company.showOptionA();
}
Basically i have a "main"JFrame with different options, and each button,representing a different option, calls the appropriate option method from Company Class.
When i click on the button "Show Employees Status". i want it to show the JTable above. Instead a new Frame opens but is blank??
EDIT: if i change showOptionA() to static, and then just call it inside showEmployeesActionPerformed , ( which is located in class PayrollForm)
public static void showOptionA(){
Company gui =new Company();
gui.getOptionA();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setVisible(true);
gui.setSize(600, 400);
}
i now see the columns but with no data(empty)
This has nothing to do with calling revalidate as recommended by another and likely has all to do with calling a method on the wrong object. In your showEmployeesActionPerformed method you create a new Company object, one that is not visualized. The key is to call this method on the proper reference, on the visualized GUI. You do this by passing a reference to the visualized GUI object into the class that is wanting to call methods on it. This can be done via a setCompany method:
setCompany(Company company) {
this.company = company);
}
or via a constructor parameter.
I think the reason is your method showOptionA():
first you add your JTable and Model to your Company Object, which is your Frame. But right after it, you create a new Company Object, set the wanted Frame settings and show that object instead of your first Company object, where the table is.
You just could leave the gui thing out, and set DefaultCloseOperation directly on your Company object and set it visible true.
Some other suggestions:
You also should set the size of your frame, before you set it visible true.
And getters normally just give back the related object, instead of putting it on some list.
Might be there are some more mistakes in it, but it should at least show your table.
Call revalidate() after adding anything to JTable (or its model).
Ok problem Solved!. The problem was in getOptionA() method.
i set the model of the Jtable, but not the option to be visible. SO thats why it appeared empty. I corrected this by moving
try {
//try to read from text file
doRead();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, "An Exception has Occured! The application will now close.");
System.exit(0);
}
table.revalidate();
add(scrollPane);
setVisible(true);
setSize(600, 400);
up,from showOptionA, up to getOptionA() method. By doing this showOptionA becomes useless(and thus i deleted it). Now i call getOptionA from the showEmployeesActionPerformed and its all ok :). Thanks to all people who replied to my wuestion, and special thanks to Hovercraft Full Of Eels . He helped me undeestand why the table wasnt appearing the way i wanted it to