Display all deserialized Objects in JTable in JAVA - java

i want to show all objects in a table.
i have a folder named /menschen which contains files like this: "firstname.lastname.ser"
package adressverwaltung;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JOptionPane;
// FILE
import java.io.*;
import java.util.*;
import java.util.Formatter;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.awt.HeadlessException;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
/**
*
* #author
*/
public class Adressverwaltung {
JFrame mainWindow;
final File folder = new File("menschen");
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Adressverwaltung verweiss = new Adressverwaltung();
verweiss.main();
}
public void main() {
mainWindow = new JFrame();
mainWindow.setBounds(0, 0, 800, 400);
mainWindow.setLocationRelativeTo(null);
mainWindow.setLayout(null);
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setResizable(false);
mainWindow.setVisible(true);
mainWindow.setLayout(new FlowLayout());
menu();
}
public String deserialize(String m, int field) {
try {
FileInputStream fin = new FileInputStream("menschen\\" + m);
ObjectInputStream ois = new ObjectInputStream(fin);
Person n = (Person) ois.readObject();
ois.close();
switch (field) {
case 1:
return n.vorname;
case 2:
return n.nachname;
}
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static void table(String[][] alle) {
String[] columnNames = {
"Vorname", "Nachname"
};
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTable table = new JTable(alle, columnNames);
f.add(new JScrollPane(table));
f.pack();
f.setVisible(true);
}
private static void serialize(Person m) {
try {
FileOutputStream fileOut =
new FileOutputStream("menschen\\" + m.vorname + "." + m.nachname + ".ser");
ObjectOutputStream out =
new ObjectOutputStream(fileOut);
out.writeObject(m);
out.close();
fileOut.close();
} catch (IOException i) {
}
}
public void menu() {
JPanel list = new JPanel();
list.setBorder(BorderFactory.createLineBorder(Color.black));
list.setPreferredSize(new java.awt.Dimension(400, 360));
list.setBackground(Color.white);
mainWindow.add(list);
// Wir lassen unseren Dialog anzeigen
mainWindow.setVisible(true);
int ButtonWidth = 100;
int ButtonHeight = 30;
int ButtonTop = 10;
JButton Button1 = new JButton("List all");
JButton Button3 = new JButton("Search");
Button1.setBounds(10, ButtonTop, ButtonWidth, ButtonHeight);
Button3.setBounds(230, ButtonTop, ButtonWidth, ButtonHeight);
list.add(Button1);
list.add(Button3);
mainWindow.add(list);
createForm();
Button1.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
list(folder);
}
});
}
public void list(final File folder) {
String[][] rowData = new String[3][];
int r = 0;
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
} else {
String name = fileEntry.getName();
rowData[r][0] = deserialize(name, 1);
rowData[r][1] = deserialize(name, 2);
r++;
}
}
table(rowData);
}
private void createForm() {
JPanel p = new JPanel();
p.setLayout(new GridLayout(3, 2));
JButton b = new JButton("Neue Person!");
JLabel vornameLabel = new JLabel("Vorname:");
final JTextField vorname = new JTextField();
JLabel nachnameLabel = new JLabel("Nachname:");
final JTextField nachname = new JTextField();
p.add(vornameLabel);
p.add(vorname);
p.add(nachnameLabel);
p.add(nachname);
p.add(b);
p.setBorder(BorderFactory.createLineBorder(Color.black));
p.setPreferredSize(new java.awt.Dimension(300, 100));
p.setBackground(Color.white);
mainWindow.add(p);
// Wir lassen unseren Dialog anzeigen
mainWindow.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Person m = new Person(vorname.getText(), nachname.getText());
serialize(m);
JOptionPane.showMessageDialog(null, vorname.getText() + "." + nachname.getText() + ".ser abgespeichert.", "Tutorial 2", JOptionPane.INFORMATION_MESSAGE);
}
});
}
}
And this is my Person class:
package adressverwaltung;
/**
*
* #author Mahshid
*/
class Person implements java.io.Serializable {
// Allgemeine Kontaktinformationen:
public String vorname;
public String nachname;
// Adresse
public String strasse;
public int hausnummer;
public int postleitzahl;
public String ort;
public String land;
// Telefon
public int mobil;
public int festnetz;
// Email & Kommentar
public String mail;
public String kommentar;
Person(String vorname, String nachname) {
this.vorname = vorname;
this.nachname = nachname;
}
}
I think there is a problem in list() function. this is my first java code so please don't be surpriced if you see any big mistakes :)

By creating a 2D array like this:
String[][] rowData = new String[3][];
you are creating an array where where all the "column" data is not initialized. You can check this for yourself by doing:
for (String[] s: rowData) {
System.out.println(s);
}
Therefore attempting to assign any of the outer array elements to a single String is impossible:
rowData[r][0] = deserialize(name, 1);

Related

how can i capture data from one class and pass it around all classes

