Saving/Loading Config Not Working - java

First time posting here. Heres my problem: I can't get the saving or loading of my configuration file to work. I am trying to save player names based off how many players specified in my code. Anyone know what is wrong and how to fix?
Config file:
public void savePlayerConfiguration(String key, int value) {
String path = "config.xml";
try {
File file = new File(path);
boolean exists = file.exists();
if (!exists) {
file.createNewFile();
}
OutputStream write = new FileOutputStream(path);
properties.setProperty(key, Integer.toString(value));
properties.storeToXML(write, key);
} catch (Exception e) {
}
}
public void loadPlayerConfiguration(String path) {
try {
InputStream read = new FileInputStream(path);
properties.loadFromXML(read);
String player1 = properties.getProperty("1");
String player2 = properties.getProperty("2");
String player3 = properties.getProperty("3");
String player4 = properties.getProperty("4");
String player5 = properties.getProperty("5");
String player6 = properties.getProperty("6");
read.close();
} catch (FileNotFoundException e) {
savePlayerConfiguration("1", 1);
savePlayerConfiguration("2", 2);
savePlayerConfiguration("3", 3);
savePlayerConfiguration("4", 4);
savePlayerConfiguration("5", 5);
savePlayerConfiguration("6", 6);
loadConfiguration(path);
} catch (IOException e) {
}
}
Options file:
private int width = Main.width;
private int height = Main.height;
private String player1 = "Player1", player2 = "Player2",
player3 = "Player3", player4 = "Player4", player5 = "Player5",
player6 = "Player6";
private String[] playerNames = { player1, player2, player3, player4,
player5, player6 };
private int[] player = { 1, 2, 3, 4, 5, 6 };
private int playerTotal;
private JButton OK;
private JTextField input1, input2, input3, input4, input5, input6;
private JTextField[] playerNameInput = { input1, input2, input3, input4,
input5, input6 };
private JLabel playerName;
private Rectangle rOK, rPlayerAmount;
private Choice playerAmount = new Choice();
Configuration config = new Configuration();
private int button_width = 80;
private int button_height = 40;
JPanel window = new JPanel();
public Database() {
setTitle("Database - Excelteor Launcher");
setSize(new Dimension(width, height));
add(window);
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
window.setLayout(null);
drop();
drawButtons();
window.repaint();
}
private void drawButtons() {
OK = new JButton("OK");
rOK = new Rectangle((width - 100), (height - 70), button_width,
button_height);
OK.setBounds(rOK);
window.add(OK);
rPlayerAmount = new Rectangle(30, 130, 80, 25);
playerAmount.setBounds(rPlayerAmount);
playerAmount.add("1");
playerAmount.add("2");
playerAmount.add("3");
playerAmount.add("4");
playerAmount.add("5");
playerAmount.add("6");
playerAmount.select(1);
window.add(playerAmount);
playerName = new JLabel("Player Names:");
playerName.setBounds(30, 110, 120, 20);
window.add(playerName);
for (int i = 0; i < playerTotal; i++) {
playerNameInput[i] = new JTextField();
playerNameInput[i].setBounds(80, 150 + i * 20, 60, 20);
window.add(playerNameInput[i]);
}
OK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
System.out.println("test");
for (int i = 0; i < playerTotal; i++) {
config.savePlayerConfiguration(parsePlayers(), player[i]);
System.out.println(player[i]);
}
}
});
}
private void drop() {
int selection = playerAmount.getSelectedIndex();
if (selection == 0) {
playerTotal = 1;
}
if (selection == 1 || selection == -1) {
playerTotal = 2;
}
if (selection == 2) {
playerTotal = 3;
}
if (selection == 3) {
playerTotal = 4;
}
if (selection == 4) {
playerTotal = 5;
}
if (selection == 5) {
playerTotal = 6;
}
}
private String parsePlayers() {
try {
for (int i = 0; i < playerTotal; i++) {
playerNames[i] = playerNameInput[i].toString();
return playerNames[i];
}
} catch (NumberFormatException e) {
drop();
return player1;
}
return player1;
}

