How to print the contents of a file to a GUI - java

For my program one of the major things we have to do is print the contents of a .csv file to a GUI. I have figured out the GUI and sorting methods however we are having trouble figuring out how to actually print the file to the GUI. Any ideas on how to do this? Here is the code for the GUI:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.*;
public class FirstGUI2 {
private static JTextArea textAreaMon;
private static JTextArea textAreaTue;
private static JTextArea textAreaWed;
private static JTextArea textAreaThu;
private static JTextArea textAreaFri;
private static JTextArea description;
private static String gE1 = "Group Exam 1";
private static String gE2 = "Group Exam 2";
private static String gE3 = "Group Exam 3";
private static String gE4 = "Group Exam 4";
private static String gE5 = "Group Exam 5";
private static String gE6 = "Group Exam 6";
private static String gE7 = "Group Exam 7";
private static String gE8 = "Group Exam 8";
private static String gE9 = "Group Exam 9";
private Container pane;
final static boolean fill = true;
final static boolean weightX = true;
final static boolean RIGHT_TO_LEFT = false;
public static String mon = "";
public static String tues = "";
public static String wed = "";
public static String thu = "";
public static String fri = "";
public static void addComponents(Container pane) {
if (RIGHT_TO_LEFT)
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
JButton button;
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.fill = GridBagConstraints.HORIZONTAL;
button = new JButton("Open File");
c.gridx = 1;
c.gridy = 1;
c.insets = new Insets(5, 5, 5, 5);
pane.add(button, c);
textAreaMon = new JTextArea(mon);
//textAreaMon.append(mon.substring(0));
textAreaMon.setLineWrap(true);
textAreaMon.setEditable(false);
c.gridx = 1;
c.gridy = 2;
pane.add(textAreaMon, c);
textAreaTue = new JTextArea(tues);
textAreaTue.setLineWrap(true);
textAreaTue.setEditable(false);
c.gridx = 1;
c.gridy = 3;
pane.add(textAreaTue, c);
textAreaWed = new JTextArea(wed);
textAreaWed.setLineWrap(true);
textAreaWed.setEditable(false);
c.gridx = 1;
c.gridy = 4;
pane.add(textAreaWed, c);
textAreaThu = new JTextArea(thu);
textAreaThu.setLineWrap(true);
textAreaThu.setEditable(false);
c.gridx = 1;
c.gridy = 5;
pane.add(textAreaThu, c);
textAreaFri = new JTextArea(fri);
textAreaFri.setLineWrap(true);
textAreaFri.setEditable(false);
c.gridx = 1;
c.gridy = 6;
pane.add(textAreaFri, c);
description = new JTextArea(
"Click the open button in order to select and import your .csv file. Your scehdule and times will be displayed in the schedule below.");
description.setEditable(false);
c.gridx = 1;
c.gridy = 0;
pane.add(description, c);
// attaching the file opener to the open file button
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
new InterfacePanel();
}
});
}
//creates the frame and showing the GUI to the user
public static void makeGUI(){
JFrame frame = new JFrame("Final Exam Scheduler");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addComponents(frame.getContentPane());
frame.pack();
frame.setVisible(true);
}
public static void printToGUI(){
//JText Fields
//textAreaMon
mon= "Monday: \n \n 8:00 - 10:00:\t Group Exam 1 \n 10:15-12:15:\t Group Exam 2 \n 12:45 - 2:45:\t";
while(!ArrayListsForClasses.time1.isEmpty()){
for(int i = 0; i < ArrayListsForClasses.time1.size(); i++){
mon += ArrayListsForClasses.time1.get(i);
mon += ", ";
}
}
mon += "\n 3:00 - 5:00:\t";
while(!ArrayListsForClasses.time2.isEmpty()){
for(int i = 0; i < ArrayListsForClasses.time2.size(); i++){
mon += ArrayListsForClasses.time2.get(i);
mon += ", ";
}
}
mon += "\n 5:30 - 7:30:\t Group Exam 3 \n \n 7:45 - 9:45:\t";
while(!ArrayListsForClasses.time3.isEmpty()){
for(int i = 0; i < ArrayListsForClasses.time3.size(); i++){
mon += ArrayListsForClasses.time3.get(i);
mon += ", ";
}
}
mon+= "\n \n";
// textAreaTues
tues = "Tuesday: \n \n 8:00 - 10:00: \t";
while (!ArrayListsForClasses.time4.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time4.size(); i++) {
tues += ArrayListsForClasses.time4.get(i);
tues += ", ";
}
}
tues += "\n 10:15 - 12:15:\t Group Exam 4 \n \n 12:45 - 2:45:\t ";
while (!ArrayListsForClasses.time5.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time5.size(); i++) {
tues += ArrayListsForClasses.time5.get(i);
tues += ", ";
}
}
tues += "\n 3:00 - 5:00:\t ";
while (!ArrayListsForClasses.time6.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time6.size(); i++) {
tues += ArrayListsForClasses.time6.get(i);
tues += ", ";
}
}
tues += "\n 5:30 - 7:30:\t ";
while (!ArrayListsForClasses.time7.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time7.size(); i++) {
tues += ArrayListsForClasses.time7.get(i);
tues += ", ";
}
}
tues += "\n 7:45 - 9:45:\t ";
while (!ArrayListsForClasses.time8.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time8.size(); i++) {
tues += ArrayListsForClasses.time8.get(i);
tues += ", ";
}
}
//TextAreaWed
wed = "Wednesday \n \n 8:00 - 10:00:\t";
while(!ArrayListsForClasses.time9.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time9.size(); i++) {
wed += ArrayListsForClasses.time9.get(i);
wed += ", ";
}
}
wed += "\n 10:15-12:15:\t";
while(!ArrayListsForClasses.time10.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time10.size(); i++) {
wed += ArrayListsForClasses.time10.get(i);
wed += ", ";
}
}
wed += "\n 12:45 - 2:45 :\t Group Exam 5 \n 3:00 - 5:00:\t";
while(!ArrayListsForClasses.time11.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time11.size(); i++) {
wed += ArrayListsForClasses.time11.get(i);
wed += ", ";
}
}
wed += "\n 5:30 - 7:30:\t";
while(!ArrayListsForClasses.time12.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time12.size(); i++) {
wed += ArrayListsForClasses.time12.get(i);
wed += ", ";
}
}
wed += "\n 7:45 - 9:45:\t";
while(!ArrayListsForClasses.time13.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time13.size(); i++) {
wed += ArrayListsForClasses.time13.get(i);
wed += ", ";
}
}
//TextAreaThurs
thu = "Thursday \n \n 8:00 - 10:00:\t";
while(!ArrayListsForClasses.time14.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time14.size(); i++) {
thu += ArrayListsForClasses.time14.get(i);
thu += ", ";
}
}
thu += "\n 10:15-12:15 :\t Group Exam 6 \n 12:45 - 2:45:\t";
while(!ArrayListsForClasses.time15.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time15.size(); i++) {
thu += ArrayListsForClasses.time15.get(i);
thu += ", ";
}
}
thu += "\n 3:00 - 5:00:\t";
while(!ArrayListsForClasses.time16.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time16.size(); i++) {
thu += ArrayListsForClasses.time16.get(i);
thu += ", ";
}
}
thu += "\n 5:30 - 7:30:\t Group Exam 7 \n 7:45 - 9:45:\t";
while(!ArrayListsForClasses.time17.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time17.size(); i++) {
thu += ArrayListsForClasses.time17.get(i);
thu += ", ";
}
}
//TextAreaFri
fri = "Friday \n \n 8:00 - 10:00:\t Group Exam 8 \n 10:15-12:15:\t";
while(!ArrayListsForClasses.time18.isEmpty()) {
for (int i = 0; i < ArrayListsForClasses.time18.size(); i++) {
fri += ArrayListsForClasses.time18.get(i);
fri += ", ";
}
}
fri += "\n 12:45 - 2:45:\t Group Exam 9";
}
public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable(){
public void run(){
makeGUI();
}
});
}
}

