Practicing IO with a highscore example - java

This is what I came up with after tinkering for a couple hours. Sadly it leaves me with an empty highscore scene.
public HighScoresPresenter(HighScoresModel model, HighScoresView view) {
this.model = model;
this.view = view;
addEventHandlers();
updateView();
}
private void updateView() {
Label[] namen = new Label[9];
Label[] scores = new Label[9];
String[] strings;
try {
Scanner scanner = new Scanner(new File(HighScoresModel.getBESTANDSNAAM()));
scanner.useDelimiter(System.lineSeparator());
for (int i = 0;i<9;i++){
strings = scanner.nextLine().split(",");
namen[i] = new Label(strings[1]);
scores[i] = new Label(strings[0]);
}
view.setNamen(namen);
view.setScores(scores);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
This is what the .txt file looks like.
2500,Peter
2400,Elisabeth
2200,Josje
1900,Sebastiaan
1500,Petra
1500,Jozef
1500,Dave
1400,Karen
1200,Kristel
1000,Jules
Highscores are separated by \n. Score and name are separated by ",".
public class HighScoresView extends GridPane {
private Label naamKop;
private Label scoreKop;
private Label[] namen;
private Label[] scores;
public HighScoresView() {
initialiseNodes();
layoutNodes();
}
private void initialiseNodes() {
naamKop = new Label("Naam");
scoreKop = new Label("Score");
namen = new Label[HighScores.AANTAL_HIGHSCORES];
scores = new Label[HighScores.AANTAL_HIGHSCORES];
for (int i = 0; i < HighScores.AANTAL_HIGHSCORES; i++) {
namen[i] = new Label("");
scores[i] = new Label("");
}
}
private void layoutNodes() {
setGridLinesVisible(true);
naamKop.setPadding(new Insets(2, 10, 8, 10));
naamKop.setPrefWidth(120);
scoreKop.setPadding(new Insets(2, 10, 8, 10));
scoreKop.setPrefWidth(120);
add(naamKop, 0, 0);
add(scoreKop, 1, 0);
for (int i = 0; i < HighScores.AANTAL_HIGHSCORES; i++) {
add(namen[i], 0, (i + 1));
add(scores[i], 1, (i + 1));
namen[i].setPadding(new Insets(5, 0, 5, 10));
scores[i].setPadding(new Insets(5, 0, 5, 10));
}
}
Label[] getNaamLabels() {
return namen;
}
Label[] getScoreLabels() {
return scores;
}
public void setNamen(Label[] namen) {
this.namen = namen;
}
public void setScores(Label[] scores) {
this.scores = scores;
}
}

Got updateView() working by changing the following things. (presenter class)
private void updateView() {
String[] namen = new String[10];
String[] scores = new String[10];
String[] strings;
try {
Scanner scanner = new Scanner(new File(HighScoresModel.getBESTANDSNAAM()));
scanner.useDelimiter(System.lineSeparator());
for (int i = 0;i<10;i++){
strings = scanner.nextLine().split(",");
namen[i] = strings[1];
scores[i] = strings[0];
}
view.setNaamText(namen);
view.setScoresText(scores);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Added different setters, although the assignment said this class was complete. (view class)
public void setNaamText(String[] namen) {
for (int i=0;i<namen.length;i++) {
this.namen[i].setText(namen[i]);
}
}
public void setScoresText(String[] scores) {
for (int i=0;i<scores.length;i++) {
this.scores[i].setText(scores[i]);
}
}

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);
}
}
}

How to connect method from another class to actionListener?