My guess would be that the path of your config.xml, the one being passed into loadPlayerConfiguration(String path), is wrong. Try out the below options for resolving your problem.
Make sure that the 'path' is correct.
Make sure that the 'path' exists using exists() method of File API.
If the path is relative, then confirm whether the path structure has been added onto the
class path. Else, try placing it in the root of your project.
If you still face issues after trying out these steps, then kindly share your project structure.
Cheers,
Madhu.
** EDIT **
#user2399785 : got a clear idea on your problem after going through your config.xml.
<properties>
<comment>javax.swing.JTextField[,80,150,60x20,invalid,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource#69ecade2,flags=296,maximumSize=,minimumSize=,preferredSize=,caretColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],disabledTextColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],editable=true,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],selectionColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],columns=0,columnWidth=0,command=,horizontalAlignment=LEADING]</comment>
<entry key="javax.swing.JTextField[,80,150,60x20,invalid,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource#69ecade2,flags=296,maximumSize=,minimumSize=,preferredSize=,caretColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],disabledTextColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],editable=true,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],selectionColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],columns=0,columnWidth=0,command=,horizontalAlignment=LEADING]">2</entry>
<entry key="javax.swing.JTextField[,80,150,60x20,invalid,layout=javax.swing.plaf.basic.BasicTextUI$UpdateHandler,alignmentX=0.0,alignmentY=0.0,border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource#2904a7cf,flags=296,maximumSize=,minimumSize=,preferredSize=,caretColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],disabledTextColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],editable=true,margin=javax.swing.plaf.InsetsUIResource[top=0,left=0,bottom=0,right=0],selectedTextColor=sun.swing.PrintColorUIResource[r=51,g=51,b=51],selectionColor=javax.swing.plaf.ColorUIResource[r=184,g=207,b=229],columns=0,columnWidth=0,command=,horizontalAlignment=LEADING]">2</entry>
</properties>
If you notice your .xml, the KEY contains some kind of a long javax swing detail. But loadPlayerConfiguration(String path) uses properties.getProperty("2") which will return you a VALUE whose KEY is "2" and not vice versa. Since there is no KEY with "2", you are getting the return value as NULL. Try the same code with the KEY as in the .xml and you should be fine.
Cheers,
Madhu.

Related

How to create an Excel-like sum function in Java, example =SUM(A1:A2)

Blessings to everyone I'm work in university project that consist to create a simulation of spreadsheet like excel, it return the name of the text field(simulation of the cells)
when I press enter
This how the spreadsheet look like
Here is all the code
public class SpreadSheet extends JFrame{
public SpreadSheet(){
Toolkit screen = Toolkit.getDefaultToolkit();
Dimension sizeScreen = screen.getScreenSize();
int heightScreen = sizeScreen.height;
int widhtScreen = sizeScreen.width;
this.setSize(widhtScreen, heightScreen);
this.setTitle("Excel Proyect");
initcomponents(heightScreen, widhtScreen);
}
private void initcomponents(int heightScreen, int widhtScreen) {
labelformulaBar = new JLabel();
txtformulaBar = new JTextField();
TableGrid = new JPanel();
scroll = new JScrollPane();
getContentPane().setLayout(null);
//labelformulaBar
labelformulaBar.setText("Formula Bar");
labelformulaBar.setName("labelFormulaBar");
getContentPane().add(labelformulaBar);
labelformulaBar.setBounds(5, 5, 100, 20);
//txtformulaBar
txtformulaBar.setName("txtformulaBar");
getContentPane().add(txtformulaBar);
txtformulaBar.setBounds(110, 5, widhtScreen-160, 23);
//scroll
scroll.setBounds(5, 30, widhtScreen-56, heightScreen-100);
scroll.setViewportView(TableGrid);
getContentPane().add(scroll);
//TableGrid
TableGrid.setLayout(null);
TableGrid.setPreferredSize(new Dimension(2650,1175));
createColumnsHeaders();
createNumberRows();
createCells();
actionFormulaBar();
}
private void actionFormulaBar(){
this.txtformulaBar.addKeyListener(new java.awt.event.KeyAdapter() {
#Override
public void keyPressed(java.awt.event.KeyEvent keycap) {
cellTableGridActionPerfomed(keycap,txtformulaBar);
}
});
}
private void createColumnsHeaders(){
char columnName = 'A';
for(int index = 0; index < columnHeaders.length; index++) {
this.columnHeaders[index] = new javax.swing.JButton();
this.columnHeaders[index].setText(""+columnName);
columnName++;
this.columnHeaders[index].setBounds((100*index)+5, 0, 100, 23);
TableGrid.add(this.columnHeaders[index]);
}
}
private void createNumberRows() {
int ContRows = 1;
for(int index = 0; index < numberRows.length; index++) {
this.numberRows[index] = new javax.swing.JButton();
this.numberRows[index].setText(""+ContRows);
ContRows++;
this.numberRows[index].setBounds(0,(23*index)+23, 50,23);
TableGrid.add(this.numberRows[index]);
}
}
In This method I create a two dimensional array with JTextFields and JButtons to simulate the spreadsheet
private void createCells(){
for(int row = 0; row < numberRows.length; row++ ) {
for(int column = 0; column < columnHeaders.length; column++) {
String names = columnHeaders[column].getText()+numberRows[row].getText();
this.cells[row][column] = new JTextField();
this.cells[row][column].setName(names);
this.cells[row][column].setBounds((100*column)+50, (23*row)+23, 100, 23);
TableGrid.add(this.cells[row][column]);
JTextField temporal = this.cells[row][column];
this.cells[row][column].addKeyListener(new java.awt.event.KeyAdapter() {
#Override
public void keyPressed(java.awt.event.KeyEvent keycap) {
cellTableGridActionPerfomed(keycap,temporal);
}
});
}
}
}
In this method I create a function to trying found name of the cells(textfield) and extract the name of the cells, my intention is trying to extract the number that found in the textfield and do a sum, example =SUM(A1:A2)
public String lookingCells(String name){
for(int rows = 0; rows<numberRows.length; rows++)
{
for(int column = 0; column<columnHeaders.length; column++)
{
if(this.cells[rows][column].getName().equals(name))
{
return name;
}
}
}
return null;
}
In this method it works when I press enter, to do the sum
private void cellTableGridActionPerfomed(java.awt.event.KeyEvent keycap, javax.swing.JTextField textFieldSelected) {
if(keycap.getKeyCode() == KeyEvent.VK_ENTER) {
//int number1 = Integer.parseInt(textFieldSelected.getText());
//int total = number1 + number1;
//JOptionPane.showMessageDialog(null, "La suma es de "+ total);
Sum obj = new Sum();
String texto = textFieldSelected.getText();
/*if(texto.contains("="))
{
String result = obj.sum(texto);
JOptionPane.showMessageDialog(null, result);
this.txtformulaBar.setText(texto);
}*/
JOptionPane.showMessageDialog(null, "Hello you are here ->" +textFieldSelected.getName());
}
}
private javax.swing.JLabel labelformulaBar;
private javax.swing.JTextField txtformulaBar;
private javax.swing.JScrollPane scroll;
private javax.swing.JPanel TableGrid;
private javax.swing.JButton[] columnHeaders = new javax.swing.JButton[26];
private javax.swing.JButton[] numberRows = new javax.swing.JButton[50];
private javax.swing.JTextField[][] cells = new javax.swing.JTextField[50][26];
}

Multiple Windows(AWT) by Using Thread, But Only the Last Window Works

I want to make an imitative hack System. There will be 3 windows displayed on screen. Each window will show some string Constantly (like some movie scene) . However only the third (the last) window works. So how to make every window show string at the same time?
the frame class as follow:
import java.awt.*;
import java.awt.event.*;
class sys extends Thread {
private static Frame frm;
private static TextArea txa;
private int fsx, fsy, flx, fly, tsx, tsy, tlx, tly;
private String strarr[] = new String[7];
private String frmName;
public sys(String str, String SAEC[]) {
frmName = str;
strarr = SAEC;
}
public void SettingFRM(int sx, int sy, int lx, int ly) {
//frame's location and size
fsx = sx;
fsy = sy;
flx = lx;
fly = ly;
}
public void SettingTXA(int sx, int sy, int lx, int ly) {
//textArea's location and size
tsx = sx;
tsy = sy;
tlx = lx;
tly = ly;
}
public void run() {
frm = new Frame(frmName);
//the exterior design
txa = new TextArea("", 100, 100, TextArea.SCROLLBARS_BOTH);
txa.setBounds(tlx, tly, tsx, tsy);
txa.setBackground(Color.darkGray);
txa.setFont(new Font("Arial", Font.PLAIN, 16));
txa.setForeground(Color.green);
frm.setLayout(null);
frm.setSize(fsx, fsy);
frm.setLocation(flx, fly);
frm.setVisible(true);
frm.setBackground(Color.darkGray);
frm.add(txa);
while (1 != 0) {
txa.append(strarr[(int) (Math.random() * 7)]);// to obtain new string
frm.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
try {
sleep(200);
} catch (InterruptedException e) {
}
}
}
}
main program as follow:
public class ImitativeHackSystem {
public static void main(String[] args) throws InterruptedException {
//specific string
String strarr[] = new String[9];
strarr[0] = new String("Hacking... Time estimate 25 seconds...\n");
strarr[1] = new String("Retrying...\n");
strarr[2] = new String("Error! Code:e2130443523\n");
strarr[3] = new String("Success! IP:192.168.0.1\n");
strarr[4] = new String("picking datas...\n");
strarr[5] = new String("Anti-system started\n");
strarr[6] = new String("Has been discovering... fake random IP address\n");
strarr[7] = new String("01011010000011001000000011111101010");
strarr[8] = new String("111101010101001101101101010011010");
//object array
sys fhs[] = new sys[3];
for (int i = 0; i < 3; i++)
fhs[i] = new sys("Fake Hacking System", strarr);
fhs[0].SettingTXA(635, 690, 5, 30);
fhs[0].SettingFRM(640, 720, 0, 0);
fhs[1].SettingTXA(635, 330, 5, 30);
fhs[1].SettingFRM(640, 360, 645, 0);
fhs[2].SettingTXA(635, 330, 5, 30);
fhs[2].SettingFRM(640, 360, 645, 365);
//to execute
for (int i = 0; i < 3; i++) {
fhs[i].start();
Thread.sleep(500);
}
}
}

Unable to Load Panel Images, Text, etc when switching from one panel to another

I am a high school student who is need of finishing a game for my Java class. My game revolves around using levels. The main problem I have in my game is when I was loading one of my panels. What happened was that the screen froze. I was unable to press buttons or even close the panel. No errors appeared on the terminal and this was after compiling successfully.
Some information:
Using CardLayout
The first panel that showed up and other panels after it worked perfectly. Just not this panel.
When I attempted to make this panel appear initially when running, the panel was white.
Used eclipse and added SerialVersionUID to all my classes. Still didn't work.
Please excuse any code that is or looks unappealing to you. Thanks.
class Level1 extends JPanel implements ActionListener
{
private String [] questions;
private String question;
private String [] answers;
private String answer;
private String [] images;
private String image;
private String [] wrongAnswers1;
private String wrongAnswer1;
private String [] wrongAnswers2;
private String wrongAnswer2;
private String [] wrongAnswers3;
private String wrongAnswer3;
private int time;
private int integer;
private int problemNumber;
private int lives;
private int answerLocation;
private int wrongOrNot;
private int num;
private boolean finished;
private boolean newProblem;
private boolean getOut;
private boolean makeOrder;
private JButton restartButton;
private JButton getOutButton;
private ButtonGroup colorgroup;
private JRadioButton answer1;
private JRadioButton answer2;
private JRadioButton answer3;
private JRadioButton answer4;
private File file;
private PrintWriter makesOutput;
private Scanner lookForTwo;
private String number;
private boolean thereIsTwo;
private Timer timer;
private ArrayList<Integer> list1;
private int i;
private int y;
public Level1()
{
questions = new String[15];
//filled in each part of the array;
question = "";
answers = new String[15];
//filled in each part of the array
answer = "";
images = new String[15];
//filled in each part of the array
image = "";
wrongAnswers1 = new String[15];
//filled in each part of the array
wrongAnswer1 = "";
wrongAnswers2 = new String[15];
//filled in each part of the array
wrongAnswer2 = "";
wrongAnswers3 = new String[15];
//filled in each part of the array
wrongAnswer3 = "";
time = 60;
integer = -1;
problemNumber = 1;
lives = 3;
answerLocation = -1;
wrongOrNot = 1;
num = 0;
finished = false;
newProblem = true;
getOut = false;
makeOrder = true;
restartButton = new JButton("Restart"); //create buttons: Restart, Exit
add(restartButton);
restartButton.addActionListener(this);
getOutButton = new JButton("Exit");
add(getOutButton);
getOutButton.addActionListener(this);
colorgroup = new ButtonGroup();
answer1 = new JRadioButton("");//create radiobuttons to hold answer
colorgroup.add(answer1);
answer2 = new JRadioButton("");
colorgroup.add(answer2);
answer3 = new JRadioButton("");
colorgroup.add(answer3);
answer4 = new JRadioButton("");
colorgroup.add(answer4);
//radiobuttons on south side
file = new File("SaveFiles.txt");
makesOutput = null; //variables for try-catch block
lookForTwo = null;
number = "";
thereIsTwo = false;
timer = new Timer(0,this);
timer.setDelay(1000);
timer.start();
list1 = new ArrayList<Integer>();
i = 0;
y = 0;
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
if(newProblem) //when a new problem needs to be made, the variable needs to be true
{
if(makeOrder) //create random order of problems
{
while(i<15)
{
list1.add(new Integer(i));
i++;
}
Collections.shuffle(list1);
makeOrder = false;
}
integer++;
/*create problems randomly along with answer based on Math.Random
and if-else along with level #s*/
Image img1 = Toolkit.getDefaultToolkit().getImage(images[integer]);
g.drawImage(img1, 500, 500, this); //make sure to have an image if needed for the problem
question = questions[integer];
g.drawString(question, 500, 400);
answer = answers[integer];
wrongAnswer1 = wrongAnswers1[integer];
wrongAnswer2 = wrongAnswers2[integer];
wrongAnswer3 = wrongAnswers3[integer];
answerLocation = (int)(Math.random()*4); //set Location of answers on radiobuttons
if(answerLocation == 1)
{
answer1.setText(answer);
answer2.setText(wrongAnswer1);
answer3.setText(wrongAnswer3);
answer4.setText(wrongAnswer2);
}
else if(answerLocation == 2)
{
//different locations
}
else if(answerLocation == 3)
{
//different locations
}
else if(answerLocation == 4)
{
//different locations
}
}
g.drawString("Time: " + time, 900, 100);
//time is on upperleft; use drawString and time variable
g.drawString(problemNumber + " out of 10", 50, 50);
if(time == 0 || lives == 0) //if time or lives goes to zero, open GameOverScreen
panels.show(c, "Game Over Screen1");
if(wrongOrNot == 2)
{
g.setColor(Color.RED);
g.drawString("Incorrect",600,600);
}
else if(wrongOrNot == 3)
{
g.setColor(Color.GREEN);
g.drawString("Correct",600,600);
}
g.setColor(Color.BLACK);
if(problemNumber == 6) //try-catch block for when user completes levels
finished = true;
try //PrintWriter is used when 5 problems are finished
{
makesOutput = new PrintWriter("SaveFiles.txt");
lookForTwo = new Scanner("SaveFiles.txt");
}
catch(FileNotFoundException e)
{
System.out.println("Can't find file.");
System.exit(1);
}
while(lookForTwo.hasNext())
{
if(number.equals("2"))
thereIsTwo = true;
}
if(getOut)
{
panels.show(c, "Title Screen");
getOut = false;
}
if(finished && thereIsTwo == false)
makesOutput.println("2");
if(finished)
{
panels.show(c, "Level Complete");
finished = false;
}
makesOutput.close();
time--;
}
public void actionPerformed(ActionEvent e)
{
newProblem = false;
if(answer1.isSelected() && answer1.getText() == answer)
{
problemNumber++;
newProblem = true;
wrongOrNot = 3;
questions[integer] = "";
}
else if(answer2.isSelected() && answer2.getText() == answer)
{
//same as above
}
else if(answer3.isSelected() && answer3.getText() == answer)
{
//same as above
}
else if(answer4.isSelected() && answer4.getText() == answer)
{
//same as above
}
else
{
lives-=1;
wrongOrNot = 2;
}
if(restartButton.getModel().isPressed())
{
problemNumber = 1;
time = 60;
lives = 3;
newProblem = true;
}
else if(getOutButton.getModel().isPressed())
{
getOut = true;
}
repaint();
}
}
try //code is now from another panel that loads Level1
{
scanner = new Scanner(file);
}
catch(FileNotFoundException e)
{
System.out.println("Can't find file.");
System.exit(1);
}
while(scanner.hasNext())
{
if(word.equals("2"))
toLevel2 = true;
if(word.equals("3"))
toLevel3 = true;
}
scanner.close();
if(backToTitle)
{
panels.show(c, "Title Screen");
backToTitle = false;
}
if(lvl1ButtonPressed)
panels.show(c, "Level 1");

JAR file will create txt. file but won't write to it

I've made UEFA team generator with Jsoup Html parser. Everything works perfectly when running it as a project but when I build jar, it will create file but won't write to it. I heard it's some kind of securing but I'd like to avoid it. Any ideas?
Code :
public final class Generator extends JPanel {
JLabel label;
File file;
Font font;
ArrayList<String> urllist;
PrintWriter writer;
Document doc;
URL url;
JComboBox<String> seasons; // edited
String[] seas = {"1999-2000", "2000-2001", "2001-2002", "2002-2003", "2003-2004", "2004-2005", "2005-2006", "2006-2007", "2007-2008", "2008-2009", "2009-2010", "2014-2015", "2015-2016"};
public Generator(int width, int height) {
setLayout(null);
setPreferredSize(new Dimension(width, height));
seasons = new JComboBox<>(seas);
font = new Font("Verdana", Font.BOLD, 12);
label = new JLabel("Choose a season :");
label.setFont(font);
label.setBounds(20, 10, 120, 30);
seasons.setBounds(150, 10, 100, 30);
add(seasons);
add(label);
urllist = new ArrayList<>();
urllist.add("https://en.wikipedia.org/wiki/1999%E2%80%932000_UEFA_Champions_League_group_stage");
urllist.add("https://en.wikipedia.org/wiki/2000%E2%80%9301_UEFA_Champions_League_group_stage");
urllist.add("https://en.wikipedia.org/wiki/2001%E2%80%9302_UEFA_Champions_League_group_stage");
urllist.add("https://en.wikipedia.org/wiki/2002%E2%80%9303_UEFA_Champions_League_group_stage");
urllist.add("https://en.wikipedia.org/wiki/2003%E2%80%9304_UEFA_Champions_League_group_stage");
urllist.add("https://en.wikipedia.org/wiki/2004%E2%80%9305_UEFA_Champions_League_group_stage");
urllist.add("https://en.wikipedia.org/wiki/2005%E2%80%9306_UEFA_Champions_League_group_stage");
urllist.add("https://en.wikipedia.org/wiki/2006%E2%80%9307_UEFA_Champions_League_group_stage");
urllist.add("https://en.wikipedia.org/wiki/2007%E2%80%9308_UEFA_Champions_League_group_stage");
urllist.add("https://en.wikipedia.org/wiki/2008%E2%80%9309_UEFA_Champions_League_group_stage");
urllist.add("https://en.wikipedia.org/wiki/2009%E2%80%9310_UEFA_Champions_League_group_stage");
urllist.add("https://en.wikipedia.org/wiki/2014%E2%80%9315_UEFA_Champions_League_group_stage");
urllist.add("https://en.wikipedia.org/wiki/2015%E2%80%9316_UEFA_Champions_League_group_stage");
seasons.addActionListener(new GenerateHandler());
}
public void cycle(int start, int end) {
for (int j = start; j < end; j++) {
Element table = doc.select("table.wikitable").get(j);
Elements rows = table.select("tr");
for (int i = 1; i < 3; i++) {
writer.println(rows.get(i).select("td").select("a").get(1).attr("Title").replace(" (football)", "") + "," + rows.get(i).select("td").select("a").attr("Title"));
}
}
writer.close();
}
public class GenerateHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
int i = seasons.getSelectedIndex();
String foldername = "C:/Users/neutron/Desktop/data/";
file = new File(foldername, seas[i] + ".txt");
file.canWrite();
try {
url = new URL(urllist.get(i));
} catch (MalformedURLException ex) {
Logger.getLogger(Generator.class.getName()).log(Level.SEVERE, null, ex);
}
try {
doc = Jsoup.parse(url, 3000);
} catch (IOException ex) {
Logger.getLogger(Generator.class.getName()).log(Level.SEVERE, null, ex);
}
try {
writer = new PrintWriter(file, "UTF-8");
} catch (FileNotFoundException | UnsupportedEncodingException ex) {
Logger.getLogger(Generator.class.getName()).log(Level.SEVERE, null, ex);
}
if (i >= 0 && i < 3) {
cycle(1, 9);
} else if ((i > 2 && i < 4)|| (i > 10 && i < 13)) {
cycle(5, 13);
} else if (i == 8) {
cycle(2, 10);
}
else {
cycle(6, 14);
}
}
}
}
.. when building a jar it doesn't print any warnings or errors
OK I solved it by making generic JComboBox
instead of JComboBox seasons;
I put in there JComboBox<String> seasons;