i have a multi class program, with each class having its own GUI, my task is to capture details from a class called dataInput and the data must be captured into variables of a class called studentRecords, i must capture about 10 records comprised of name, surname, student number and tests from 1-4, i have a class called RecordsMenu which have Buttons that call the different classes, for example, when i click dataInput button it calls the DataInput class, in the datainput class i must capture data into records class, then i must go back to recordsMenu screen, from there! when i click for example, the display Button , i must be able to see the data i captured, the problem i have is that, when ever i go back to the main screen , all the data i captured get lost and it print nulls when i test whether it captured or not, i will appreciate any kind of help, my code is below.this must be done with out using files, thank you
[here is the picture of the main screen of my application][1]
enter code here
[1]: https://i.stack.imgur.com/I6JyI.jpg
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.*;
public class InputDetails extends JPanel
{
JLabel title,name,surname,studentno,tests,t1,t2,t3,t4;
JTextField nametxf,surnametxf,studentnotxf,t1txf,t2txf,t3txf,t4txf;
JButton submit,home;
JPanel buttons, mainPanel, labels;
public InputDetails()
{
// title
title = new JLabel("Records Menu",SwingConstants.CENTER);
title.setForeground(Color.BLUE);
Font newLabelFont =new Font("Serif",Font.BOLD,70);
title.setFont(newLabelFont);
// buttons and actions
submit = new JButton("Submit");
submit.addActionListener(new Handler());
home = new JButton("Home");
home.addActionListener(new Handler());
//labels
name = new JLabel("Name");
surname = new JLabel("Surname");
studentno= new JLabel("Student Number");
tests = new JLabel("Tests");
// tests
t1 = new JLabel("Test 1");
t2 = new JLabel("Test 2");
t3 = new JLabel("Test 3");
t4 = new JLabel("Test 4");
//textfields
nametxf = new JTextField(10);
surnametxf = new JTextField(10);
studentnotxf = new JTextField(10);
t1txf= new JTextField(10);
t2txf= new JTextField(10);
t3txf= new JTextField(10);
t4txf= new JTextField(10);
buttons = new JPanel(new GridLayout(1,2,5,5));
buttons.add(submit);
buttons.add(home);
// fields
labels = new JPanel(new GridLayout(7,1,5,5));
labels.add(name);
labels.add(nametxf);
labels.add(surname);
labels.add(surnametxf);
labels.add(studentno);
labels.add(studentnotxf);
labels.add(t1);
labels.add(t1txf);
labels.add(t2);
labels.add(t2txf);
labels.add(t3);
labels.add(t3txf);
labels.add(t4);
labels.add(t4txf);
//
mainPanel = new JPanel(new BorderLayout(5,5));
mainPanel.add(title,BorderLayout.NORTH);
mainPanel.add(labels,BorderLayout.WEST);
mainPanel.add( buttons,BorderLayout.SOUTH);
add(mainPanel);
}
class Handler implements ActionListener
{
public void actionPerformed(ActionEvent click)
{
if(click.getSource()==home)
{
// back to main view
mainPanel.setVisible(false);
add(new RecordsMenu());
}
else if(click.getSource()==submit)
{
String name,surname,studentno;
int test1,test2,test3,test4;
name = nametxf.getText();
surname = surnametxf.getText();
studentno=studentnotxf.getText();
test1 =Integer.parseInt(t1txf.getText());
test2 = Integer.parseInt(t2txf.getText());
test3 = Integer.parseInt(t3txf.getText());
test4 = Integer.parseInt(t4txf.getText());
StudentRecords records = new StudentRecords(name,surname,studentno,test1,test2,test3,test4);
}
}
}
}
import java.io.*;
import javax.swing.JOptionPane;
public class StudentRecords {
String name , Surname, studentno;
int test1,test2,test3,test4;
FileWriter records;
PrintWriter out;
public StudentRecords(String Name, String Surname,String StudentNo,int t1, int t2, int t3, int t4)
{
setName(Name);
setSurname(Surname);
setStudentno(StudentNo);
setTest1(t1);
setTest2(t2);
setTest3(t3);
setTest4(t4);
// saveRecords();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return Surname;
}
public void setSurname(String surname) {
Surname = surname;
}
public String getStudentno() {
return studentno;
}
public void setStudentno(String studentno) {
this.studentno = studentno;
}
public int getTest1() {
return test1;
}
public void setTest1(int test1) {
this.test1 = test1;
}
public int getTest2() {
return test2;
}
public void setTest2(int test2) {
this.test2 = test2;
}
public int getTest3() {
return test3;
}
public void setTest3(int test3) {
this.test3 = test3;
}
public int getTest4() {
return test4;
}
public void setTest4(int test4) {
this.test4 = test4;
}
}
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.*;
public class ReadFile extends JPanel{
private JButton read,back;
private JTextArea desplay;
private JLabel title;
private JPanel mainpanel, buttons;
String record,student1,student2,student3,student4,student5,student6,student7,student8,student9,student10;
public ReadFile()
{
// title
title = new JLabel("Read File Contents",SwingConstants.CENTER);
Font newLabelFont =new Font("Serif",Font.BOLD,30);
title.setFont(newLabelFont);
// textarea
desplay = new JTextArea();
// buttons
read = new JButton("Open");
read.addActionListener(new Handler());
back = new JButton("back to main");
back.addActionListener(new Handler());
// panel
buttons = new JPanel(new GridLayout(1,2,5,5));
buttons.add(read);
buttons.add(back);
mainpanel = new JPanel(new BorderLayout(5,5));
mainpanel.add(title,BorderLayout.NORTH);
mainpanel.add(desplay,BorderLayout.CENTER);
mainpanel.add(buttons,BorderLayout.SOUTH);
add(mainpanel);
}
class Handler implements ActionListener
{
#Override
public void actionPerformed(ActionEvent click) {
if(click.getSource()==read)
{
JFileChooser chooser = new JFileChooser();
Scanner input = null;
if(chooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION)
{
File selectedFile = chooser.getSelectedFile();
try {
input = new Scanner(selectedFile);
while(input.hasNextLine())
{
record = input.nextLine();
desplay.append(record);
desplay.append("\n");
}
}catch(IOException fileerror) {
JOptionPane.showMessageDialog(null, "you have an error");
}
}
}
else if(click.getSource()==back)
{
mainpanel.setVisible(false);
add(new RecordsMenu());
}
}
}
}
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class Search extends JPanel
{
DisplayDetails d = new DisplayDetails();
JLabel title,stdn;
JTextField studentno;
JPanel mainp,details,buttons;
JButton search,home;
Scanner input;
File records;
String key;
String line;
boolean wordfound = false;
public Search()
{
// title
title = new JLabel("Search a Student",SwingConstants.CENTER);
Font newLabelFont =new Font("Serif",Font.BOLD,30);
title.setFont(newLabelFont);
stdn = new JLabel("Student Number");
studentno = new JTextField(10);
//
search = new JButton("Search");
search.addActionListener(new Handler());
home = new JButton("Home");
mainp = new JPanel(new BorderLayout());
details = new JPanel(new GridLayout(1,2));
details.add(stdn);
details.add(studentno);
buttons = new JPanel(new GridLayout(1,2));
home.addActionListener(new Handler());
buttons.add(search);
buttons.add(home);
mainp.add(title,BorderLayout.NORTH);
mainp.add(details,BorderLayout.WEST);
mainp.add(buttons,BorderLayout.SOUTH);
add(mainp);
}
class Handler implements ActionListener
{
public void actionPerformed(ActionEvent button)
{
if(button.getSource()==search)
{
// define the key
key = studentno.getText();
if(key.matches("^2\\d{8}"))
{
File file =new File("StudentRecords.txt");
Scanner in;
try {
in = new Scanner(file);
while(in.hasNextLine())
{
line=in.nextLine();
if((line.contains(key))) {
wordfound=true;
break;
}
}
if((wordfound)) {
System.out.println(line);
mainp.setVisible(false);
add(d);
d.display.setText(line);
JOptionPane.showMessageDialog(null,"found");
}
else
{
JOptionPane.showMessageDialog(null,"not found");
}
in.close();
} catch(IOException e) {
}
}
else if(!(key.matches("^2\\d{8}")))
{
JOptionPane.showMessageDialog(null,"incorrect student number");
}
}
else if(button.getSource()==home)
{
mainp.setVisible(false);
add(new RecordsMenu());
}
}
}
// methods
public void RecordFOund()
{
}
public void notFound()
{
}
}
import javax.swing.*;
import java.awt.*;
public class Frame extends JFrame
{
public Frame()
{
setSize(500,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
add(new RecordsMenu());
// add(new Search());
setVisible(true);
}
}
try this
In the getter methods of the StudentRecords Class make them {return this.variable;}
as an example in the public int getTest1(){return this.test1;}

How to pass snapshots generated by a Frame Splitter as an input to another class in Java

I am converting a video into frames using a simple Frame splitter code and these are getting stored in a separate folder.
I want to pass these snapshots sequentially to another module (class) for processing. How Can i do this?
this is the code of the Frame Splitter:
package FrameSplitter;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import com.xuggle.mediatool.IMediaReader;
import com.xuggle.mediatool.MediaListenerAdapter;
import com.xuggle.mediatool.ToolFactory;
import com.xuggle.mediatool.event.IVideoPictureEvent;
import com.xuggle.xuggler.Global;
public class FrameSplitter {
public static final double SECONDS_BETWEEN_FRAMES = 2;
private static final String inputFilename = "C://Sample.mp4";
private static final String outputFilePrefix = "C://snapshots//mysnapshot";
private static int mVideoStreamIndex = -1;
// Time of last frame write
private static long mLastPtsWrite = Global.NO_PTS;
public static final long MICRO_SECONDS_BETWEEN_FRAMES =
(long)(Global.DEFAULT_PTS_PER_SECOND * SECONDS_BETWEEN_FRAMES);
public static void main(String[] args) {
IMediaReader mediaReader = ToolFactory.makeReader(inputFilename);
// stipulate that we want BufferedImages created in BGR 24bit color space
mediaReader.setBufferedImageTypeToGenerate(BufferedImage.TYPE_3BYTE_BGR);
mediaReader.addListener(new ImageSnapListener());
while (mediaReader.readPacket() == null) ;
}
private static class ImageSnapListener extends MediaListenerAdapter {
public void onVideoPicture(IVideoPictureEvent event) {
if (event.getStreamIndex() != mVideoStreamIndex) {
if (mVideoStreamIndex == -1)
mVideoStreamIndex = event.getStreamIndex();
else
return;
}
if (mLastPtsWrite == Global.NO_PTS)
mLastPtsWrite = event.getTimeStamp() - MICRO_SECONDS_BETWEEN_FRAMES;
if (event.getTimeStamp() - mLastPtsWrite >=
MICRO_SECONDS_BETWEEN_FRAMES) {
String outputFilename = dumpImageToFile(event.getImage());
double seconds = ((double) event.getTimeStamp()) /
Global.DEFAULT_PTS_PER_SECOND;
System.out.printf(
"at elapsed time of %6.3f seconds wrote: %s\n",
seconds, outputFilename);
// update last write time
mLastPtsWrite += MICRO_SECONDS_BETWEEN_FRAMES;
}
}
private String dumpImageToFile(BufferedImage image) {
try{
String outputFilename = outputFilePrefix +
System.currentTimeMillis() + ".png";
ImageIO.write(image, "png", new File(outputFilename));
return outputFilename;
}
catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
}
`
this is the code of the module which performs text extraction from images.. i need to pass the snapshots to this module
package tessgui;
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Window;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Properties;
import java.util.PropertyResourceBundle;
import javax.swing.UIManager;
public class Main
{
private static Hashtable preferences = new Hashtable();
public static final String TESS_PATH = "TesseractPath";
public static void main(String[] args)
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception ex)
{
ex.printStackTrace();
}
String tesseractPath = "";
readPreferences();
// tesseractPath = (String)preferences.get("TesseractPath");
tesseractPath = "C:/Tesseract-OCR/";
File tessLog = new File(tesseractPath + "\\tesseract.exe");
if (tessLog.canWrite())
{
System.out.println("Path valid : " + tesseractPath);
TessFrame tf = new TessFrame(tesseractPath);
tf.setTitle("Tesseract 1.00 GUI");
centerOnParent(tf);
tf.setVisible(true);
}
else
{
System.out.println("Path valid: " + tesseractPath);
TessFrame tf = new TessFrame("Enter Valid Tesseract Path");
centerOnParent(tf);
tf.setVisible(true);
}
}
public static void readPreferences()
{
Properties properties = System.getProperties();
Enumeration myEnum = properties.propertyNames();
while (myEnum.hasMoreElements())
{
String key = myEnum.nextElement().toString();
if (key.startsWith("Pianificatore")) {
preferences.put(key, properties.getProperty(key));
}
}
try
{
PropertyResourceBundle rb = new PropertyResourceBundle(new FileInputStream("tessgui.properties"));
myEnum = rb.getKeys();
while (myEnum.hasMoreElements())
{
String key = myEnum.nextElement().toString();
String value = (String)preferences.get(key);
if (value == null) {
preferences.put(key, rb.getString(key));
}
}
}
catch (FileNotFoundException ex)
{
System.out.println("File not found");
}
catch (IOException ex1) {}
}
public static void centerOnParent(Window window)
{
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
Rectangle r = ge.getMaximumWindowBounds();
Dimension dim = new Dimension(r.width, r.height);
Rectangle abounds = window.getBounds();
window.setLocation((dim.width - abounds.width) / 2, (dim.height - abounds.height) / 2);
}
}
front end of it
package tessgui;
import java.awt.Color;
import java.awt.Container;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.accessibility.AccessibleContext;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.GroupLayout.ParallelGroup;
import javax.swing.GroupLayout.SequentialGroup;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.LayoutStyle;
import javax.swing.LayoutStyle.ComponentPlacement;
public class TessFrame
extends JFrame
{
String tesseractPath = "";
java.util.List<File> selectedFiles;
private JButton aboutButton;
private JButton addFileButton;
private JPanel buttonPanel;
private JPanel cfgPanel;
private JButton changePathButton;
private java.awt.List fileList;
private JPanel fileListPanel;
private JLabel jLabel1;
private JLabel jLabel2;
private JScrollPane jScrollPane1;
private JPanel logPanel;
private JTextArea logTextArea;
private JLabel outputFileNameLabel;
private JTextField outputFileNameTextField;
private JButton quitButton4;
private JButton removeAllButton;
private JButton runButton;
private JTextField tessPathTextField;
public TessFrame(String tessPath)
{
this.selectedFiles = new ArrayList();
this.tesseractPath = tessPath;
initComponents();
this.tessPathTextField.setText(this.tesseractPath);
}
private void initComponents()
{
this.cfgPanel = new JPanel();
this.tessPathTextField = new JTextField();
this.jLabel1 = new JLabel();
this.changePathButton = new JButton();
this.outputFileNameLabel = new JLabel();
this.outputFileNameTextField = new JTextField();
this.fileListPanel = new JPanel();
this.fileList = new java.awt.List();
this.buttonPanel = new JPanel();
this.runButton = new JButton();
this.addFileButton = new JButton();
this.removeAllButton = new JButton();
this.quitButton4 = new JButton();
this.aboutButton = new JButton();
this.jLabel2 = new JLabel();
this.logPanel = new JPanel();
this.jScrollPane1 = new JScrollPane();
this.logTextArea = new JTextArea();
setDefaultCloseOperation(3);
this.jLabel1.setText("Tesseract Installation Path");
this.changePathButton.setText("...");
this.changePathButton.setToolTipText("Change Tesseract Installation Path");
this.changePathButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
TessFrame.this.changePathButtonActionPerformed(evt);
}
});
this.outputFileNameLabel.setText("Output File Name");
this.outputFileNameTextField.setText("= FileName.txt");
this.outputFileNameTextField.setEnabled(false);
GroupLayout cfgPanelLayout = new GroupLayout(this.cfgPanel);
this.cfgPanel.setLayout(cfgPanelLayout);
cfgPanelLayout.setHorizontalGroup(cfgPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(cfgPanelLayout.createSequentialGroup().addContainerGap().addGroup(cfgPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.jLabel1).addComponent(this.outputFileNameLabel)).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addGroup(cfgPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING, false).addComponent(this.outputFileNameTextField).addComponent(this.tessPathTextField, -1, 329, 32767)).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.changePathButton).addContainerGap(34, 32767)));
cfgPanelLayout.setVerticalGroup(cfgPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(cfgPanelLayout.createSequentialGroup().addContainerGap().addGroup(cfgPanelLayout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(this.jLabel1).addComponent(this.changePathButton).addComponent(this.tessPathTextField, -2, -1, -2)).addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED).addGroup(cfgPanelLayout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(this.outputFileNameLabel).addComponent(this.outputFileNameTextField, -2, -1, -2)).addContainerGap(20, 32767)));
this.jLabel1.getAccessibleContext().setAccessibleName("tessPathLabel");
this.changePathButton.getAccessibleContext().setAccessibleName("changePathButton");
GroupLayout fileListPanelLayout = new GroupLayout(this.fileListPanel);
this.fileListPanel.setLayout(fileListPanelLayout);
fileListPanelLayout.setHorizontalGroup(fileListPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.fileList, -1, 556, 32767));
fileListPanelLayout.setVerticalGroup(fileListPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.fileList, -1, 285, 32767));
this.buttonPanel.setBackground(new Color(204, 204, 255));
this.runButton.setText("RUN");
this.runButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
TessFrame.this.runButtonActionPerformed(evt);
}
});
this.addFileButton.setText("ADD FILE");
this.addFileButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
TessFrame.this.addFileButtonActionPerformed(evt);
}
});
this.removeAllButton.setText("REMOVE ALL");
this.removeAllButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
TessFrame.this.removeAllButtonActionPerformed(evt);
}
});
this.quitButton4.setText("QUIT");
this.quitButton4.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
TessFrame.this.quitButton4ActionPerformed(evt);
}
});
this.aboutButton.setText("About");
this.aboutButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt)
{
TessFrame.this.aboutButtonActionPerformed(evt);
}
});
this.jLabel2.setForeground(new Color(102, 102, 255));
this.jLabel2.setText("TessGUI-v0-20");
GroupLayout buttonPanelLayout = new GroupLayout(this.buttonPanel);
this.buttonPanel.setLayout(buttonPanelLayout);
buttonPanelLayout.setHorizontalGroup(buttonPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(buttonPanelLayout.createSequentialGroup().addContainerGap().addComponent(this.jLabel2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 63, 32767).addComponent(this.runButton).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.addFileButton).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.removeAllButton).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.quitButton4).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.aboutButton).addGap(46, 46, 46)));
buttonPanelLayout.setVerticalGroup(buttonPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(buttonPanelLayout.createSequentialGroup().addContainerGap().addGroup(buttonPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(buttonPanelLayout.createParallelGroup(GroupLayout.Alignment.BASELINE).addComponent(this.runButton).addComponent(this.addFileButton).addComponent(this.removeAllButton).addComponent(this.quitButton4).addComponent(this.aboutButton)).addComponent(this.jLabel2)).addContainerGap(-1, 32767)));
this.logTextArea.setColumns(20);
this.logTextArea.setForeground(SystemColor.textInactiveText);
this.logTextArea.setRows(5);
this.jScrollPane1.setViewportView(this.logTextArea);
GroupLayout logPanelLayout = new GroupLayout(this.logPanel);
this.logPanel.setLayout(logPanelLayout);
logPanelLayout.setHorizontalGroup(logPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 556, 32767).addGroup(logPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.jScrollPane1, -1, 556, 32767)));
logPanelLayout.setVerticalGroup(logPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addGap(0, 160, 32767).addGroup(logPanelLayout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.jScrollPane1, -1, 160, 32767)));
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(this.logPanel, -1, -1, 32767).addComponent(this.buttonPanel, -1, -1, 32767).addComponent(this.cfgPanel, -1, -1, 32767).addComponent(this.fileListPanel, -1, -1, 32767));
layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addComponent(this.cfgPanel, -2, -1, -2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.fileListPanel, -1, -1, 32767).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.buttonPanel, -2, -1, -2).addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(this.logPanel, -2, -1, -2)));
pack();
}
private void quitButton4ActionPerformed(ActionEvent evt)
{
System.exit(0);
}
private void addFileButtonActionPerformed(ActionEvent evt)
{
JFileChooser chooser = new JFileChooser();
int x = 0;
chooser.setCurrentDirectory(new File(this.tesseractPath));
int returnVal = chooser.showOpenDialog(this);
if (returnVal == 0)
{
File f = chooser.getSelectedFile();
this.selectedFiles.add(f);
updateShowedList();
}
}
private void removeAllButtonActionPerformed(ActionEvent evt)
{
this.selectedFiles.clear();
updateShowedList();
}
private void runButtonActionPerformed(ActionEvent evt)
{
for (File fs : this.selectedFiles)
{
String executeCom = this.tesseractPath + "\\tesseract.exe " + fs.getAbsolutePath() + " " + this.tesseractPath + "\\" + fs.getName().subSequence(0, fs.getName().length() - 4) + "";
System.out.println(" --- " + executeCom);
try
{
this.logTextArea.append("Starting tesseract for: \n" + fs.getName() + "\n");
Process p = Runtime.getRuntime().exec(executeCom);
p.waitFor();
if (p.exitValue() == 0) {
this.logTextArea.append("Done: \n" + fs.getName().subSequence(0, fs.getName().length() - 4) + ".txt \n");
} else {
this.logTextArea.append("Errors for: \n" + fs.getName().subSequence(0, fs.getName().length() - 4) + ".txt \n");
}
}
catch (InterruptedException ex)
{
Logger.getLogger(TessFrame.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
Logger.getLogger(TessFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void aboutButtonActionPerformed(ActionEvent evt)
{
AboutDlg adlg = new AboutDlg(this, true);
adlg.setVisible(true);
}
private void changePathButtonActionPerformed(ActionEvent evt)
{
JFileChooser chooser = new JFileChooser();
chooser.setDialogTitle("Select Tesseract Path");
chooser.setFileSelectionMode(1);
chooser.setCurrentDirectory(new File(this.tesseractPath));
int returnVal = chooser.showOpenDialog(this);
if (returnVal == 0)
{
this.tesseractPath = chooser.getSelectedFile().getAbsolutePath();
this.tessPathTextField.setText(this.tesseractPath);
}
}
private void updateShowedList()
{
this.fileList.removeAll();
for (File fs : this.selectedFiles) {
this.fileList.add(fs + "");
}
}
private void updateLog()
{
String fileLogName = this.tesseractPath + "\\tesseract.log";
File tessLog = new File(fileLogName);
String s = "";
if (tessLog.canRead()) {
try
{
FileReader fRed = new FileReader(fileLogName);
BufferedReader in = new BufferedReader(fRed);
while ((s = in.readLine()) != null) {
this.logTextArea.append(s + "\n");
}
}
catch (IOException e)
{
System.err.println("Unable to read from file");
System.exit(-1);
}
}
}
}
`

how i can change the end of r.keyPress(KeyEvent.VK_W) the W out of the VK

Alright, So im doing Keypressed and keyreleased, and that works with VK_ stuff.... i have a GUi ready and im able to save and load config files, but i was wondering on how i can change the end of r.keyPress(KeyEvent.VK_W) the W out of the VK with my code....
Here is my main
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class Main {
public static void main(String[] args) throws Exception{
Config bot = new Config();
bot.setVerbose(true);
bot.connect("irc.twitch.tv", 6667, "oauth:6u54pi07uzegv42dwee65gpgzmwwgi");
bot.joinChannel("#mmolegion");
JFrame frame = new JFrame("TwitchBot");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(700, 500));
frame.setLocationRelativeTo(null);
frame.setResizable(true);
KeyGetter.LoadKeys();
try {
Config.loadConfig();
} catch (Exception e) {
e.printStackTrace();
}
JMenuBar mb = new JMenuBar();
JMenu file = new JMenu("File");
mb.add(file);
JMenu edit = new JMenu("Edit");
mb.add(edit);
JMenuItem options = new JMenuItem("Options");
options.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
Config.openConfig(frame);
}
});
frame.setJMenuBar(mb);
edit.add(options);
frame.pack();
frame.setVisible(true);
}
}
and he is my Config
import java.awt.Choice;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import org.jibble.pircbot.PircBot;
public class Config extends PircBot{
public static String left = "up", right = "right", up = "up", down = "down";
private static ArrayList<Choice> choices;
public Config() {
this.setName("Rex__Bot");
}
public void onMessage(String channel, String sender, String login, String hostname, String message) {
if(message.equals("up")) {
try {
Robot r = new Robot();
r.keyPress(KeyEvent.VK_W);
r.delay(300);
r.keyRelease(KeyEvent.VK_W);
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
public static void openConfig(JFrame frame){
choices = new ArrayList<Choice>();
JFrame options = new JFrame("Options");
options.setSize(600, 400);
options.setResizable(false);
options.setLocationRelativeTo(frame);
options.setLayout(null);
Choice left = addChoice("left", options, 30, 30);
left.select(Config.left);
Choice right = addChoice("right", options, 30, 80);
right.select(Config.right);
Choice up = addChoice("up", options, 150, 30);
up.select(Config.up);
Choice down = addChoice("down", options, 150, 80);
down.select(Config.down);
JButton done = new JButton("ok");
done.setBounds(150, 220, 100, 30);
done.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
options.dispose();
saveChanges();
}
});
options.add(done);
options.setVisible(true);
}
public static void saveChanges(){
Choice left = choices.get(0);
Choice right = choices.get(1);
Choice up = choices.get(2);
Choice down = choices.get(3);
Config.left = left.getSelectedItem();
Config.right = right.getSelectedItem();
Config.up = up.getSelectedItem();
Config.down = down.getSelectedItem();
try{
saveConfig();
}
catch(Exception e){
e.printStackTrace();
}
}
public static Choice addChoice(String name, JFrame options, int x, int y){
JLabel label = new JLabel(name);
label.setBounds(x, y - 20, 100, 20);
Choice key = new Choice();
for(String s: getKeyNames()){
key.add(s);
}
key.setBounds(x, y, 100, 20);
options.add(key);
options.add(label);
choices.add(key);
return key;
}
public static ArrayList<String> getKeyNames(){
ArrayList<String> result = new ArrayList<String>();
for(String s: KeyGetter.keyNames){
result.add(s);
if(s.equalsIgnoreCase("F24")){
break;
}
}
return result;
}
public static void loadConfig() throws Exception{
File directory = new File(getDefaultDirectory(), "/Twitchbot");
if(!directory.exists()){
directory.mkdirs();
}
File config = new File(directory,"config.txt");
if(!config.exists()){
config.createNewFile();
System.out.println("File not found, saving default");
saveConfig();
return;
}
#SuppressWarnings("resource")
Scanner s = new Scanner(config);
HashMap<String, String> values = new HashMap<String, String>();
while(s.hasNextLine()){
String[] entry = s.nextLine().split(":");
String key = entry[0];
String value = entry[1];
values.put(key, value);
}
if(!values.containsKey("left") || !values.containsKey("right") || !values.containsKey("up") || !values.containsKey("down")){
System.out.println("Invalid names in config, saving default config");
saveConfig();
return;
}
String left = values.get("left");
String right = values.get("right");
String up = values.get("up");
String down = values.get("down");
if(!(getKeyNames().contains(left) && getKeyNames().contains(right) && getKeyNames().contains(up) && getKeyNames().contains(down))){
System.out.println("Invalid key in config, saving default config");
}
Config.left = left;
Config.right = right;
Config.up = up;
Config.down = down;
}
public static void saveConfig() throws Exception{
File directory = new File(getDefaultDirectory(), "/Twitchbot");
if(!directory.exists()){
directory.mkdirs();
}
File config = new File(directory,"config.txt");
PrintWriter pw = new PrintWriter(config);
pw.println("left:" + left);
pw.println("right:" + right);
pw.println("up:" + up);
pw.println("down:" + down);
pw.close();
}
public static String getDefaultDirectory(){
String OS = System.getProperty("os.name").toUpperCase();
if(OS.contains("WIN")){
return System.getenv("APPDATA");
}
if(OS.contains("MAC")){
return System.getProperty("user.home") + "Library/Application Support";
}
return System.getProperty("user.home");
}
}
and here is my KeyGetter
import java.awt.event.KeyEvent;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
public class KeyGetter {
public static HashMap<String, Integer> keys;
public static ArrayList<String> keyNames;
public static void LoadKeys(){
keys = new HashMap<String, Integer>();
keyNames = new ArrayList<String>();
Field[] fields = KeyEvent.class.getFields();
for(Field f: fields){
if(Modifier.isStatic(f.getModifiers())){
if(f.getName().startsWith("VK")){
try{
int num = f.getInt(null);
String name = KeyEvent.getKeyText(num);
keys.put(name, num);
keyNames.add(name);
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
}
}
So is there anyway of changing the The last letter of VK_W with my config file?
I don't know if you can do this.
Why don't you just save int values. For example KeyEvent.VK_W transforms to:
public static final int VK_W = 87;
So it would be much easier if you would just save int walues to your configuration.
Here can you find the whole list:
KeyEvent.VK_W
So you can just use the following code:
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == 87) {
System.out.println("W pressed");
}
}
Instead of:
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_W) {
System.out.println("W pressed");
}
}

