i am working on a project where i have to display a set of records then the user can select 1 or more of these records to move them to another set.
i think the most appropiate componenet to use is Checkboxes. my probelm is that i cant add the check boxes to the frame automatically while reading the file. i added a panel, and added the check box but it still doesnt appear after using paint, or updateUI.
this is my code:
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file.getAbsolutePath()), "UTF-8"));
String line = reader.readLine();
String text = "";
while (line != null) {
text += line;
line = reader.readLine();
}
ArrayList<String> records = new ArrayList<String>(Arrays.asList(text.split("")));
for(String rec: records){
resPanal.add(new JCheckBox(rec));
}
resPanal.updateUI();
the number of records is not constant, so i need a way to add the components = to the number of records found.
i am open to other suggestions that can help other than check boxes
for anyone interested:
i tried what #TerryStorm suggested in a small program with only a button, and each time the button is clicked a box is added
private void addCBActionPerformed(java.awt.event.ActionEvent evt) {
JCheckBox box=new JCheckBox("add");
box.setVisible(true);
jPanel1.add(box);
jPanel1.updateUI();
}
Related
I've hit a roadblock in my jFrame form programming and no solutions comes up on the internet.
I'm creating a booking system where it requires the User to have the ability to view, book or cancel booking hour slots. I can save a row of code as an array with commas (",") as a means to separate the various types of data (time, place, date etc) into a text file.
I am able to write and read the text file and display it into a jTable. Retrieval is not the problem here, however, as my current problem is clicking on a selected row in the jTable and changing a particular column data with the click of a button and saving it into a text file, replacing the previous line.
I have heard suggestions of using a temp file and deleting the previous text file but I am unable to reproduce that technique into practice.
An example of my JTable structure shows up as follows:
|StaffID|EmployeeID|Status |Location |Time Start |Duration | Date |
| ID10t | IDidN4Ht |Available| Here | 12:30 | 30 min | 12/3/2020 |
|Lorelai| Gorbachev| Booked | There | 6 BCE |40 years| 02/02/11 |
An example of the data that would be saved in text files is as follows, with commas (",") as delimiter:
ID10t,IDidN4Ht,Available,Here,12:30,30 min,12/3/2020
Lorelai,Gorbachev,Booked,There,6 BCE,40 years,02/02/11
testStaff,-,Available,Room-5A,10:40pm,15mins,13/12/2023
IDqq,ID01,b,Class A,10:30am,15mins,13/11/2023
Assuming StaffID in the Jtable && String "test" in the text file = column[0],
what would I need to do if I wanted to click on a Book button that would change column[1]/EmployeeID in the text file from a dash ("-") into the current User's EmployeeID as well as change column[3]/Status from "Available" to "Booked", then save the new data into the text file?
I've tried various BufferedReader and FileWriter methods, tried creating and using an #Override class, but to no results.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
//I am using Comboboxes to save the data, hence the .getSelectedItem
//This is the code for the Adding button which I use to write the data into the text file, which is "info.txt"
String staffid = jLabel1.getText().trim();
String empid = "-";
String status = "Available";
String venue = venueb.getSelectedItem().toString();
String time = timeb.getSelectedItem().toString();
String dura = durab.getSelectedItem().toString();
String date = dateb.getSelectedItem().toString();
try {
FileWriter writer = new FileWriter("info.txt", true);
BufferedWriter print = new BufferedWriter(writer);
Scanner sc = new Scanner("info.txt");
while (sc.hasNext()) {
print.newLine(); //newLine added so each row will stack
print.write(staffid);
print.write(",");
print.write(empid);
print.write(",");
print.write(status);
print.write(",");
print.write(venue);
print.write(",");
print.write(time);
print.write(",");
print.write(dura);
print.write(",");
print.write(date);
print.close();
JOptionPane.showMessageDialog(rootPane, "Booking Added");
}
} catch (Exception e) {
e.printStackTrace();
}
//This is the code I use the Update button to retrieve the data from the text file and display them into the jTable
table = (DefaultTableModel)jTable1.getModel();
table.setColumnIdentifiers(
new String[]{"Staff ID","Employee ID","Status","Venue","Time Start",
"Duration","Date"}
);
table.setRowCount(0); //this is to clear the jTable after each click
try {
File file = new File("info.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
Object[] Lines = br.lines().toArray();
for(int i = 1; i < Lines.length; i++)
{
String line = Lines[i].toString().trim();
String[] dataRow = line.split(",");
table.addRow(dataRow);
}
} catch (Exception ex) {
Logger.getLogger(TextFileDataToJTable.class.getName()).log(Level.SEVERE, null, ex);
}
As of now, I have left the Book and Cancel Button's code blank. I have been pulling my hair out trying to scour the entire internet trying to find a solution. If someone could help me I would be so grateful
I have an arraylist that I want to verify with the rows of a csv file.
Everytime the arraylist has different elements as I am creating that arraylist dynamically and adding element text from my webpage. But I wanna access the csv data horizontally i.e. everytime I want to veryfy the row data with my arraylist. Please give me a solution for this.
You can try doing something like this:
try (BufferedReader br = new BufferedReader (new FileReader (path))){
Stream<String> lines = br.lines();
String[] linesArray = lines.toArray();
if (index < linesArray.length) {
String line = linesArray[index];
//then you can do your verification
}
}
I am new to Java
I created a conversion software for metric units and now I want to create new window for logging the output of converted units from one Window text areas into one text area in another window Picture of the application
Both Windows are one application
What code would I need to put in there to display this in another window text area
JButton btnConvert = new JButton("Convert");
btnConvert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double numCM,sumCM;
double numKM,sumKM;
double numMIL,sumMIL;
try {
//startCM//
numCM = Double.parseDouble(textFieldenter.getText());
sumCM = numCM*100;
textFieldcm.setText(Double.toString(sumCM));
//endCM//
//startKILOMETERS//
numKM = Double.parseDouble(textFieldenter.getText());
sumKM = numKM*0.001;
textFieldkm.setText(Double.toString(sumKM));
//endKILOMETERS//
//startMILES//
numMIL = Double.parseDouble(textFieldenter.getText());
sumMIL = numMIL*0.000621;
textFieldmil.setText(Double.toString(sumMIL));
//endMILES//
}
catch (Exception e1) {
JOptionPane.showInternalMessageDialog(btnConvert, "Value etered is incorrect");
}
}
});
You can use the method JTextField.getText() over your JTextFields and store its value into a String variable, then pass it to the JTextArea using the method append(String str) and put a line break at the end with /n
Read the API for these classes to learn more about its methods and how to use them Java API
It would be something like this
String record = "";
record = textFieldcm.getText()+" "+textFieldkm.getText()+" "+textFieldmil.getText();
JTextArea.append(record+"\n");
I have a jTextArea that is filled with information that the program gives out, however, when i call the .print(); method, it prints 2 blank pages, it displays the popup and everything as other information shows on in the internet, I assume it does "see" the data in the text area since it wants to print two pages, but the problem is the pages just come out blank, any ideas what i'm doing wrong?
try {
boolean complete = txaMainOutput.print();
if(complete)
{
JOptionPane.showMessageDialog(null, "Done Printing", "Information", JOptionPane.INFORMATION_MESSAGE);
} else
{
JOptionPane.showMessageDialog(null, "Printing", "Printer", JOptionPane.ERROR_MESSAGE);
}
} catch (PrinterException ex) {
JOptionPane.showMessageDialog(null, "An Error has occured, looks like we could not print");
}
https://gyazo.com/376958811a5fd9c5356843d8bf83c36f
After Playing around with the code, I found that creating a new JTextArea, saving all the Origianal TextArea data to a string then setting the new TextArea to that string, and then printing it will resolve the problem of blank pages.
String YourString = "Line 1 \nLine 2 \nLine 3" //define and set contents of your string - remember about formating with \n if you want to have it split on lines
JTextArea YourTextArea = new JTextArea(); //define new Swing JtextArea
YourTextArea.setLineWrap(true); //set line wrap for YourTextArea - this will prevent too long lines to be cut - they will be wrapaed to next line
YourTextArea.append(YourString); //append YourString to YourTextArea
YourTextArea.print(); //this will display print dialog that will lead you to print contents of YourTextArea so in efect contents of YourString
I am making a sort of Macro recorder/player
I have done the player part with utils such as java.awt.Robot() which emulates basic human mouse/keyboard output commands, reading an XML file.
I am stuck at the part where I have to record that XML file.
I have no idea of which Class I can use to do the opposite of Robot() If yo have any FemaleRobot() for me I would be very happy :D
The only thing in this direction I have so far is :
while (true) {
Point pos = MouseInfo.getPointerInfo().getLocation();
System.out.println(pos.x+" x "+pos.y);
}
which is not much and not really what I want ^_^, I don't know how to use a Mouse/KeyListener since it would require a Component. If it is the only way, what Compoment do I use as I don't want any graphical java implementation? Should I create a phony Component anyway? Which one?
e.g. I want my recorder to write in the XML how I click on my ubuntu desktop or press enter on firefox.
I guess it's clear, if not I will be checking the answers a lot. Have a nice day and thanks for reading this.
Try jnativehook lib:
http://code.google.com/p/jnativehook/wiki/examples
It is very easy to use and may meet your needs.
I regret to inform you it is completely impossible to monitor mouse clicks and keystrokes outside of your form. Java events simply do not fire outside the scope of your form.
The reason java behaves this way is to eliminate the possibility of java based malware attempting to steal sensitive data.
You can find examples of mouse listeners here: http://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html
to Write to a file you can do something like:
FileWriter fileStream = new FileWriter("myfile.extention");
BufferedWriter out = new BufferedWriter(fileStream);
out.write("pos.x+" x "+pos.y");
If you are doing this:
while (true)
{
Point pos = MouseInfo.getPointerInfo().getLocation();
System.out.println(pos.x+" x "+pos.y);
}
You will want to add a Thread.Sleep call in the loop.
Then you can read the file back by doing:
FileInputStream fileStream = new FileInputStream("myfile.extention");
DataInputStream in = new DataInputStream(fileStream);
BufferedReader br = new BufferedReader(new InputStreamReader(in))
String position = br.readLine()
Then you can parse that string to get the values.
So you might do something like:
FileWriter filewrite = new FileWriter("myfile.txt");
BufferedWriter out = new BufferedWriter(filewrite);
while (Recording)
{
Point pos = MouseInfo.getPointerInfo().getLocation();
out.write(pos.x + " " + pos.y);
Thread.sleep(50);
}
FileInputStream fileStream = new FileInputStream("myfile.txt");
DataInputStream in = new DataInputStream(fileStream);
BufferedReader br = new BufferedReader(new InputStreamReader(in))
String position;
while(position = br.readLine() != null)
{
String[] positions = position.split(" ");
int x = Integer.parseInt(positions[0]);
int y = Integer.parseInt(positions[1]);
}
You will have to use the mouse events to write click positions to the file.
You can first get the resolution of screen.Second thing make a frame that is a size of your screen and make its transparency to 0% .When you click to a position on a screen put down your jframe and use mouse robot to click a position.You can get the coordinates of the entire screen.This way you can record the mouse clicks,But the problem comes is when you need to type in the text