How to Save/Open an ArrayList of objects using JFileChooser?

Okay so I'm kind of new to Java programming, and I don't quite understand the concepts of file reading/writing. I've tried looking at the docs.oracle webpages about Files, but I found they aren't really helpful considering what I'm trying to do is kind of different.
I have these 3 files: CVolunteer, CDialog, and TestDialog. CVolunteer creates and object of a person who can volunteer to tutor students. CDialog manages the adding/editing of the volunteer. TestDialog displays a JList of volunteers and allows the user to edit, add, remove, or clear the list. I have those 3 classes working perfectly and will display them below (sorry they're long!).
Here's what I need help with... I added two buttons to the main window, "Save" and "Open". At any time, the user should be able to save the current JList of volunteers. When "Save" is clicked, a JFileChooser window should pop up and ask the user for a filename where all the volunteer objects will be saved. When the user clicks "Open", another JFileChooser window should pop up and ask the user what file they want to open. The volunteers currently in the main window will be erased and the volunteers from the selected file will take their place. I'm not sure if I need to use Serialization or not....
If anyone could help explain how to accomplish this or help me write the code to handle the "Save"/"Open" events, I would really appreciate it! Thanks in advance:)
I believe the only file that needs changing is TestDialog, I included the others in case someone wants to try to run it
***Sorry if there are any indentation errors, I had to do it all by hand in this dialog box
CVolunteer.java
public class CVolunteer {
int volNum;
String name;
int sub, volDays, trans;
public CVolunteer(int vNum, String vName, int subj, int days, int needTrans){
volNum = vNum;
name = vName;
sub = subj;
volDays = days;
trans = needTrans;
}
private String subjectToString()
{
switch (sub){
case 0:
return "Math";
case 1:
return "Science";
case 2:
return "English";
case 3:
return "History";
}
return " ";
}
private String volDaysToString()
{
String str = "";
str +=((volDays&1)!=0)?"M":"-";
str +=((volDays&2)!=0)?"T":"-";
str +=((volDays&4)!=0)?"W":"-";
str +=((volDays&8)!=0)?"R":"-";
return str;
}
private String transToString()
{
switch(trans)
{
case 0:
return "Yes";
case 1:
return "No";
}
return " ";
}
public String getVolunteerLine()
{
return String.format("%05d %-30s%-30s%-30s%s",
volNum, name, subjectToString(), volDaysToString(), transToString());
}
}
CDialog.java
import java.awt.Container;
import java.awt.event.*;
import javax.swing.*;
public class CDialog extends JDialog implements ActionListener
{
private JLabel label1;
private JLabel lNum;
private JLabel label2;
private JTextField tfName;
private JLabel label3;
private ButtonGroup subGroup;
private JRadioButton rbMath;
private JRadioButton rbScience;
private JRadioButton rbEnglish;
private JRadioButton rbHistory;
private JLabel label4;
private JCheckBox cbMonday;
private JCheckBox cbTuesday;
private JCheckBox cbWednesday;
private JCheckBox cbThursday;
private JLabel label5;
private ButtonGroup transGroup;
private JRadioButton rbYes;
private JRadioButton rbNo;
private JButton okButton = null;
private JButton cancelButton = null;
private boolean cancelled = true;
public boolean isCancelled() {return cancelled;}
private CVolunteer answer;
public CVolunteer getAnswer() {return answer;}
public CDialog(JFrame owner, String title, CVolunteer vol)
{
super(owner, title, true);
Container c = getContentPane();
c.setLayout(null);
label1 = new JLabel ("Volunteer Number:");
label1.setSize(140,20);
label1.setLocation(40,40);
c.add(label1);
lNum = new JLabel(String.format("%05d", vol.volNum));
lNum.setSize(40,20);
lNum.setLocation(150,40);
c.add(lNum);
label2 = new JLabel ("Volunteer Name: ");
label2.setSize(100,20);
label2.setLocation(40,90);
c.add(label2);
tfName = new JTextField(vol.name);
tfName.setSize(120,20);
tfName.setLocation(140,90);
c.add(tfName);
int x,y;
int w,h;
x=4;
y=150;
w=180;
h=20;
label3 = new JLabel("Subject: ");
label3.setSize(85,13);
label3.setLocation(x,y);
c.add(label3);
rbMath = new JRadioButton("Math", vol.sub==0);
rbMath.setSize(w,h);
rbMath.setLocation(x+16,y+30);
c.add(rbMath);
rbScience = new JRadioButton("Science", vol.sub==1);
rbScience.setSize(w,h);
rbScience.setLocation(x+16,y+66);
c.add(rbScience);
rbEnglish = new JRadioButton("English", vol.sub==2);
rbEnglish.setSize(w,h);
rbEnglish.setLocation(x+16,y+102);
c.add(rbEnglish);
rbHistory = new JRadioButton("History", vol.sub==3);
rbHistory.setSize(w,h);
rbHistory.setLocation(x+16,y+138);
c.add(rbHistory);
subGroup = new ButtonGroup();
subGroup.add(rbMath);
subGroup.add(rbScience);
subGroup.add(rbEnglish);
subGroup.add(rbHistory);
x=220;
y=150;
w=120;
h=20;
label4 = new JLabel("Days Available: ");
label4.setSize(w,h);
label4.setLocation(x,y);
c.add(label4);
cbMonday = new JCheckBox("Monday (M)", (vol.volDays&1)!=0);
cbMonday.setSize(w,h);
cbMonday.setLocation(x+6,y+30);
c.add(cbMonday);
cbTuesday = new JCheckBox("Tuesday (T)", (vol.volDays&2)!=0);
cbTuesday.setSize(w,h);
cbTuesday.setLocation(x+6,y+66);
c.add(cbTuesday);
cbWednesday = new JCheckBox("Wednesday (W)", (vol.volDays&4)!=0);
cbWednesday.setSize(w,h);
cbWednesday.setLocation(x+6,y+102);
c.add(cbWednesday);
cbThursday = new JCheckBox("Thursday (R)", (vol.volDays&8)!=0);
cbThursday.setSize(w,h);
cbThursday.setLocation(x+6,y+138);
c.add(cbThursday);
x=480;
y=150;
w=180;
h=20;
label5 = new JLabel("Need Transport? :");
label5.setSize(150,13);
label5.setLocation(x,y);
c.add(label5);
rbYes = new JRadioButton("Yes", vol.trans==0);
rbYes.setSize(w,h);
rbYes.setLocation(x+12,y+30);
c.add(rbYes);
rbNo = new JRadioButton("No", vol.trans==1);
rbNo.setSize(w,h);
rbNo.setLocation(x+12,y+66);
c.add(rbNo);
transGroup = new ButtonGroup();
transGroup.add(rbYes);
transGroup.add(rbNo);
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(this);
cancelButton.setSize(100,50);
cancelButton.setLocation(116,380);
c.add(cancelButton);
okButton = new JButton("OK");
okButton.addActionListener(this);
okButton.setSize(100,50);
okButton.setLocation(400,380);
c.add(okButton);
setSize(700,480);
setLocationRelativeTo(owner);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource()==okButton) {
int num=Integer.parseInt(lNum.getText());
String name=tfName.getText();
int subj=-1;
if (rbMath.isSelected()) subj = 0;
if (rbScience.isSelected()) subj = 1;
if (rbEnglish.isSelected()) subj = 2;
if (rbHistory.isSelected()) subj = 3;
int days=0;
if (cbMonday.isSelected()) days |= 1;
if (cbTuesday.isSelected()) days |= 2;
if (cbWednesday.isSelected()) days |= 4;
if (cbThursday.isSelected()) days |= 8;
int tran=0;
if (rbYes.isSelected()) tran = 0;
if (rbNo.isSelected()) tran = 1;
answer=new CVolunteer(num, name, subj, days, tran);
cancelled = false;
setVisible(false);
}
else if(e.getSource()==cancelButton) {
cancelled = true;
setVisible(false);
}
}
}
TestDialog.java
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.ArrayList;
public class TestDialog extends JFrame implements ActionListener
{
JLabel myLabel1 = null;
JLabel myLabel2 = null;
JLabel myLabel3 = null;
JLabel myLabel4 = null;
JLabel myLabel5 = null;
JLabel myLabel6 = null;
File fileName = new File("Volunteers.txt");
ArrayList<CVolunteer> volArray;
private DefaultListModel volunteers;
JList volList;
JScrollPane scrollPane = null;
JButton bAdd = null;
JButton bEdit = null;
JButton bRemove = null;
JButton bClear = null;
JButton bSave = null;
JButton bOpen = null;
int volNumb;
public TestDialog()
{
super("Volunteer Info");
Container c = getContentPane();
c.setLayout(null);
myLabel1 = new JLabel("Vol Number");
myLabel1.setSize(200,50);
myLabel1.setLocation(100,10);
c.add(myLabel1);
myLabel2 = new JLabel("Vol Name");
myLabel2.setSize( 200, 50 );
myLabel2.setLocation( 200, 10 );
c.add(myLabel2);
myLabel3 = new JLabel("Subject");
myLabel3.setSize( 200, 50 );
myLabel3.setLocation( 310, 10);
c.add(myLabel3);
myLabel4 = new JLabel("Vol Days");
myLabel4.setSize( 200, 50 );
myLabel4.setLocation( 400, 10 );
c.add(myLabel4);
myLabel5 = new JLabel("Transport");
myLabel5.setSize( 200, 50 );
myLabel5.setLocation( 500, 10 );
c.add(myLabel5);
volArray = new ArrayList<CVolunteer>();
volunteers = new DefaultListModel();
volList = new JList(volunteers);
volList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
scrollPane = new JScrollPane(volList);
scrollPane.setSize(500,300);
scrollPane.setLocation(100,50);
c.add(scrollPane);
bAdd = new JButton("Add");
bAdd.setSize( 100, 50 );
bAdd.setLocation( 20, 400 );
bAdd.addActionListener(this);
c.add(bAdd);
bEdit = new JButton("Edit");
bEdit.setSize( 100, 50 );
bEdit.setLocation( 150, 400 );
bEdit.addActionListener(this);
c.add(bEdit);
bRemove = new JButton("Remove");
bRemove.setSize( 100, 50 );
bRemove.setLocation( 280, 400 );
bRemove.addActionListener(this);
c.add(bRemove);
bClear = new JButton("Clear");
bClear.setSize( 100, 50 );
bClear.setLocation( 410, 400 );
bClear.addActionListener(this);
c.add(bClear);
bSave = new JButton("Save");
bSave.setSize( 100, 50 );
bSave.setLocation( 540, 400 );
bSave.addActionListener(this);
c.add(bSave);
bOpen = new JButton("Open");
bOpen.setSize( 100, 50 );
bOpen.setLocation( 670, 400 );
bOpen.addActionListener(this);
c.add(bOpen);
setSize( 800, 600 );
setLocation( 100, 100 );
setVisible(true);
volNumb = 0;
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==bAdd) {
volNumb++;
CVolunteer defaultVol = new CVolunteer(volNumb, "", 1, 0, 0);
CDialog dialogWnd = new CDialog(this, "Add a Volunteer", defaultVol);
if (!dialogWnd.isCancelled()) {
volArray.add(dialogWnd.getAnswer());
volunteers.addElement(dialogWnd.getAnswer().getVolunteerLine());
volList.setSelectedIndex(volunteers.size()-1);
volList.ensureIndexIsVisible(volunteers.size()-1);
}
}
else if(e.getSource()==bEdit) {
int index=volList.getSelectedIndex();
if (index>=0) {
CDialog dialogWnd = new CDialog (this, "Edit a Volunteer", volArray.get(index));
if (!dialogWnd.isCancelled()) {
volArray.set(index, dialogWnd.getAnswer());
volunteers.set(index, dialogWnd.getAnswer().getVolunteerLine());
}
}
}
else if(e.getSource()==bRemove) {
int index=volList.getSelectedIndex();
if (index>=0) {
volArray.remove(index);
volunteers.remove(index);
if (volunteers.size()>0) {
if (index==volunteers.size()) {
index--;
}
volList.setSelectedIndex(index);
volList.ensureIndexIsVisible(index);
}
}
}
else if(e.getSource()==bClear) {
volArray.clear();
volunteers.clear();
}
else if (e.getSource()==bSave)
{
//my sorry attempt at writing a file.. ignore this!
try {
FileWriter fw = new FileWriter(fileName);
Writer output = new BufferedWriter(fw);
int size = volArray.size();
for (int i = 0; i<size; i++)
{
output.write(volArray.get(i).getVolunteerLine() + "\n");
}
output.close();
}
catch (Exception e1) {
// TODO Auto-generated catch block
}
final JFileChooser fc = new JFileChooser();
}
else if (e.getSource()==bOpen)
{
}
}
public static void main(String[] args) {
TestDialog mainWnd = new TestDialog();
}
}
EDIT:
Here is some attempted code for my "Save" Button.... I still don't know if this is on the right track or not! It doesn't seem to be doing anything
else if (e.getSource()==bSave)
{
try
{
FileOutputStream fileOut = new FileOutputStream("???");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
for(int i=0; i<volArray.size(); i++)
{
out.writeObject(volArray.get(i).getVolunteerLine());
}
out.close();
fileOut.close();
} catch (Exception e1) {
// TODO Auto-generated catch block
}
final JFileChooser fc = new JFileChooser();
}
You have to use a specific format that you define to write in your file :
Add a serialize method in you volunteer class then you can iterate over them and serialize each of them.
String serialize() will encode all the members as a string then you can reconstruct at reading (on Open).
An example could be a coma separated list : member1=xxx, member2=xxx, ...
Or xml or json for more ease :)
At reading, it's the opposite, parse the content of the file and build your volunteers back !
Edit:
Saving:
Open a file in write mode
write all your n volunteers
at this point you should have n lines in your file
close the file
Reading:
Open your file in reading mode
Read it line by line
For each line
split over ','
build your volunteer
add it to volArray
close your file
Does it make sense for you ? Each of these steps are trivial with a simple google search
Edit :
Final JFileChooser fc = new JFileChooser();
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
log.append("Opening: " + file.getName() + "." + newline);
// Here you can open the file and write to it
//
} else {
log.append("Open command cancelled by user." + newline);
}
You can do the same when on open, select the file then read from it

Categories