I have figured out the GUI
Actaully, the design of your code is all wrong. You should NOT be using static variables and static methods. In general, the only static method should be the method to create the GUI. All other application code should be defined in a class so any method can access the variables of your class.
we have to do is print the contents of a .csv file to a GUI
To me the word "print" means to use a printer to print something to a piece of paper. I'm guessing you really want to display the contents of a file in a GUI.
Below is a simple example that shows how to read and write a file. The contents of the file will be displayed in a text area. Note you need to write to the file first before you can read the file.
I suggest you start with this basic code and rewrite your class so you can get rid of all the static variables and methods:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.*;
class TextAreaLoad extends JPanel
{
private JTextArea edit;
public TextAreaLoad()
{
setLayout( new BorderLayout() );
edit = new JTextArea(30, 60);
add(new JScrollPane(edit), BorderLayout.NORTH);
JButton read = new JButton("Read TextAreaLoad.txt");
read.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
FileReader reader = new FileReader( "TextAreaLoad.txt" );
BufferedReader br = new BufferedReader(reader);
edit.read( br, null );
br.close();
edit.requestFocus();
}
catch(Exception e2) { System.out.println(e2); }
}
});
add(read, BorderLayout.LINE_START);
JButton write = new JButton("Write TextAreaLoad.txt");
write.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
FileWriter writer = new FileWriter( "TextAreaLoad.txt" );
BufferedWriter bw = new BufferedWriter( writer );
edit.write( bw );
bw.close();
edit.setText("");
edit.requestFocus();
}
catch(Exception e2) { System.out.println(e2); }
}
});
add(write, BorderLayout.LINE_END);
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("TextArea Load");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TextAreaLoad());
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}

You have yet to set the String value with the imported data to the TextAreas. What you did do, was give the JTextAreas a value equal to the initial value of strings like mon, like so:
textAreaMon = new JTextArea(mon);
However, that does not mean textAreaMon will be updated if mon is updated; it simply matters when the view is initialized.
Add method calls to your file-import button listener that contain methods that do something like this
textAreaMon.setText(mon);
This should properly update the GUI every time a file is imported.

