Changing the button colour after making a booking - java

I'm having an issue when trying to change the colour of a button when referencing the button as a string? I want to change the colour when a booking has been made in my program and because I am reading from a file (in is a buffered reader) I was thinking about passing in the button name as a string
Is there any way to do this?
while (in.hasNext()){
seat = in.nextLine();
in.nextLine();
in.nextLine();
in.nextLine();
in.nextLine();
seatNum = "btn" + seat;
seatNum.setBackground(new java.awt.Color(255, 51, 0));
}

You can use these two functions:
public static void loadButtonAndUpdateColor(String filename) {
BufferedReader br;
try {
br = new BufferedReader(new FileReader(new File(filename)));
String[] color = br.readLine().split(",");
int[] vals = new int[3];
for (int i = 0; i < color.length; i++) {
vals[i] = Integer.parseInt(color[i]);
}
Color c = new Color(vals[0],vals[1],vals[2]);
btnNewButton.setBackground(c);
repaint();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnNewButton) {
FileWriter fos;
try {
fos = new FileWriter(new File("path to file"));
Color c = new Color(251,51,0);
fos.write("" + c.getRed() + "," + c.getGreen() + "," + c.getBlue());
fos.flush();
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
loadButtonAndUpdateColor("path to file");
}
}
The first one is static, and can be placed wherever you want.
The second one needs to be in your JFrame class. I named the button btnNewButton...

Related

Create text file dynamically in a specified directory, write data,read data from that file in java

Recently i have tried to write code of above given title and the problem is that i could not get sufficient date to write upon have a look at my code .it is showing some errors like
it is showing invalid token for semicolon after tagfile.createnewfile();
let us look at code:
public class WriteToFileExample {
String path = "G:"+File.separator+"Software"+File.separator+"Files";
String fname= path+File.separator+"fileName.txt";
boolean bool=false;
File f = new File(path);
File f1 = new File(fname);
try {
f1.createNewFile();
bool=f.mkdirs() ;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static final String FILENAME = "G:\\Software\\Files\\anil.txt";
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
String content = null;
String[] str = new String[100];
try (BufferedWriter bw = new BufferedWriter(new FileWriter(FILENAME))) {
System.out.println(" enter no.of line to be inserted into file");
int k = sc.nextInt();
for (int i = 0; i <= k; i++) {
System.out.println(" enter " + i + " line data");
content = sc.nextLine();
bw.write(content);
str[i] = content;
}
System.out.println("The content present in\n
G:\Software\Files\anil.txt is:");
for (int i = 1; i <= k; i++)
System.out.println(str[i]);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Please find the code and then you can use
**Writing** : PrintWriter,Scanner,BufferedWriter etc to write to that file
**Reading** :FileReader,BufferReader,Scanner with these readers etc
String path = "G:"+File.separator+"Software"+File.separator+"Files";
String fname= path+File.separator+"fileName.txt";
File f = new File(path);
File f1 = new File(fname);
f.mkdirs() ;
try {
f1.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Ref : https://www.lynda.com/Java-tutorials/Reading-writing-text-files/107061/113497-4.html
Refer above video which may help

How can I read lines of a file into an array then search for matching keywords?

I would like to read a file and store the lines in an array, then use a JOptionPane to search the array and display all lines which match a specified keyword.
This is what I have so far:
public class NeedleInHaystack {
public static void main(String[] args) {
JFileChooser jfc = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("jpg", "gif","txt");
jfc.setFileFilter(filter);
int returnCode = jfc.showOpenDialog(null);
if(returnCode == JFileChooser.APPROVE_OPTION);
File f = jfc.getSelectedFile();
System.out.println("You chose to open this file: " +jfc.getSelectedFile().getName());
try {
BufferedReader data;
String aLine;
data = new BufferedReader(new FileReader(jfc.getSelectedFile()));
List<String> lines = new ArrayList<String>();
String UserInPut= JOptionPane.showInputDialog("Please enter a word in your txt");
while((aLine = data.readLine()) != null){
lines.add(aLine);
}
String[] stringArr = lines.toArray(new String[0]);
for(int i=0 ; i < stringArr.length; i++){
System.out.println(aLine);
if (i<=15) { //here just a example, how to do this step
i++;
System.out.println(stringArr[0]);
}
}
data.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
this can help you
public static void main(String[] args) {
JFileChooser jfc = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("jpg", "gif", "txt");
jfc.setFileFilter(filter);
int returnCode = jfc.showOpenDialog(null);
if (returnCode == JFileChooser.APPROVE_OPTION)
;
File f = jfc.getSelectedFile();
System.out.println("You chose to open this file: " + jfc.getSelectedFile().getName());
try {
BufferedReader data;
String aLine;
data = new BufferedReader(new FileReader(jfc.getSelectedFile()));
List<String> lines = new ArrayList<String>();
String UserInPut = JOptionPane.showInputDialog("Please enter a word in your txt");
while ((aLine = data.readLine()) != null) {
lines.add(aLine);
// !!!Output userunput and line of file!!!
if (aLine.contains(UserInPut)) {
System.out.println(UserInPut + " -> " + aLine);
}
}
data.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Saving Game Scores

i am trying to make a highscore for a hangman game. So i need to save it so it doesnt restart everytime u start the game or return to the menu.. so I have a playstate that records the wins and losses at the end of the game and if the user leaves before solving it adds a loss. I found a tutorial to save via a SavaData file.. the problem is it saves an empty file nothing in there but has 2 empty lines.. and so i get a numberformatexception null.. i had it working before but it still would not read the line and would return an error numberformatexception Integer.parseInt.. I know the problem is in reading lines and now i dont know what went wrong please help me .. whats wrong with the code?? thanx
this is the saving code...
private void createSaveData() {
File file = new File(saveDataPath, filename);
try {
FileWriter output = new FileWriter(file);
BufferedWriter writer = new BufferedWriter(output);
writer.write("" + 0);
writer.newLine();
writer.write("" + 0);
} catch (Exception e) {
e.printStackTrace();
}
}
private void setScores() {
FileWriter output = null;
try {
File F = new File(saveDataPath, filename);
output = new FileWriter(F);
BufferedWriter writer = new BufferedWriter(output);
writer.write(wins);
writer.newLine();
writer.write(losses);
writer.close();
}catch (Exception e){
e.printStackTrace();
}
}
private void loadScores() {
try {
File F = new File(saveDataPath, filename);
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(F)));
String line = reader.readLine();
line = reader.readLine();
wins = Integer.parseInt(line);
line = reader.readLine();
losses = Integer.parseInt(line);
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
i then add loadScore(); at the begging of the playstate.. and setScore(); after a win++ or a loss++..
i have another highscorestate that calls on playstate and gets the wins and lossess as an integer and that works no problems cause it draws 0 , 0 .
in my render method i have this if the tries are too much or if the correct answer is guessed...
if (tries == 6) {
currentWord = ranWord;
execcurrentframe.setRegion(eman.ExecLoss.getKeyFrame(elapsedTime, false));
hangcurrentframe.setRegion(hman.hangdead.getKeyFrame(elapsedTime, false));
Wordsfont.draw(batch, "Game Over", eman.getPosition().x + 60, hman.getPosition().y + 70);
batch.draw(fu, 160, 510);
if (leverpressed == false){
bksound.stop();
lever.play();
leverpressed = true;
}
if (lossrecorded == false) {
losses += 1;
System.out.print("Losses = " + losses);
setScores();
lossrecorded = true;
}
}
else if (CorrectAnswer == true) {
hangcurrentframe.setRegion(hman.hangwin.getKeyFrame(elapsedTime, false));
Wordsfont.draw(batch, "You Won", eman.getPosition().x + 60, hman.getPosition().y + 70);
if (winrecorded == false) {
bksound.stop();
victory.play();
wins += 1;
System.out.print("Wins = " + wins);
setScores();
winrecorded = true;
}
}
I would suggest the following changes.
Use a single writeSaveData method. The code between createSaveData and setScores is largely duplicated. Also, use the Integer.toString() to write the output. Also, ensure the stream is closed (here using try with resources).
private void writeSaveData(int wins, int losses)
{
File file = new File(saveDataPath, filename);
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(Integer.toString(wins));
writer.newLine();
writer.write(Integer.toString(losses));
}
catch (Exception e) {
e.printStackTrace();
}
}
There is an extra readLine() in the loadScores() method. Remove that extra line. Change to use try with resources.
private void loadScores()
{
File file = new File(saveDataPath, filename);
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
String line = reader.readLine();
// line = reader.readLine() <-- REMOVE THIS LINE
wins = Integer.parseInt(line);
line = reader.readLine();
losses = Integer.parseInt(line);
reader.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
EDIT: If one cannot use try with resources, then the following approach may be used instead.
private void loadScores()
{
File file = new File(saveDataPath, filename);
BufferedReader reader = null;
// try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line = reader.readLine();
wins = Integer.parseInt(line);
line = reader.readLine();
losses = Integer.parseInt(line);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (reader != null) {
try {
reader.close();
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}
A similar modification may be made to the suggested writeSaveData() or other methods.
You have overlooked one important part of the original createSaveData method:
writer.write("" + 0);
See that "" + 0? It effectively converts the integer to a string (though there are more elegant ways of doing this).
BufferedWriter has overloaded write method. This means there is a different method that is called when the parameter is a String, and a different one when the parameter is an int.
You have called the version whose parameter is an int. Its documentation says:
public void write(int c) throws IOException
Writes a single character.
Overrides:
write in class Writer
Parameters:
c - int specifying a character to be
written
Throws:
IOException - If an I/O error occurs
This tells you that it considers the int that you passed as a character. That is, if you give it the int 65, it will be taken as the character A. If you give it the int 48, it will be taken as the character 0.
If you give it the integer 0, this is the NUL control character.
When you read that back as a string, it is taken as a single-character string containing the NUL character. Of course, that's not a valid string format for a number.
So replace
writer.write(wins);
With
writer.write(String.valueOf(wins));
And do the same for losses.

How to Update or delete a specific line from a .txt file?

I already have methods to insert data in to a text file and search. now I want methods for 'updating' and 'deleting' a selected record.
this is what I have done so far,
private void InsertbuttonActionPerformed(java.awt.event.ActionEvent evt) {
fileWriter = null;
try {
String phone = Phone.getText();
String fname = Fname.getText();
String lname = Lname.getText();
String nic = NIC.getText();
String city = City.getSelectedItem().toString();
fileWriter = new FileWriter(file, true);
fileWriter.append(phone + "|" + fname + "|" + lname + "|" + nic + "|" + city+ "|");
fileWriter.append("\r\n");
fileWriter.flush();
JOptionPane.showMessageDialog(InsertGUI.this, "<html> " + phone + " <br> Successfully saved! </html>");
Phone.setText(null);
NIC.setText(null);
Fname.setText(null);
Lname.setText(null);
City.setSelectedIndex(0);
} catch (IOException ex) {
Logger.getLogger(InsertGUI.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
fileWriter.close();
} catch (IOException ex) {
Logger.getLogger(InsertGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void searchbuttonActionPerformed(java.awt.event.ActionEvent evt) {
try {
fileReader = new FileReader(file);
BufferedReader br = new BufferedReader(fileReader);
String selectedphone = SearchF.getText();
String content = "";
String temp = "";
try {
while ((temp = br.readLine()) != null) {
content += temp;
}
} catch (IOException ex) {
Logger.getLogger(UpdateGUI.class.getName()).log(Level.SEVERE, null, ex);
}
HashMap<String, String> map = new HashMap();
StringTokenizer stringTokenizer = new StringTokenizer(content, "|");
boolean found = false;
while (stringTokenizer.hasMoreTokens()) {
String phone = stringTokenizer.nextElement().toString();
String fname = stringTokenizer.nextElement().toString();
String lname = stringTokenizer.nextElement().toString();
String nic = stringTokenizer.nextElement().toString();
String city = stringTokenizer.nextElement().toString();
if (phone.equalsIgnoreCase(selectedphone)) {
Phone.setText(phone);
NIC.setText(nic);
Fname.setText(fname);
Lname.setText(lname);
switch (city) {
case "Ambalangoda":
City.setSelectedIndex(0);
break;
case "Ampara":
City.setSelectedIndex(1);
break;
case "Anuradhapura":
City.setSelectedIndex(2);
break;
case "Avissawella":
City.setSelectedIndex(3);
break;
case "Badulla":
City.setSelectedIndex(4);
break;
case "Balangoda":
City.setSelectedIndex(5);
break;
}
found = true;
}
}
if (!found) {
JOptionPane.showMessageDialog(UpdateGUI.this, "Phone number not found!");
Phone.setText(null);
NIC.setText(null);
Fname.setText(null);
Lname.setText(null);
City.setSelectedIndex(0);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(UpdateGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
can someone please help me with this?
I want methods for:
private void UpdatebuttonActionPerformed(java.awt.event.ActionEvent evt) {
}
private void DeleteButtonActionPerformed(java.awt.event.ActionEvent evt) {
}
Thanks in advance! :)
I give you an example that i found. In this example i will replace a string inside of a line. You can see that in my case im reading from a txt.
/******
public static void replaceSelected(String replaceWith, String type) {
try {
// input the file content to the String "input"
BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
String line;String input = "";
while ((line = file.readLine()) != null) input += line + '\n';
file.close();
System.out.println(input); // check that it's inputted right
// this if structure determines whether or not to replace "0" or "1"
if (Integer.parseInt(type) == 0) {
input = input.replace(replaceWith + "1", replaceWith + "0");
}
else if (Integer.parseInt(type) == 1) {
input = input.replace(replaceWith + "0", replaceWith + "1");
}
// check if the new input is right
System.out.println("----------------------------------" + '\n' + input);
// write the new String with the replaced line OVER the same file
FileOutputStream fileOut = new FileOutputStream("notes.txt");
fileOut.write(input.getBytes());
fileOut.close();
} catch (Exception e) {
System.out.println("Problem reading file.");
}
}
public static void main(String[] args) {
replaceSelected("Do the dishes","1");
}
*/
Result:
Original:
Original Text File Content:
Do the dishes0
Feed the dog0
Cleaned my room1
Output:
Do the dishes0
Feed the dog0
Cleaned my room1
Do the dishes1
Feed the dog0
Cleaned my room1
Recent output:
Do the dishes1 (HAS BEEN CHANGED)
Feed the dog0
Cleaned my room1
Maybe this example helps for you.
Regards!
Read data to string. Use string.replace(forDelte,""). And then just rewrite to txt file.

Java Reading Text File Yielding Null Result

Here I have some code where I create an ActionListener for a JCheckBox.
Once the user clicks the JCheckBox the actionlistener is triggered and this code runs.
First I check whether they are selecting it or deselecting the check box and I input this into the text file. I re-input the checkbox's text plus a 0 if the user is deselecting it or a 1 if they are selecting it.
However, when I try to read through my file using a loop it seems to only result in null values. Here is an excerpt of exactly what I'm talking about.
for (int i = 0; i < notes.length; i++) {
String text;
try {
text = br.readLine();
if (text.contains(s)) {
brw.write(s + "0");
brw.newLine();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
The notes.length is an array that contains the amount of lines of my file. I've also tried changing that to an int that held line the line count. No change, still didn't work. If I print out "text" and "s" I get the checkbox's text value followed by "null". The text variable should have a value.
I get a NullPointerException..
selected
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at SideNotes$2.actionPerformed(SideNotes.java:86)
By the way.. when I read the file in other places I do not get a NullPointerException. It returns the line just fine.
Full code:
File file = new File("notes.txt");
if (file.exists()) {
try {
FileInputStream fs = new FileInputStream(file);
final BufferedReader br = new BufferedReader(
new InputStreamReader(fs));
final BufferedReader reader = new BufferedReader(
new FileReader("notes.txt"));
FileWriter writer = new FileWriter(file, true);
final BufferedWriter brw = new BufferedWriter(writer);
while (reader.readLine() != null)
lines++;
// reader.close();
notes = new JCheckBox[lines];
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JCheckBox checkbox = (JCheckBox) e.getSource();
if (checkbox.isSelected()) {
System.out.println("selected");
String s = checkbox.getText();
for (int i = 0; i < notes.length; i++) {
String text;
try {
text = br.readLine();
if (text.contains(s)) {
brw.write(s + "0");
brw.newLine();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
} else {
System.out.println("deselected");
String s = checkbox.getText();
for (int i = 0; i < notes.length; i++) {
String text;
try {
text = br.readLine();
if (text.contains(s)) {
brw.write(s + "0");
brw.newLine();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
};
Why am I getting a null result, and how do I fix it?
I think this one should be :
String s = checkBox.getText().toString();
so you can set the value of text as String.

Categories

Resources