I'm trying to finish my project about searching graphs, where one of the functions is input (vertex and edges) from user.
I already have a method for this in another class, but now I need to put it into GUI.
I've already tried many of tutorials, but nothing worked. Can somebody help me, how to put the method getInputFromCommand to gui?
I've already tried to copy the method into the GUI, but there was problem with the "return g" because of the void result type, I've tried just to call the method, (I know.. stupid) but it didn't work either.
package Process;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;
public class FindIslands {
String message = "";
int V;
LinkedList<Integer>[] adjListArray;
static LinkedList<String> nodeList = new LinkedList<String>();
// constructor
FindIslands(int V) {
this.V = V;
adjListArray = new LinkedList[V];
for (int i = 0; i < V; i++) {
adjListArray[i] = new LinkedList<Integer>();
}
}
void addEdge(int src, int dest) {
adjListArray[src].add(dest);
adjListArray[dest].add(src);
}
void DFSUtil(int v, boolean[] visited) {
visited[v] = true;
message += getValue(v) + " ";
// System.out.print(getValue(v) + " ");
for (int x : adjListArray[v]) {
if (!visited[x]) {
DFSUtil(x, visited);
}
}
}
void connectedComponents() {
boolean[] visited = new boolean[V];
int count = 0;
message = "";
for (int v = 0; v < V; ++v) {
if (!visited[v]) {
DFSUtil(v, visited);
message += "\n";
// System.out.println();
count++;
}
}
System.out.println("" + count);
System.out.println("");
System.out.println("Vypis ostrovu: ");
String W[] = message.split("\n");
Arrays.sort(W, new java.util.Comparator<String>() {
#Override
public int compare(String s1, String s2) {
// TODO: Argument validation (nullity, length)
return s1.length() - s2.length();// comparison
}
});
for (String string : W) {
System.out.println(string);
}
}
public static void main(String[] args) {
FindIslands g = null; //
String csvFile = "nodefile.txt";
BufferedReader br = null;
String line = "";
int emptyLine = 0;
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
if (line.equals("")) {
emptyLine = 1;
// System.out.println("found blank line");
}
if (emptyLine == 0) {
// System.out.println(line);
nodeList.add(line);
} else if (line.isEmpty()) {
g = new FindIslands(nodeList.size());
} else {
String[] temp = line.split(",");
g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
}
}
} catch (FileNotFoundException e) {
System.out.println("Soubor nenalezen, zadejte data v danem formatu");
g = getInputFromCommand();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Pocet ostrovu");
if (g != null) {
g.connectedComponents();
}
}
public static int getIndex(String str) {
return nodeList.indexOf(str);
}
public static String getValue(int index) {
return nodeList.get(index);
}
public static FindIslands getInputFromCommand() {
FindIslands g = null;
BufferedReader br = null;
String line = "";
int emptyLine = 0;
Scanner scanner = new Scanner(System.in);
line = scanner.nextLine();
while (!line.equals("")) {
if (line.equals("--gui")) {
Guicko gui = new Guicko();
gui.setVisible(true);
} else
nodeList.add(line);
line = scanner.nextLine();
}
g = new FindIslands(nodeList.size());
line = scanner.nextLine();
while (!line.equals("")) {
String[] temp = line.split(",");
if (temp.length != 2) {
System.out.println("spatny format zadanych dat, prosim zkuste znovu");
} else {
g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
}
line = scanner.nextLine();
}
return g;
}
}
Where important is the last method "getInputFromCommand()"
and... gui
package Process;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.util.Scanner;
public class Guicko extends JFrame {
private JButton štartButton;
private JPanel panel;
private JTextField textField2;
private JTextArea textArea1;
public Guicko() {
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setTitle("Zadej hodnoty");
setSize(500, 400);
textField2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
FindIslands.getInputFromCommand();
}
});
štartButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String str = "asd";
FindIslands g = null;
g.connectedComponents();
textArea1.setText(str);
}
});
}
public static void main (String args[]){
Guicko gui = new Guicko();
gui.setVisible(true);
}
}
I'm sure there are many correct ways this code can be fixed, but in IMHO, your Guicko class needs to have a FindIslands class member, and I think you need to move some stuff from FindIslands.main() into Guicko.main() or some other method.
Then your "Action Listener" inner classes' actionPerformed methods just delegate to the methods in the FindIslands member instance, like this
....
private FindIslands fi;
public Guicko() {
....
textField2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
fi = FindIslands.getInputFromCommand();
}
});
startButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String comps = fi.connectedComponents();// method needs to return a string
textArea1.setText(comps);
}
});
}
The whole idea of seperating GUI from domain is to make changes easily. GUI has knowledge of the domain but domain has no knowledge about the GUI. We can use an interface to seperate them, in that case, Domain says , i don't care who implements this interface but whoever implements this interface will get response and can work with me.
So , If we create a new GUI, we can let it implements that interface and the same domain will work with that GUI.
There are many mistakes but in order to make it work and to show you an example i did few changes.
public class Guicko extends JFrame implements PropertyChangeListener{
private JButton štartButton;
private JPanel panel;
private JTextField textField2;
private JTextArea textArea1;
private FindIslands land;
private JTextField textField;
private JButton button;
public Guicko() {
JPanel panel = new JPanel();
super.getContentPane().setLayout(new GridLayout());
//For each gui, there should be one land.
this.setLand(new FindIslands(100));
//Subscribe to the domain so that you can get update if something change in domain.
this.getLand().subscribe(this);
//Dummy buttons are fields(need too initiate first)
textField2 = new JTextField("",30);
štartButton = new JButton();
textField = new JTextField("",30);
button = new JButton();
button.setPreferredSize(new Dimension(100, 40));
button.setText("Get input from Domain");
štartButton.setPreferredSize(new Dimension(100, 40));
textField.setEditable(false);
štartButton.setText("Start");
panel.add(textField2);
panel.add(štartButton);
panel.add(textField);
panel.add(button);
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setTitle("Zadej hodnoty");
setSize(500, 400);
//When you type something in , then this function will send it to domain(i mean to function : getInputFromCommand();).
this.addListerToField(štartButton,this.getLand(),textField2);
//Now the second case, suppose you press a button and want something to show up in textfield. In that case , this function will do work.
this.addListerToSecondField(button,this.getLand(),textField);
}
//Here i can catch the events from the domain.
#Override
public void propertyChange(PropertyChangeEvent e) {
if(e.getPropertyName().equals("String changed")) {
this.getTextField().setText((String) e.getNewValue());
}
}
private void addListerToSecondField(JButton button, FindIslands land, JTextField field) {
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
land.requireArgumentsForField();
}
});
}
private void addListerToField(JButton štartButton, FindIslands land, JTextField field) {
štartButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
land.getInputFromCommand(field.getText());
}
});
}
public static void main (String args[]){
Guicko gui = new Guicko();
gui.setVisible(true);
}
public FindIslands getLand() {
return land;
}
public void setLand(FindIslands land) {
this.land = land;
}
public JTextField getTextField() {
return textField;
}
public void setTextField(JTextField textField) {
this.textField = textField;
}
public JButton getButton() {
return button;
}
public void setButton(JButton button) {
this.button = button;
}
Here is the second class. Run it and try to get feeling for it how it works.
public class FindIslands {
String message = "";
int V;
LinkedList<Integer>[] adjListArray;
static LinkedList<String> nodeList = new LinkedList<String>();
// constructor
FindIslands(int V) {
this.V = V;
//initialize the list
this.setListeners(new ArrayList<>());
adjListArray = new LinkedList[V];
for (int i = 0; i < V; i++) {
adjListArray[i] = new LinkedList<Integer>();
}
}
void addEdge(int src, int dest) {
adjListArray[src].add(dest);
adjListArray[dest].add(src);
}
void DFSUtil(int v, boolean[] visited) {
visited[v] = true;
message += getValue(v) + " ";
// System.out.print(getValue(v) + " ");
for (int x : adjListArray[v]) {
if (!visited[x]) {
DFSUtil(x, visited);
}
}
}
void connectedComponents() {
boolean[] visited = new boolean[V];
int count = 0;
message = "";
for (int v = 0; v < V; ++v) {
if (!visited[v]) {
DFSUtil(v, visited);
message += "\n";
// System.out.println();
count++;
}
}
System.out.println("" + count);
System.out.println("");
System.out.println("Vypis ostrovu: ");
String W[] = message.split("\n");
Arrays.sort(W, new java.util.Comparator<String>() {
#Override
public int compare(String s1, String s2) {
// TODO: Argument validation (nullity, length)
return s1.length() - s2.length();// comparison
}
});
for (String string : W) {
System.out.println(string);
}
}
//You need only one main class, not two.----------------------------
/**
public static void main(String[] args) {
FindIslands g = null; //
String csvFile = "nodefile.txt";
BufferedReader br = null;
String line = "";
int emptyLine = 0;
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
if (line.equals("")) {
emptyLine = 1;
// System.out.println("found blank line");
}
if (emptyLine == 0) {
// System.out.println(line);
nodeList.add(line);
} else if (line.isEmpty()) {
g = new FindIslands(nodeList.size());
} else {
String[] temp = line.split(",");
g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
}
}
} catch (FileNotFoundException e) {
System.out.println("Soubor nenalezen, zadejte data v danem formatu");
g = getInputFromCommand();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Pocet ostrovu");
if (g != null) {
g.connectedComponents();
}
}
**/
public static int getIndex(String str) {
return nodeList.indexOf(str);
}
public static String getValue(int index) {
return nodeList.get(index);
}
//Static cases are to be avoided.This is the property of object not class.
public void getInputFromCommand(String string) {
//Here you will recieve a string from the GUI and will be printed in command prompt.You can do whatever you want to do with it.
System.out.println("Recieve string is " + string);
//No idea what you are trying to do.
/** FindIslands g = null;
BufferedReader br = null;
String line = "";
int emptyLine = 0;
Scanner scanner = new Scanner(System.in);
line = scanner.nextLine();
while (!line.equals("")) {
if (line.equals("--gui")) {
Guicko gui = new Guicko();
gui.setVisible(true);
} else
nodeList.add(line);
line = scanner.nextLine();
}
g = new FindIslands(nodeList.size());
line = scanner.nextLine();
while (!line.equals("")) {
String[] temp = line.split(",");
if (temp.length != 2) {
System.out.println("spatny format zadanych dat, prosim zkuste znovu");
} else {
g.addEdge(getIndex(temp[0]), getIndex(temp[1]));
}
line = scanner.nextLine();
}
return line;**/
}
//This function is triggered with second button and you can send data to gui as shown below.
public void requireArgumentsForField() {
//Suppose i want to send following string.
String name = "I don't know";
this.getListeners().stream().forEach(e -> {
// I will catch this in view.
e.propertyChange(new PropertyChangeEvent(this, "String changed", null, name));
});
}
private ArrayList<PropertyChangeListener> listeners;
//Let the objects subscibe. You need this to publish the changes in domain.
public void subscribe(PropertyChangeListener listener) {
this.getListeners().add(listener);
}
public ArrayList<PropertyChangeListener> getListeners() {
return listeners;
}
public void setListeners(ArrayList<PropertyChangeListener> listeners) {
this.listeners = listeners;
}

Application not displaying GUI and won't quit Java

So I'm creating a game in Java and I ran into a little problem. Whenever I run the application the GUI does not show on the screen and the only way to close the application is to use the Windows Task Manager. In the application, you choose a username and click an enter button which creates a new window in which the game is played. But after you click the button, none of the GUI loads and you can't close the application.
Basically, when you click the button, a method is called that disposes the current window and starts the game window. The code for that method is below:
public void login(String name) {
String[] args={};
dispose();
SingleplayerGUI.main(args);
}
And here is the code of the SingleplayerGUI class:
public SingleplayerGUI(String userName, Singleplayer sp) {
this.userName = userName;
setResizable(false);
setTitle("Console Clash Singleplayer");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(880, 550);
setLocationRelativeTo(null);
System.setIn(inPipe);
try {
System.setOut(new PrintStream(new PipedOutputStream(outPipe), true));
inWriter = new PrintWriter(new PipedOutputStream(inPipe), true);
} catch (IOException e1) {
e1.printStackTrace();
}
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[] { 28, 815, 30, 7 }; // SUM = 880
gbl_contentPane.rowHeights = new int[] { 25, 485, 40 }; // SUM = 550
contentPane.setLayout(gbl_contentPane);
history = new JTextPane();
history.setEditable(false);
JScrollPane scroll = new JScrollPane(history);
caret = (DefaultCaret) history.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
GridBagConstraints scrollConstraints = new GridBagConstraints();
scrollConstraints.insets = new Insets(0, 0, 5, 5);
scrollConstraints.fill = GridBagConstraints.BOTH;
scrollConstraints.gridx = 0;
scrollConstraints.gridy = 0;
scrollConstraints.gridwidth = 2;
scrollConstraints.gridheight = 2;
scrollConstraints.weightx = 1;
scrollConstraints.weighty = 1;
scrollConstraints.insets = new Insets(0, 0, 5, -64);
contentPane.add(scroll, scrollConstraints);
txtMessage = new JTextField();
txtMessage.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
Color color = new Color(92, 219, 86);
String text = txtMessage.getText();
inWriter.println(text);
console(txtMessage.getText(), color);
command = txtMessage.getText();
}
}
});
GridBagConstraints gbc_txtMessage = new GridBagConstraints();
gbc_txtMessage.insets = new Insets(0, 0, 0, 25);
gbc_txtMessage.fill = GridBagConstraints.HORIZONTAL;
gbc_txtMessage.gridx = 0;
gbc_txtMessage.gridy = 2;
gbc_txtMessage.gridwidth = 2;
gbc_txtMessage.weightx = 1;
gbc_txtMessage.weighty = 0;
txtMessage.setColumns(5);
contentPane.add(txtMessage, gbc_txtMessage);
chat = new JTextPane();
chat.setEditable(false);
JScrollPane chatscroll = new JScrollPane(chat);
caret = (DefaultCaret) chat.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
GridBagConstraints chatscrollConstraints = new GridBagConstraints();
chatscrollConstraints.insets = new Insets(0, 0, 5, 5);
chatscrollConstraints.fill = GridBagConstraints.BOTH;
chatscrollConstraints.gridx = 0;
chatscrollConstraints.gridy = 0;
chatscrollConstraints.gridwidth = 2;
chatscrollConstraints.gridheight = 2;
chatscrollConstraints.weightx = 1;
chatscrollConstraints.weighty = 1;
chatscrollConstraints.insets = new Insets(150, 600, 5, -330);
contentPane.add(chatscroll, chatscrollConstraints);
chatMessage = new JTextField();
final String name = this.userName;
chatMessage.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
chatconsole(name + ": " + chatMessage.getText());
}
}
});
GridBagConstraints gbc_chatMessage = new GridBagConstraints();
gbc_txtMessage.insets = new Insets(000, 600, 000, -330);
gbc_txtMessage.fill = GridBagConstraints.HORIZONTAL;
gbc_txtMessage.gridx = 0;
gbc_txtMessage.gridy = 2;
gbc_txtMessage.gridwidth = 2;
gbc_txtMessage.weightx = 1;
gbc_txtMessage.weighty = 0;
txtMessage.setColumns(5);
contentPane.add(chatMessage, gbc_txtMessage);
JButton btnSend = new JButton("Send");
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Color color = new Color(92, 219, 86);
String text = txtMessage.getText();
inWriter.println(text);
console(txtMessage.getText(), color);
command = txtMessage.getText();
}
});
GridBagConstraints gbc_btnSend = new GridBagConstraints();
gbc_btnSend.insets = new Insets(0, 0, 0, 275);
gbc_btnSend.gridx = 2;
gbc_btnSend.gridy = 2;
gbc_btnSend.weightx = 0;
gbc_btnSend.weighty = 0;
contentPane.add(btnSend, gbc_btnSend);
list = new JList();
GridBagConstraints gbc_list = new GridBagConstraints();
gbc_list.insets = new Insets(0, 600, 330, -330);
gbc_list.fill = GridBagConstraints.BOTH;
gbc_list.gridx = 0;
gbc_list.gridy = 0;
gbc_list.gridwidth = 2;
gbc_list.gridheight = 2;
JScrollPane p = new JScrollPane();
p.setViewportView(list);
contentPane.add(p, gbc_list);
list.setFont(new Font("Verdana", 0, 24));
System.out.println("HEY");
setVisible(true);
new SwingWorker<Void, String>() {
protected Void doInBackground() throws Exception {
Scanner s = new Scanner(outPipe);
while (s.hasNextLine()) {
String line = s.nextLine();
publish(line);
}
return null;
}
#Override protected void process(java.util.List<String> chunks) {
for (String line : chunks) {
try {
Document doc = history.getDocument();
doc.insertString(doc.getLength(), line + "\r\n", null);
} catch(BadLocationException exc) {
exc.printStackTrace();
}
}
}
}.execute();
Singleplayer spp = new Singleplayer();
Singleplayer.startOfGame();
setVisible(true);
}
public static void console(String message, Color color) {
txtMessage.setText("");
try {
StyledDocument doc = history.getStyledDocument();
Style style = history.addStyle("", null);
StyleConstants.setForeground(style, color);
doc.insertString(doc.getLength(), message + "\r\n", style);
} catch(BadLocationException exc) {
exc.printStackTrace();
}
}
public static void console(String message) {
txtMessage.setText("");
try {
Document doc = history.getDocument();
doc.insertString(doc.getLength(), message + "\r\n", null);
} catch(BadLocationException exc) {
exc.printStackTrace();
}
}
public void chatconsole(String message) {
chatMessage.setText("");
try {
Document doc = chat.getDocument();
doc.insertString(doc.getLength(), message + "\r\n", null);
} catch(BadLocationException exc) {
exc.printStackTrace();
}
}
public static void single() {
Singleplayer sp = new Singleplayer();
new SingleplayerGUI("", sp);
}
public static void main(String[] args) {
Singleplayer sp = new Singleplayer();
new SingleplayerGUI("", sp);
}
And the singleplayer class:
public static void startOfGame(){
System.out.println("HEY");
SingleplayerGUI.console("Welcome to Console Clash Pre Alpha Version 1!");
SingleplayerGUI.console("Created by Drift");
SingleplayerGUI.console("Published by Boring Games");
SingleplayerGUI.console("");
SingleplayerGUI.console("");
menuScreen();
}
static void menuScreen() {
Scanner scan = new Scanner(System.in);
System.out.println("To play the game, type 'start'. To quit, type 'quit'.");
String menu = scan.nextLine();
if (menu.equals("start")) {
start();
} else if (menu.equals("quit")) {
quit();
} else {
menuScreen();
}
}
private static void quit() {
SingleplayerGUI.console("You quit the game.");
}
private static void start() {
SingleplayerGUI.console("You started the game.");
}
So far I've figured out that the problem most likey occurs when adding the outPipe to the console. Would I be able to fix this or am I just not able to use outPipes with this application?
Thanks in advance for your help.
The setVisible() method is invoked twice.. Remove the second setVisible() call after the Singleplayer.startOfGame(); line in SingleplayerGUI constructor.

Saving/Loading Config Not Working

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.

Categories