Use wait() in Java

I need to create a new JFrame in a new Thread.. When I close the JFrame I need to return a String.
The problem is that the wait() method "doesn't wait" the "notify()" of new Thread.
Thank's for your answer.
import java.awt.Button;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.LayoutManager;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class FinestraTesto extends Thread {
JLabel jdescr;
JTextArea testo;
JPanel pannelloTasti;
JButton bottoneInvio;
JButton bottoneAnnulla;
JFrame finestraTestuale;
JPanel panAll;
static Boolean pause = true;
String titolo;
String descrizione;
private static String testoScritto = "";
public String mostra() {
// Create a new thread
Thread th = new Thread(new FinestraTesto(titolo, descrizione));
th.start();
synchronized (th) {
try {
// Waiting the end of th.
th.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return testoScritto;
}
public void run() {
synchronized (this) {
System.out.println("Fatto 1 thread");
finestraTestuale = new JFrame(titolo);
finestraTestuale.setPreferredSize(new Dimension(600, 200));
finestraTestuale.setSize(600, 200);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
finestraTestuale.setLocation(
dim.width / 2 - finestraTestuale.getSize().width / 2,
dim.height / 2 - finestraTestuale.getSize().height / 2);
panAll = new JPanel();
panAll.setLayout(new BoxLayout(panAll, BoxLayout.Y_AXIS));
bottoneInvio = new JButton("Conferma");
bottoneAnnulla = new JButton("Annulla");
pannelloTasti = new JPanel();
testo = new JTextArea();
testo.setPreferredSize(new Dimension(550, 100));
testo.setSize(550, 100);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(testo);
jdescr = new JLabel(descrizione);
jdescr.setPreferredSize(new Dimension(550, 50));
jdescr.setSize(550, 50);
pannelloTasti.setLayout(new BoxLayout(pannelloTasti,
BoxLayout.X_AXIS));
pannelloTasti.add(bottoneInvio);
pannelloTasti.add(bottoneAnnulla);
panAll.add(jdescr);
panAll.add(scrollPane);
panAll.add(pannelloTasti);
finestraTestuale.add(panAll);
bottoneInvio.addActionListener(new ActionListener() {
#Override
/**
* metodo attivato quando c'è un'azione sul bottone
*/
public void actionPerformed(ActionEvent arg0) {
testoScritto = testo.getText();
pause = false;
finestraTestuale.show(false);
// send notify
notify();
}
});
bottoneAnnulla.addActionListener(new ActionListener() {
#Override
/**
* metodo attivato quando c'è un'azione sul bottone
*/
public void actionPerformed(ActionEvent arg0) {
pause = false;
testoScritto = "";
finestraTestuale.show(false);
// send notify
notify();
}
});
finestraTestuale.show();
}
}
public FinestraTesto(String titolo, String descrizione) {
this.titolo = titolo;
this.descrizione = descrizione;
}
}
You would better to use Synchronizers instead of wait and notify. They're more preferable because of simplicity and safety.
Given the difficulty of using wait and notify correctly, you should
use the higher-level concurrency utilities instead.
Effective Java (2nd Edition), Item 69
I solved with this class:
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class CustomDialog
{
private List<JComponent> components;
private String title;
private int messageType;
private JRootPane rootPane;
private String[] options;
private int optionIndex;
private JTextArea testo;
public CustomDialog(String title,String descrizione)
{
components = new ArrayList<>();
setTitle(title);
setMessageType(JOptionPane.PLAIN_MESSAGE);
addMessageText(descrizione);
testo = new JTextArea();
testo.setPreferredSize(new Dimension(550, 100));
testo.setSize(550, 100);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(testo);
addComponent(scrollPane);
setRootPane(null);
setOptions(new String[] { "Send", "Cancel" });
setOptionSelection(0);
}
public void setTitle(String title)
{
this.title = title;
}
public void setMessageType(int messageType)
{
this.messageType = messageType;
}
public void addComponent(JComponent component)
{
components.add(component);
}
public void addMessageText(String messageText)
{
components.add(new JLabel(messageText));
}
public void setRootPane(JRootPane rootPane)
{
this.rootPane = rootPane;
}
public void setOptions(String[] options)
{
this.options = options;
}
public void setOptionSelection(int optionIndex)
{
this.optionIndex = optionIndex;
}
public String show()
{
int optionType = JOptionPane.OK_CANCEL_OPTION;
Object optionSelection = null;
if(options.length != 0)
{
optionSelection = options[optionIndex];
}
int selection = JOptionPane.showOptionDialog(rootPane,
components.toArray(), title, optionType, messageType, null,
options, optionSelection);
if(selection == 0)
return testo.getText();
else
return null;
}
}

Populating a JList from a JButton ActionListener

Running into a lot of problems trying to populate a JList after a button press. The code below utilizes a technique that I have employed successfully before, but I have been unable to get this working. The goal is to run a test after pressing a button and display the urls that passed and the urls that failed in separate JLists.
The Action Listener:
//Start button--starts tests when pressed.
JButton start = new JButton("Start");
start.setPreferredSize(new Dimension(400, 40));
start.setAlignmentX(Component.CENTER_ALIGNMENT);
start.addActionListener(new Web(urlA, codeA, cb, passJ, failJ));
panel2.add(start);
The Action Listener Method:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JList;
public class Web implements ActionListener {
private ArrayList<String> urls;
private ArrayList<Integer> statusCodes;
private JComboBox cb;
private JList passJ = new JList();
private JList failJ = new JList();
//constructor--allows other values to be used
public Web(ArrayList<String> urls, ArrayList<Integer> statusCodes, JComboBox cb, JList passList, JList failList ){
this.urls = urls;
this.statusCodes = statusCodes;
this.cb = cb;
this.passJ = passJ;
this.failJ = failJ;
}
#Override
public void actionPerformed(ActionEvent event){
ArrayList<String> resultsP = new ArrayList<String>();
ArrayList<String> resultsF = new ArrayList<String>();
//get source
JButton start = (JButton) event.getSource();
//get value from combobox
String selected = cb.getSelectedItem().toString();
if(selected.equals("ALL")){
}
if(selected.equals("STATUS CODE")){
for(int i = 0; i < urls.size(); i++){
try {
URL u = new URL(urls.get(i));
HttpURLConnection connection = (HttpURLConnection)u.openConnection(); //open connection and cast to HttpURLConnection
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
if (code == statusCodes.get(i)){
System.out.println(i + "."+ urls.get(i)+" \t\t\t PASS");
resultsP.add(urls.get(i));
}
else{
System.out.println(i + "." +urls.get(i)+ "\t\t\t FAIL");
resultsF.add(urls.get(i));
}
} catch (MalformedURLException | ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (String str: resultsP){
System.out.println(str);
}
System.out.println("/////////////////////////////////////////////////////////////////////////////////");
for (String str: resultsF){
System.out.println(str);
}
passJ.removeAll();
failJ.removeAll();
passJ.setListData(resultsP.toArray());
failJ.setListData(resultsF.toArray()) ;
passJ.repaint();
failJ.repaint();
}//StatusCodeTest
}
}
How the lists are added to the GUI:
JList passJ = new JList(urlA.toArray());
JScrollPane scroll1 = new JScrollPane(passJ);
scroll1.setPreferredSize(new Dimension (700, 150));
scroll1.setMaximumSize( scroll1.getPreferredSize() );
scroll1.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
panel2.add(scroll1);
panel2.add(Box.createRigidArea(new Dimension(0,50)));
JList failJ = new JList(urlA.toArray());
JScrollPane scroll2 = new JScrollPane(failJ);
scroll2.setPreferredSize(new Dimension(700, 150));
scroll2.setMaximumSize(scroll1.getPreferredSize());
scroll2.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
panel2.add(scroll2);
//spacer
panel2.add(Box.createRigidArea(new Dimension(0,25)));
Any GUIdance would be greatly appreciated.
Seems you have different instances of passJ/failJ in your Web class and GUI class.
passJ.removeAll(); failJ.removeAll(); doesn't clear items of JList, that method from Container.
Here is simple example of adding/clearing items to JList:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class TestFrame extends JFrame {
private JList<Integer> normal;
private JList<Integer> fail;
private Integer[] vals;
public TestFrame() {
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
private void init() {
normal = new JList<Integer>(new DefaultListModel<Integer>());
fail = new JList<Integer>(new DefaultListModel<Integer>());
vals = new Integer[]{1,2,3,4,5,6,7,8,9,33};
JButton add = new JButton("collect data");
add.addActionListener(getCollectListener());
JButton clear = new JButton("clear data");
clear.addActionListener(getClearListener());
JPanel p = new JPanel();
p.add(new JScrollPane(normal));
p.add(new JScrollPane(fail));
JPanel btnPanel = new JPanel();
btnPanel.add(add);
btnPanel.add(clear);
add(p);
add(btnPanel,BorderLayout.SOUTH);
}
private ActionListener getClearListener() {
return new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
((DefaultListModel<Integer>)normal.getModel()).removeAllElements();
((DefaultListModel<Integer>)fail.getModel()).removeAllElements();
}
};
}
private ActionListener getCollectListener() {
return new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for(Integer i : vals){
if(i%3==0){
((DefaultListModel<Integer>)normal.getModel()).addElement(i);
} else {
((DefaultListModel<Integer>)fail.getModel()).addElement(i);
}
}
}
};
}
public static void main(String args[]) {
new TestFrame();
}
}

Categories