I may be wrong, but inside the actionPerformed() method, you should write the following code
String myCsvFile = "mySCVFile.csv"; //you can modify this based on where the file is located
BufferedReader br = null;
String line = "";
try {
br = new BufferedReader(new FileReader(myCsvFile));
while ((line = br.readLine()) != null) {
String[] columns = line.split(","); //you may do extra tweeks in here based on how you want to display the data
for(int x=0; x <columns.length(); x++){
description.append(columns[x]); //I guess this is the textarea you want to display the content of the CSV file
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Related

Why doesn't my find method work here even with all the values saved on the array?

I am fairly new to programming and I cant seem to find the problem in the area where I make the program search for the specific key term tho it's saved in the array.
here is the code where I add the details of the customer:
private void addCustomerToSeat(String[] seatBooking, String[] customerName, String[] seatBookingAndCustomerName) {
Button[] seat = new Button[(SEATING_CAPACITY + 1)];
Button selectSeat = new Button(" Click to Book Seats ");
selectSeat.setLayoutX(320);
selectSeat.setLayoutY(512);
selectSeat.setOnAction(event -> {
window.setScene(scene2);
});
Label header = new Label("TRAIN BOOKING SYSTEM");
header.setLayoutX(250);
header.setLayoutY(30);
header.setStyle("-fx-font-size: 25px;");
Label clientName = new Label("Enter Customer Name: ");
clientName.setLayoutX(225);
clientName.setLayoutY(150);
clientName.setStyle("-fx-font-size: 16px;");
TextField cusName = new TextField();
cusName.setLayoutX(397);
cusName.setLayoutY(150);
Label destination = new Label("Choose destination: ");
destination.setLayoutX(225);
destination.setLayoutY(200);
destination.setStyle("-fx-font-size:16px;");
String [] destinations = {"Colombo to Badulla", "Badulla to Colombo"};
ComboBox Destination = new ComboBox(FXCollections.observableArrayList(destinations));
Destination.setLayoutX(397);
Destination.setLayoutY(200);
Label date = new Label("Select date:");
date.setLayoutY(275);
date.setLayoutX(225);
date.setStyle("-fx-font-size:16px;");
DatePicker datePicker = new DatePicker();
LocalDate now = LocalDate.now();
datePicker.setValue(now);
datePicker.setLayoutX(397);
datePicker.setLayoutY(275);
AnchorPane layout1 = new AnchorPane();
layout1.setStyle("-fx-background-color:#5a89a3; ");
layout1.getChildren().addAll(Destination,destination,selectSeat,clientName,cusName,header,date,datePicker);
scene1 = new Scene(layout1,800,600);
window.setTitle("Train Booking System");
window.setScene(scene1);
window.show();
Label header1 = new Label("TRAIN BOOKING SYSTEM");
header1.setLayoutX(250);
header1.setLayoutY(30);
header1.setStyle("-fx-font-size: 25px;");
Button submit = new Button("Submit");
submit.setLayoutX(640);
submit.setLayoutY(480);
Button exit = new Button("Exit");
exit.setLayoutX(710);
exit.setLayoutY(480);
exit.setOnAction(event -> {
window.close();
displayMenu(seatBooking,customerName,seatBookingAndCustomerName);
});
Label greenSeat = new Label("Unbooked Seat");
greenSeat.setLayoutY(160);
greenSeat.setLayoutX(590);
greenSeat.setStyle("-fx-font-size:14px;");
Button unbooked = new Button(" ");
unbooked.setLayoutY(160);
unbooked.setLayoutX(560);
unbooked.setStyle("-fx-background-color:green;");
Label redSeat = new Label("Booked Seat");
redSeat.setLayoutX(590);
redSeat.setLayoutY(200);
redSeat.setStyle("-fx-font-size:14px;");
Button booked = new Button(" ");
booked.setLayoutX(560);
booked.setLayoutY(200);
booked.setStyle("-fx-background-color:red;");
GridPane gridPane = new GridPane();
int columnIndex = 0;
int rowIndex = 0;
int rowIndexes = 0;
int[] reservedSeats = new int[1];
String seatNumber;
for (int i = 1; i < (SEATING_CAPACITY + 1); i++) {
if (i <= 9) {
seatNumber = "0" + (i);
} else {
seatNumber = "" + (i);
}
seat[i] = new Button(seatNumber);
gridPane.add(seat[i], columnIndex, rowIndex);
columnIndex++;
rowIndexes++;
if (rowIndexes == 4) {
columnIndex = 0;
rowIndexes = 0;
rowIndex++;
}
}
for (int f = 1; f < (SEATING_CAPACITY + 1); f++) {
if (seatBooking[f].equals("Empty")) {
seat[f].setStyle("-fx-background-color: green;");
}
if (seatBooking[f].equals("booked")) {
seat[f].setStyle("-fx-background-color: red");
}
}
List<Integer> bookedCurrent = new ArrayList<>();
for (int f = 1; f < (SEATING_CAPACITY + 1); f++) {
int finalF = f;
seat[f].setOnAction(event -> {
seat[finalF].setStyle("-fx-background-color: red");
seatBooking[finalF] = "booked";
bookedCurrent.add(finalF);
});
submit.setOnAction(event -> {
String personName = cusName.getText();
personName = personName.toLowerCase();
window.close();
for ( int loopSeatArray = 1; loopSeatArray< (SEATING_CAPACITY + 1); loopSeatArray++) {
if (loopSeatArray == reservedSeats[0]) {
seatBooking[loopSeatArray] = "Booked";
customerName[loopSeatArray] = personName;
}
seatBookingAndCustomerName[loopSeatArray] = seatBooking[loopSeatArray];
}
for (int total = 43; total < (SEATING_CAPACITY + 1); total++){
seatBookingAndCustomerName[total]= customerName[total-42]; }
displayMenu(seatBooking, customerName, seatBookingAndCustomerName);
});
}
gridPane.setLayoutX(160);
gridPane.setLayoutY(80);
gridPane.setHgap(20);
gridPane.setVgap(5);
AnchorPane layout2 = new AnchorPane();
layout2.setStyle("-fx-background-color:#5a89a3; ");
layout2.getChildren().addAll(gridPane,submit,exit,header1,greenSeat,unbooked,redSeat,booked);
scene2 = new Scene(layout2,800,600);
window.setTitle("Train Booking System");
window.show();
window.setOnCloseRequest(event -> {
window.close();
displayMenu(seatBooking,customerName,seatBookingAndCustomerName);
});
}
and here is the part of the code where I prompt the user for the name and find the location of given name:
private void findCustomerSeats(String[] seatBooking, String[] customerName, String[] seatBookingAndCustomerName) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter customer name: ");
String name = input.nextLine();
boolean flag = false;
for (int i = 1; i < (SEATING_CAPACITY + 1); i++){
if (name.toLowerCase().equals(customerName[i])){
System.out.println("Seats booked are: " + seatBooking);
flag = true;
}
}
if (flag !=true){
System.out.println(name + " has not reserved a seat");
}
displayMenu(seatBooking,customerName,seatBookingAndCustomerName);
}
when the above code is run, and when I input the name, it plain out does not work.
One potential issue, your for loop is starting at index 1, I would begin by using something like this:
for (int idx = 0; idx < customerName.length; idx++) {
//This way you will not check an index of your array that does not exist
//which could cause a NullPointerException
//Additionally, this is useful if you want to grow your customerName array
}
Another useful tip, that I use all the time. Try printing out more information and see if you can spot the issue. This might seem trivial but I have found it extremely helpful. For example:
System.out.println("Inputted Name: " + name);
for (int idx = 0; idx < customerName.length; idx++) {
System.out.println("Does " + name.toLowerCase() + " = " + customerName[idx] + " ?");
}

JFrame Printing out not as expected. if loop trouble

Sorry for the long code, didn't want to leave anything out.
Little explanation, I'm just trying to do a way where the user inputs a date to check there history between the two dates now i have it working to an extent, it reads of a text document, which for each transactions has 8 lines that need to be printed if the date is between the dates
the Example document is structured as below:
######## START OF TRANSACTION ########
Name: name
DATE: 14/05/2015
Ammount: 100
Address: address
Card Number: 123312
ExpiryDate: 123312
######## END OF TRANSACTION ########
######## START OF TRANSACTION ########
Name: name
DATE: 19/05/2015
Ammount: 100
Address: address
Card Number: 123312
ExpiryDate: 123312
######## END OF TRANSACTION ########
if i input the date 15-05-2015 to 16-05-2015
i get:
######## START OF TRANSACTION ########
Name: name
DATE: 14/05/2015
Ammount: 100
Address: address
Card Number: 123312
ExpiryDate: 123312
null######## END OF TRANSACTION ########
######## START OF TRANSACTION ########
Name: name
DATE: 19/05/2015
Ammount: 105
Address: address
Card Number: 123312
null
1: what is with the NULL values guessing my loop
2: why does it print the 19. even if i have the 16th in their it still prints the 19th....please help, I've been on this for awhile
import javax.swing.*;
import java.awt.Dialog.ModalityType;
import java.awt.event.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class TopUpHistoryScreen extends JDialog {
private JPanel mainPanel;
private JTextArea historyScreen;
public TopUpHistoryScreen()
{
setPanels();
setModalityType(ModalityType.APPLICATION_MODAL);
setSize(400, 450);
setVisible(true);
}
public String Reader() {
try {
ArrayList<String> Trains = new ArrayList<String>();
int count = 0;
String testing = "";
File file = new File("TopUp.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null)
{
stringBuffer.append(line);
count += count;
Trains.add(line + "\n");
stringBuffer.append("\n");
testing += line + "\n";
//field.setText(line);
}
fileReader.close();
return testing;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public String checkDates(String startDate, String endDate) {
try {
ArrayList<String> Lines = new ArrayList<String>();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
int count = 0;
int check = 0;
String[] lineArray = new String[8];
String DateSelected = "";
String testing="";
File file = new File("TopUp.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null)
{
lineArray[count] = line+"\n";
if (count < 8){
count ++;
}
if (count == 7){
if(check == 1){
testing += lineArray[0];
testing += lineArray[1];
testing += lineArray[2];
testing += lineArray[3];
testing += lineArray[4];
testing += lineArray[5];
testing += lineArray[6];
testing += lineArray[7];
check = 0;
}
}
if (count == 7){
count = 0;
check = 0;
lineArray = new String[8];
}
if (line.contains("DATE")){
try {
DateSelected = line.replace("DATE: ", "");
Date MainDate = sdf.parse(DateSelected);
Date SDate = sdf.parse(startDate);
Date EDate = sdf.parse(endDate);
if(MainDate.compareTo(SDate)>=0 || MainDate.compareTo(EDate)<=0 ){
//is after Sdate and before eDate
check = 1;
}
// if(MainDate.compareTo(SDate)<0){ //is Before SDate
//
// }
// if(MainDate.compareTo(SDate)==0){ //is equal to mainDate
//
// }
} catch (ParseException e) {
//e.printStackTrace();
}
}
stringBuffer.append(line);
Lines.add(line + "\n");
stringBuffer.append("\n");
}
fileReader.close();
return testing;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void setPanels()
{
mainPanel = new JPanel(new GridLayout(0, 2));
JPanel containerPanel = new JPanel(new GridLayout(0, 1));
JPanel lowerPanel = new JPanel(new FlowLayout());
//JButton apply = new JButton("Select data area");
JButton exit = new JButton("Okay!");
exit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
dispose();
}
});
JButton checkDate = new JButton("check dates");
JLabel START = new JLabel("START DATE!");
JLabel startDay = new JLabel("Day:");
JTextField sDay = new JTextField();
JLabel startMonth = new JLabel("Month:");
JTextField sMonth = new JTextField();
JLabel startYear = new JLabel("Year:");
JTextField sYear = new JTextField("2015");
JLabel END = new JLabel("END DATE!");
JLabel endDay = new JLabel("Day:");
JTextField eDay = new JTextField();
JLabel endMonth = new JLabel("Month:");
JTextField eMonth = new JTextField();
JLabel endYear = new JLabel("Year:");
JTextField eYear = new JTextField("2015");
//JTextField Data = new JTextField();
//JTextField touchOnTimeFieldminute = new JTextField();
historyScreen = new JTextArea(10,20);
JScrollPane scrolll = new JScrollPane(historyScreen);
//mainPanel.add(SelectData);
//mainPanel.add(SelectData);
// mainPanel.add(new JLabel());
mainPanel.add(new JLabel());
mainPanel.add(START);
mainPanel.add(startDay);
mainPanel.add(sDay);
mainPanel.add(startMonth);
mainPanel.add(sMonth);
mainPanel.add(startYear);
mainPanel.add(sYear);
mainPanel.add(new JLabel());
mainPanel.add(END);
mainPanel.add(endDay);
mainPanel.add(eDay);
mainPanel.add(endMonth);
mainPanel.add(eMonth);
mainPanel.add(endYear);
mainPanel.add(eYear);
mainPanel.add(new JLabel());
mainPanel.add(checkDate);
lowerPanel.add(scrolll);
lowerPanel.add(exit);
containerPanel.add(mainPanel);
containerPanel.add(lowerPanel);
add(containerPanel);
checkDate.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
String startday = sDay.getText();
String startmonth = sMonth.getText();
String startyear = sYear.getText();
String endday = eDay.getText();
String endmonth = eMonth.getText();
String endyear = eYear.getText();
String startDate = (startday+"/"+startmonth+"/"+startyear);
String endDate = (endday+"/"+endmonth+"/"+endyear);
String AnswerDates = checkDates(startDate,endDate);
historyScreen.setText(AnswerDates);
}
});
}
}
sorry guys i got it this time, just incase someone looks at this later hahaha, it was because my for loop was ending at 7 instead of 8 and was saving no value into array [7], and also because the date check was doing || instead of && below is the updated class
public String checkDates(String startDate, String endDate) {
try {
ArrayList<String> Lines = new ArrayList<String>();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
int count = 0;
int check = 0;
String[] lineArray = new String[8];
String DateSelected = "";
String testing="";
File file = new File("TopUp.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null)
{
lineArray[count] = line+"\n";
if (count < 8){
count ++;
}
if (count == 8){
if(check == 1){
testing += lineArray[0];
testing += lineArray[1];
testing += lineArray[2];
testing += lineArray[3];
testing += lineArray[4];
testing += lineArray[5];
testing += lineArray[6];
testing += lineArray[7];
check = 0;
}
}
if (count == 8){
count = 0;
check = 0;
lineArray = new String[8];
}
if (line.contains("DATE")){
try {
DateSelected = line.replace("DATE: ", "");
Date MainDate = sdf.parse(DateSelected);
Date SDate = sdf.parse(startDate);
Date EDate = sdf.parse(endDate);
if(MainDate.compareTo(SDate)>=0 && MainDate.compareTo(EDate)<=0 ){
//is after Sdate and before eDate
check = 1;
}
// if(MainDate.compareTo(SDate)<0){ //is Before SDate
//
// }
// if(MainDate.compareTo(SDate)==0){ //is equal to mainDate
//
//
}
} catch (ParseException e) {
//e.printStackTrace();
}
}
stringBuffer.append(line);
Lines.add(line + "\n");
stringBuffer.append("\n");
}
fileReader.close();
return testing;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

how to put the data into a new column in dialog box

I am trying to put the output of formattedText1 into a new column.
Currently formatted text and formattedText1 appear in one continuous list. I tried putting a +" "+ between formattedText and formattedText1 but that doesnt do the trick, I would appreciate some help please
null, (formattedText) + (formattedText1), "Cashout Prices",
Full code below
package simpledialogbox;
import javax.swing.JOptionPane;
import java.io.IOException;
import java.util.logging.*;
import org.jsoup.*;
import org.jsoup.nodes.*;
import org.jsoup.select.*;
public class SimpleDialogBox {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try {
String url = "http://bmreports.com/bsp/additional/soapfunctions.php?element=SYSPRICE&dT=2014-10-03";
Document doc = Jsoup.connect(url).get();
Elements SSPparagraphs;
Elements SBPparagraphs;
SSPparagraphs = doc.select("SSP");
SBPparagraphs = doc.select("SBP");
String[] numbers = SSPparagraphs.text().toString().split(" ");
String[] numbers1 = SBPparagraphs.text().toString().split(" ");
String formattedText = new String("");
String formattedText1 = new String("");
for (int x = 0; x < numbers.length; x++)
{
formattedText += numbers[x] + "\n";
}
for (int x = 0; x < numbers1.length; x++)
{
formattedText1 += numbers1[x] + "\n";
}
JOptionPane.showMessageDialog(
null, (formattedText) + (formattedText1), "Cashout Prices", JOptionPane.PLAIN_MESSAGE);
System.exit(0);
}
catch (IOException ex) {
Logger.getLogger(SimpleDialogBox.class.getName())
.log(Level.SEVERE, null, ex);
}
}
}
You can use HTML
(I revised this to account for your two columns)
(NOTE: you'd get a better result with a JScrollPane in a JFrame)
try this:
String[] numbers = SSPparagraphs.text().toString().split(" ");
String[] numbers1 = SBPparagraphs.text().toString().split(" ");
//generate table and column heads
String formattedText = new String("<html><table><tbody>");
formattedText += "<tr><th>SSP</th><th>SBP</th></tr>";
//populate table with data in two columns
//will account for differing amounts of data between SBP and SSP
int x = 0;
while (x < numbers.length || x < numbers1.length)
{
formattedText += "<tr><td>";
if (x < numbers.length)
{
formattedText += numbers[x];
}
else
{
formattedText += " ";
}
formattedText += "</td><td>";
if (x < numbers1.length)
{
formattedText += numbers1[x];
}
else
{
formattedText += " ";
}
formattedText += "</td></tr>";
x++;
}
formattedText += "<tbody></table>";

reading desired data from file but saving the whole file data

I have made a GUI using swing, i read data from a text file to the jtable,
the text file has 6 columns and 5 rows,the 3 row has values 0,0.0,0,0,0,0.so i want to display
values in the JTable till it encounters 0.but to save the full text file while saving which means values of 5 rows.here is my code:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class Bb extends JFrame
{
private JTable table;
private DefaultTableModel model;
#SuppressWarnings("unchecked")
public Bb()
{
String aLine ;
Vector columnNames = new Vector();
Vector data = new Vector();
try
{
FileInputStream fin = new FileInputStream("Bbb.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fin));
StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
while( st1.hasMoreTokens())
{
columnNames.addElement(st1.nextToken());
}
while ((aLine = br.readLine()) != null )
{
StringTokenizer st2 = new StringTokenizer(aLine, " ");
Vector row = new Vector();
while(st2.hasMoreTokens())
{
row.addElement(st2.nextToken());
}
data.addElement( row );
}
br.close();
}
catch (Exception e)
{
e.printStackTrace();
}
model = new DefaultTableModel(data, columnNames);
table = new JTable(model);
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
JPanel buttonPanel = new JPanel();
getContentPane().add( buttonPanel, BorderLayout.SOUTH );
JButton button2 = new JButton( "SAVE TABLE" );
buttonPanel.add( button2 );
button2.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if ( table.isEditing() )
{
int row = table.getEditingRow();
int col = table.getEditingColumn();
table.getCellEditor(row, col).stopCellEditing();
}
int rows = table.getRowCount();
int columns = table.getColumnCount();
try {
StringBuffer Con = new StringBuffer();
for (int i = 0; i < table.getRowCount(); i++)
{
for (int j = 0; j < table.getColumnCount(); j++)
{
Object Value = table.getValueAt(i, j);
Con.append(" ");
Con.append(Value);
}
Con.append("\r\n");
}
FileWriter fileWriter = new FileWriter(new File("cc.txt"));
fileWriter.write(Con.toString());
fileWriter.flush();
fileWriter.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
public static void main(String[] args)
{
Bb frame = new Bb();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}
}
and the text file:
1 2 6 0.002 0.00 2
2 5 5 0.005 0.02 4
0 0 0 0.000 0.00 0
4 8 9 0.089 0.88 7
5 5 4 0.654 0.87 9
I was able to understand what you want
For first part that you just wanted to show your data in your JTable till you encounter 0
code:
while ((aLine = br.readLine()) != null) {
String[] sp = aLine.split(" ");
if (sp[0].equals("0")) {
break;
}
StringTokenizer st2 = new StringTokenizer(aLine, " ");
Vector row = new Vector();
while (st2.hasMoreTokens()) {
String s = st2.nextToken();
row.addElement(s);
}
data.addElement(row);
}
Explanation: when you read each line, split it, so if the first element of each splitted line is zero, you come out of the loop and do not show any other values inside the loop.
For saving all your data from first file to second file, you should copy them from first file to second file because your JTable will not have enough info to help your purpose in this matter.
Note: I do not understand why you want to do this but you can accomplish that in following way
Code:
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (table.isEditing()) {
int row = table.getEditingRow();
int col = table.getEditingColumn();
table.getCellEditor(row, col).stopCellEditing();
}
int rows = table.getRowCount();
int columns = table.getColumnCount();
try {
String st = "";
FileInputStream fin = new FileInputStream("C:\\Users\\J Urguby"
+ "\\Documents\\NetBeansProjects\\Bb\\src\\bb\\Bbb.txt");
Scanner input = new Scanner(fin).useDelimiter("\\A");
while (input.hasNext()) {
st = input.next();
System.out.println("st is " + st);
}
FileWriter fileWriter = new FileWriter(new File("C:\\Users\\J Urguby"
+ "\\Documents\\NetBeansProjects\\Bb\\src\\bb\\cc.txt"));
fileWriter.write(st);
fileWriter.flush();
fileWriter.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
Explanation: you read the whole file with Scanner trick and write it down into a second file.
Source: https://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner.html
Based on what the OP requested
Code:
public Bb() {
String aLine;
Vector columnNames = new Vector();
Vector data = new Vector();
boolean found = false;
StringBuilder temp = new StringBuilder();
/*Using try catch block with resources Java 7
Read about it
*/
try (FileInputStream fin = new FileInputStream("C:\\Users\\8888"
+ "\\Documents\\NetBeansProjects\\Bb\\src\\bb\\Bbb.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fin))) {
StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
//the first line of the txt file fill colum names
while (st1.hasMoreTokens()) {
String s = st1.nextToken();
columnNames.addElement(s);
}
while ((aLine = br.readLine()) != null) {
String[] sp = aLine.split(" ");
if (sp[0].equals("0") && !found) {
found = true;
} else if (found) {
temp.append(aLine).append("\r\n");
} else if (!sp[0].equals("0") && !found) {
StringTokenizer st2 = new StringTokenizer(aLine, " ");
Vector row = new Vector();
while (st2.hasMoreTokens()) {
String s = st2.nextToken();
row.addElement(s);
}
data.addElement(row);
}
}
} catch (IOException e) {
e.printStackTrace();
}
model = new DefaultTableModel(data, columnNames);
table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
JPanel buttonPanel = new JPanel();
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
JButton button2 = new JButton("SAVE TABLE");
buttonPanel.add(button2);
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (table.isEditing()) {
int row = table.getEditingRow();
int col = table.getEditingColumn();
table.getCellEditor(row, col).stopCellEditing();
}
int rows = table.getRowCount();
int columns = table.getColumnCount();
try {
StringBuilder con = new StringBuilder();
for (int i = 0; i < table.getRowCount(); i++) {
for (int j = 0; j < table.getColumnCount(); j++) {
Object Value = table.getValueAt(i, j);
con.append(" ");
con.append(Value);
}
con.append("\r\n");
}
try (FileWriter fileWriter = new FileWriter(new File("C:\\Users\\8888"
+ "\\Documents\\NetBeansProjects\\Bb\\src\\bb\\cc.txt"))) {
fileWriter.write(con.append(temp).toString());
fileWriter.flush();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
My code just works if you have row includes zeros. if you want to make it better to cover up all conditions, I am sure you can follow my plan.
Sample to get rid of all zeros like
1 1 1
0 0 0
0 0 0
1 1 1
Code:
String s = "xxxooooooxxx";
String[] sp = s.split("");
boolean xFlag = false;
for (int i = 0; i < sp.length; i++) {
if (sp[i].equals("x") && !xFlag) {
System.out.print("x");
} else if (sp[i].equals("o")) {
xFlag = true;
} else if (sp[i].equals("x") && xFlag) {
System.out.print("X");
}
}
output:
xxxXXX

How to "hide" a JFrame using a JButton outside the main

So i've nearly completed this project, the last thing being the "hide" button. My teacher never gave instruction on what to do, but since it's annoying me and I can't find an answer that works, I figured i'd ask you good folks.
I've tried:
setExtendedState(JFrame.ICONIFIED) //causes a compiler error, can't find my variable name
setState(JFrame.ICONIFIED) //same issue, "can't find symbol", or rather find my variable
setVisible(false) //this doesn't work bc it hides my entire frame, and I can't get it back without closing the program.
I use Container c = getContentPane() to create the pane, then inside the main I use:
ClassName variableName = new ClassName() to create the parameters.
This is how I was taught and I have to use this way for now(since it is what my teacher wants) but I have noticed there are other ways to achieve this same goal.
Any input specific to my program would be awesome! Thanks!
My program as follows(I posted the whole thing so nothing may be left out):
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Arrays;
public class Project9 extends JFrame
{
Font f1 = new Font("Serif", Font.BOLD, 30);
Font f2 = new Font("Serif", Font.PLAIN, 18);
private BOOKItem[] bookArray = new BOOKItem[10];
private JLabel headerLbl;
private JLabel messagesLbl;
private JTextField idLabelFld;
private JTextField idFld;
private JTextField priceLabelFld;
private JTextField priceFld;
private JTextField numInStockLabelFld;
private JTextField numInStockFld;
private JTextField codeLabelFld;
private JTextField codeFld;
private JTextField messagesFld;
private JButton insertBtn;
private JButton deleteBtn;
private JButton displayBtn;
private JButton displayOneBtn;
private JButton hideBtn;
private JButton clearBtn;
private String input = "";
private String displayOneStr = "";
private int idInput = 0;
private double priceInput = 0.0;
private int numInStockInput = 0;
private int codeInput = 0;
private int index = 0;
private int numItems = 0;
private int responseCode = 0;
private Container c = getContentPane();
//Main Method, sets arrayFrame params
public static void main(String[] args)
{
Project9 arrayFrame = new Project9();
arrayFrame.setSize(555,450);
arrayFrame.setVisible(true);
arrayFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//Constructor
public Project9()
{
//Creates the array
for (int i = 0; i < bookArray.length; i++)
{
bookArray[i] = new BOOKItem();
System.out.println(bookArray[i]);
}
setTitle("Project 9");
c.setLayout(new FlowLayout());
headerLbl = new JLabel("Data Entry: BestBargainBook Store");
headerLbl.setFont(f1);
c.add(headerLbl);
idLabelFld = new JTextField("Enter ID:", 15);
idLabelFld.setEditable(false);
c.add(idLabelFld);
idFld = new JTextField(25);
c.add(idFld);
priceLabelFld = new JTextField("Enter Price:", 15);
priceLabelFld.setEditable(false);
c.add(priceLabelFld);
priceFld = new JTextField(25);
c.add(priceFld);
numInStockLabelFld = new JTextField("Enter Number In Stock:", 15);
numInStockLabelFld.setEditable(false);
c.add(numInStockLabelFld);
numInStockFld = new JTextField(25);
c.add(numInStockFld);
codeLabelFld = new JTextField("Enter Code: 1,2,3 or 4:", 15);
codeLabelFld.setEditable(false);
c.add(codeLabelFld);
codeFld = new JTextField(25);
c.add(codeFld);
insertBtn = new JButton("Insert");
c.add(insertBtn);
deleteBtn = new JButton("Delete");
c.add(deleteBtn);
displayBtn = new JButton("Display");
c.add(displayBtn);
displayOneBtn = new JButton("DisplayOne");
c.add(displayOneBtn);
hideBtn = new JButton("Hide");
c.add(hideBtn);
clearBtn = new JButton("Clear");
c.add(clearBtn);
messagesLbl = new JLabel("Messages:");
messagesLbl.setFont(f2);
c.add(messagesLbl);
messagesFld = new JTextField(30);
c.add(messagesFld);
//Event Listeners
insertBtn.addActionListener(new EventHandler());
deleteBtn.addActionListener(new EventHandler());
displayBtn.addActionListener(new EventHandler());
displayOneBtn.addActionListener(new EventHandler());
hideBtn.addActionListener(new EventHandler());
clearBtn.addActionListener(new EventHandler());
}//end constructor
private class EventHandler implements ActionListener
{
public void actionPerformed(ActionEvent ev)
{
if (ev.getSource() == insertBtn)
{
input = idFld.getText();
idInput = Integer.parseInt(input);
input = priceFld.getText();
priceInput = Double.parseDouble(input);
input = numInStockFld.getText();
numInStockInput = Integer.parseInt(input);
input = codeFld.getText();
codeInput = Integer.parseInt(input);
insert(idInput, priceInput, numInStockInput,
codeInput);
if (responseCode == 0)
{
messagesFld.setText("Array is full. Cannot insert book ID: " +
idInput);
}
else if (responseCode == 1)
{
messagesFld.setText("Succesful insertion of " + idInput);
}
else if (responseCode == -1)
{
messagesFld.setText("Duplicate ID: " + idInput);
}
}
else if (ev.getSource() == deleteBtn)
{
input = idFld.getText();
idInput = Integer.parseInt(input);
delete(idInput);
if (responseCode == 1)
{
messagesFld.setText("Successful delete of book ID: " +
idInput);
}
else if (responseCode == -1)
{
messagesFld.setText("ID: " + idInput + " not found.");
}
}
else if (ev.getSource() == displayBtn)
{
for (index = 0; index < bookArray.length; index++)
{
bookArray[index].display();
}
}
else if (ev.getSource() == displayOneBtn)
{
input = idFld.getText();
idInput = Integer.parseInt(input);
for (index = 0; index < bookArray.length; index++)
{
if (bookArray[index].getID() == idInput)
{
bookArray[index].getID();
bookArray[index].getPrice();
bookArray[index].getNumberInStock();
bookArray[index].getCode();
messagesFld.setText("id: " + bookArray[index].getID() +
" Price: " + bookArray[index].getPrice() +
" Number In Stock: " + bookArray[index].getNumberInStock() +
" Code: " + bookArray[index].getCode());
}
}
}
else if (ev.getSource() == hideBtn)
{
}
else if (ev.getSource() == clearBtn)
{
idFld.setText("");
priceFld.setText("");
numInStockFld.setText("");
codeFld.setText("");
messagesFld.setText("");
repaint();
}
}//End actionPerformed
}//End handler
//insert method, called when insert button is pressed
public int insert(int iD, double prc, int numInStock, int code)
{
if (numItems == 10)
{
System.out.println("\nThe Array is full, please delete an entry");
responseCode = 0;
return responseCode;
}
for (index = 0; index < bookArray.length; index++)
{
if (bookArray[index].getID() == iD)
{
System.out.println("\nThat ID already exists");
responseCode = -1;
return responseCode;
}
else if (bookArray[index].getID() == 0)
{
bookArray[index] = new BOOKItem(iD, prc, numInStock, code);
numItems++;
System.out.println("\n" + idInput + "\n" + priceInput + "\n" +
numInStockInput + "\n" + codeInput + "\n" + index);
System.out.println("\nID: " + bookArray[index].getID());
System.out.println("Price: " + bookArray[index].getPrice());
System.out.println("NIS: " + bookArray[index].getNumberInStock());
System.out.println("Code: " + bookArray[index].getCode());
System.out.println("Items in Array: " + numItems);
responseCode = 1;
return responseCode;
}
}
return responseCode;
}//end insert method
//Delete method, called when delete button is pressed
public int delete(int id)
{
for (index = 0; index < bookArray.length; index++)
{
if (bookArray[index].getID() == id)
{
bookArray[index].setID(0);
bookArray[index].setPrice(0);
bookArray[index].setStock(0);
bookArray[index].setCode(0);
numItems--;
System.out.println("\nSuccessful deletion");
responseCode = 1;
return responseCode;
}
}
responseCode = -1;
return responseCode;
}//end delete method
}//end app
In the ActionListener for your "Hide" button the basic code would be:
JButton button = (JButton)e.getSource();
Window window = SwingUtilities.windowForComponent( button );
JFrame frame = (JFrame)window;
frame.setState(JFrame.ICONIFIED);
This way you are not depending on any instance variable that identifies your frame. Using the source object of the event is a good way to make your listeners generic and flexible.
You can just simply do this with a button listener that sets the visiblity of the frame to false:
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
frame.setVisible(false);
}
});
If you want to iconify a JFrame:
minimize with frame.setState(Frame.ICONIFIED)
restore with frame.setState(Frame.NORMAL)
taken from: How to minimize a JFrame window from Java?
In your EventHandler nested class, try something like
Project9.this.setState(JFrame.ICONIFIED);

Categories

Resources