How to "hide" a JFrame using a JButton outside the main - java
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);
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] + " ?"); }
ArrayList Index Error
I am trying to finish up a project that uses a graphical User Interface to search through a data Base of geysers in the US. I keep getting an error for one of my Array Lists. I would include my data for the program but is is 10,000 entries long. Any help much appreciated. This is being done in BlueJ Error : java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 DataBase Code: import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.*; import java.util.ArrayList; import java.util.Scanner; public class GeyserDatabase { private ArrayList < Geyser > Geysers; private ArrayList < Eruption > Eruptions; public GeyserDatabase() { Geysers = new ArrayList < Geyser >(); Eruptions = new ArrayList < Eruption >(); } public void readGeyserData(String filename){ try{ File f = new File(filename); Scanner sc = new Scanner(f); String text; // keep reading as long as there is more data while(sc.hasNext()) { text = sc.nextLine(); Eruption e = new Eruption(text); Eruptions.add(e); } sc.close(); } catch(IOException e) { System.out.println("Failed to read the data file: " + filename); } createGeyserList(); } public void addEruption (Eruption e){ Eruptions.add(e); } public ArrayList <Eruption> getEruptionList(){ return Eruptions; } public ArrayList <Geyser> getGeyserList(){ return Geysers; } public int getNumEruptions() { return Eruptions.size(); } public int getNumEruptions(int m,int d,int y) { int count = 0; for ( Eruption e : Eruptions) { if (e.getMonth()==m && e.getDay()==d && e.getYear()==y) { count++; } } return count; } public Eruption getLateNightEruption() { Eruption latestEruption = Eruptions.get(0); int latestHour = latestEruption.getHour(); int latestMinute = latestEruption.getMinute(); for ( Eruption e: Eruptions ) { if (e.getHour() > latestHour || (e.getHour()==latestHour && e.getMinute()>latestMinute)) { latestEruption = e; latestHour = e.getHour(); latestMinute = e.getMinute(); } } return latestEruption; } public ArrayList < Eruption > getEruptions(String geyser) { ArrayList < Eruption > result = new ArrayList < Eruption > (); for ( Eruption e: Eruptions ) { if (e.getGeyserName().startsWith(geyser)) { result.add(e); } } return result; } private void createGeyserList(){ ArrayList<String>nameList = new ArrayList<String>(); // create temporary list of unique geyser names for(Eruption e:Eruptions){ if(!nameList.contains(e.getGeyserName())){ nameList.add(e.getGeyserName()); } } // create a list of geysers ArrayList<Geyser>geyserList = new ArrayList<Geyser>(); for(String s:nameList){ Geyser g = new Geyser(s); // count number of eruptions for current geyser name for(Eruption e:Eruptions){ if(e.getGeyserName().equals(g.getName())) g.increment(); } geyserList.add(g); } } public int getMostGeysers(){ return Geysers.size(); } public Geyser findMostActiveGeyser(){ Geyser MostEruptions = Geysers.get(0); int mostActive = MostEruptions.getNumEruptions(); for( Geyser g : Geysers){ if(g.getNumEruptions() > mostActive){ MostEruptions =g; mostActive = g.getNumEruptions(); } } return MostEruptions; } public Geyser findLeastActiveGeyser() { Geyser leastActiveGeyser = Geysers.get(0); int leastActive = leastActiveGeyser.getNumEruptions(); for(Geyser g: Geysers) { if(g.getNumEruptions() < leastActive) { leastActiveGeyser = g; leastActive = g.getNumEruptions(); } } return leastActiveGeyser; } public String findDayWithMostEruptions(int y){ int dayMost = 1; int monthMost = 1; int maxSoFar = getNumEruptions(1,1,y); for(int m = 1; m<=12; m++){ for(int d = 1; d<=31;d++){ int eruptionsDay = getNumEruptions(m,d,y); if(eruptionsDay>maxSoFar){ dayMost = d; monthMost = m; maxSoFar=eruptionsDay; } } } return monthMost + "/" + dayMost + "/" + y + "Eruptions: " + maxSoFar; } public static void main(String args[]){ GeyserDatabase gdb = new GeyserDatabase(); } } GUI Code: import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.util.*; import java.io.*; import java.text.*; /*********************************************************************** * GUI front end for a Yellowstone Geyser database * * #author Scott Grissom * #version August 1, 2016 public class GeyserGUI extends JFrame implements ActionListener{ /** results box */ private JTextArea resultsArea; private GeyserDatabase db; /**JButtons */ private JButton findLateNightEruption; private JButton findAmountOfEruptionsonDate; private JButton findMaxEruptionsInYear; private JButton findGeyserByName; private JButton findMostActiveGeyser; private JButton findLeastActiveGeyser; private JButton getGeyserList; private JTextField month; private JTextField day; private JTextField Year; private JTextField geyser; /** menu items */ private JMenuBar menus; private JMenu fileMenu; private JMenu reportsMenu; private JMenuItem quitItem; private JMenuItem openItem; private JMenuItem countItem; private JMenuItem geyserItem; /********************************************************************* Main Method *********************************************************************/ public static void main(String arg[]){ GeyserGUI gui = new GeyserGUI(); gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); gui.setTitle("Yellowstone Geysers"); gui.pack(); gui.setVisible(true); } /********************************************************************* Constructor - instantiates and displays all of the GUI commponents *********************************************************************/ public GeyserGUI(){ db = new GeyserDatabase(); // FIX ME: the following line should be removed db.readGeyserData("GeyserData.txt"); // create the Gridbag layout setLayout(new GridBagLayout()); GridBagConstraints position = new GridBagConstraints(); // create the Results Text Area (5 x 10 cells) resultsArea = new JTextArea(20,40); JScrollPane scrollPane = new JScrollPane(resultsArea); position.gridx = 0; position.gridy = 0; position.gridheight = 10; position.gridwidth = 5; position.insets = new Insets(20,20,0,0); add(scrollPane, position); /*******************************************************/ position = new GridBagConstraints(); position.insets = new Insets(0,20,0,0); position.gridx = 0; position.gridy = 10; position.gridwidth = 1; position.gridheight = 1; position.anchor = GridBagConstraints.LINE_START; add(new JLabel("Month"), position); position = new GridBagConstraints(); position.gridx = 0; position.gridy = 11; position.gridwidth = 1; position.gridheight = 1; position.anchor = GridBagConstraints.LINE_START; position.insets = new Insets(0,20,0,0); month = new JTextField(2); add(month, position); /*************************************************************/ position = new GridBagConstraints(); position.insets = new Insets(0,20,0,0); position.gridx = 1; position.gridy = 10; position.gridwidth = 1; position.gridheight = 1; position.anchor = GridBagConstraints.LINE_START; add(new JLabel("Day"), position); position = new GridBagConstraints(); position.gridx = 1; position.gridy = 11; position.gridwidth = 1; position.gridheight = 1; position.anchor = GridBagConstraints.LINE_START; position.insets = new Insets(0,20,0,0); day = new JTextField(2); add(day, position); /**********************************************************/ position = new GridBagConstraints(); position.insets = new Insets(0,20,0,0); position.gridx = 2; position.gridy = 10; position.gridwidth = 1; position.gridheight = 1; position.anchor = GridBagConstraints.LINE_START; add(new JLabel("Year"), position); position = new GridBagConstraints(); position.gridx = 2; position.gridy = 11; position.gridwidth = 1; position.gridheight = 1; position.anchor = GridBagConstraints.LINE_START; position.insets = new Insets(0,20,0,0); Year = new JTextField(4); add(Year, position); /**********************************************************/ position = new GridBagConstraints(); position.insets = new Insets(0,20,0,0); position.gridx = 3; position.gridy = 10; position.gridwidth = 1; position.gridheight = 1; position.anchor = GridBagConstraints.LINE_START; add(new JLabel("Geyser"), position); position = new GridBagConstraints(); position.gridx = 3; position.gridy = 11; position.gridwidth = 1; position.gridheight = 1; position.anchor = GridBagConstraints.LINE_START; position.insets = new Insets(0,20,0,0); geyser = new JTextField(12); add(geyser, position); /*********************************************************/ position = new GridBagConstraints(); position.insets = new Insets(30,5,5,5); position.gridx = 6; position.gridy = 0; position.gridwidth = 1; position.gridheight = 1; add(new JLabel("Eruptions"), position); position = new GridBagConstraints(); position.gridx = 6; position.gridy = 1; position.gridwidth = 1; position.gridheight = 1; position.insets = new Insets(0,5,5,5); findLateNightEruption = new JButton("Late Night Eruption"); findLateNightEruption.addActionListener(this); add(findLateNightEruption, position); position = new GridBagConstraints(); position.gridx = 6; position.gridy = 2; position.gridwidth = 1; position.gridheight = 1; position.insets = new Insets(0,5,5,5); findAmountOfEruptionsonDate = new JButton("# On Date"); findAmountOfEruptionsonDate.addActionListener(this); add(findAmountOfEruptionsonDate, position); position = new GridBagConstraints(); position.gridx = 6; position.gridy = 3; position.gridwidth = 1; position.gridheight = 1; position.insets = new Insets(0,5,5,5); findMaxEruptionsInYear = new JButton("Max Eruptions in Year"); findMaxEruptionsInYear.addActionListener(this); add(findMaxEruptionsInYear, position); position = new GridBagConstraints(); position.gridx = 6; position.gridy = 4; position.gridwidth = 1; position.gridheight = 1; position.insets = new Insets(0,5,5,5); findGeyserByName = new JButton("By Name"); findGeyserByName.addActionListener(this); add(findGeyserByName, position); position = new GridBagConstraints(); position.insets = new Insets(30,5,5,5); position.gridx = 6; position.gridy = 5; position.gridwidth = 1; position.gridheight = 1; add(new JLabel("Geysers"), position); position = new GridBagConstraints(); position.gridx = 6; position.gridy = 6; position.gridwidth = 1; position.gridheight = 1; position.insets = new Insets(0,5,5,5); findMostActiveGeyser = new JButton("Most Active"); findMostActiveGeyser.addActionListener(this); add(findMostActiveGeyser, position); position = new GridBagConstraints(); position.gridx = 6; position.gridy = 7; position.gridwidth = 1; position.gridheight = 1; position.insets = new Insets(0,5,5,5); findLeastActiveGeyser = new JButton("Least Active"); findLeastActiveGeyser.addActionListener(this); add(findLeastActiveGeyser, position); position = new GridBagConstraints(); position.gridx = 6; position.gridy = 8; position.gridwidth = 1; position.gridheight = 1; position.insets = new Insets(0,5,5,5); getGeyserList = new JButton("Geyser List"); getGeyserList.addActionListener(this); add(getGeyserList, position); // set up File menus setupMenus(); pack(); } /********************************************************************* List all entries given an ArrayList of eruptions. Include a final line with the number of eruptions listed #param m list of eruptions *********************************************************************/ private void displayEruptions(ArrayList <Eruption> m){ resultsArea.setText(""); for(Eruption e: m){ resultsArea.append("\n" + e.toString()); } resultsArea.append ("\nNumber of Geysers: " + m.size()); } /********************************************************************* Respond to menu selections and button clicks #param e the button or menu item that was selected *********************************************************************/ public void actionPerformed(ActionEvent e){ Eruption item = null; // either open a file or warn the user if (e.getSource() == openItem){ openFile(); }else if(db.getNumEruptions() == 0){ String errorMessage = "Did you forget to open a file?"; resultsArea.setText(errorMessage); return; } // menu item - quit else if (e.getSource() == quitItem){ System.exit(1); } // FIX ME: Count menu item - display number of eruptions and geysers else if (e.getSource() == countItem){ resultsArea.setText("\nNumber of Eruptions: " + db.getNumEruptions()); } // FIX ME: display late night eruption else if (e.getSource() == findLateNightEruption){ resultsArea.setText("Latest Eruption\n" + db.getLateNightEruption()); } //FIX ME: display all geyser names else if (e.getSource() == getGeyserList){ displayEruptions(db.getEruptionList()); } //FIX ME: max eruptions day in a year (check for year) else if(e.getSource() == findMaxEruptionsInYear){ String aux = Year.getText(); if(aux.length() == 0){ JOptionPane.showMessageDialog(this, "Enter a Year to Search For Maax Eruptions"); } else { int y = Integer.parseInt(Year.getText()); String result = db.findDayWithMostEruptions(y); resultsArea.setText(result); } } // FIX ME: list all eruptions for a geyser (check for name) else if(e.getSource() == findGeyserByName){ String name = geyser.getText(); if(name.length() == 0){ JOptionPane.showMessageDialog(this, "Provide Name"); } else { ArrayList<Eruption>result = db.getEruptions(name); displayEruptions(result); } } // FIX ME: display eruptions for a particular date else if(e.getSource()==findAmountOfEruptionsonDate){ String aux1 = Year.getText(); String aux2 = month.getText(); String aux3 = day.getText(); if(aux1.length() == 0 || aux2.length() == 0 || aux3.length() == 0) { JOptionPane.showMessageDialog(this, "Provide year,month, and day"); } else { int y = Integer.parseInt(Year.getText()); int m = Integer.parseInt(month.getText()); int d = Integer.parseInt(day.getText()); int result = db.getNumEruptions(m, d, y); resultsArea.setText("Number of Eruptions: " + result); } } else if(e.getSource() == findMostActiveGeyser){ resultsArea.setText("Most active Geyser: " + db.findMostActiveGeyser()); } else if(e.getSource() == findLeastActiveGeyser){ resultsArea.setText("Least active Geyser: " + db.findLeastActiveGeyser()); } } /********************************************************************* In response to the menu selection - open a data file *********************************************************************/ private void openFile(){ JFileChooser fc = new JFileChooser(new File(System.getProperty("user.dir"))); int returnVal = fc.showOpenDialog(this); // did the user select a file? if (returnVal == JFileChooser.APPROVE_OPTION) { String filename = fc.getSelectedFile().getName(); // use the name of your lottery ticket variable db.readGeyserData(filename); } } /********************************************************************* Create a custom gridbag constraint *********************************************************************/ private GridBagConstraints makeConstraints(int x, int y, int h, int w, int align){ GridBagConstraints rtn = new GridBagConstraints(); rtn.gridx = x; rtn.gridy = y; rtn.gridheight = h; rtn.gridwidth = w; // set alignment: LINE_START, CENTER, LINE_END rtn.anchor = align; return rtn; } /********************************************************************* Set up the menu items *********************************************************************/ private void setupMenus(){ // create menu components fileMenu = new JMenu("File"); quitItem = new JMenuItem("Quit"); openItem = new JMenuItem("Open..."); reportsMenu = new JMenu("Reports"); countItem = new JMenuItem("Counts"); // assign action listeners quitItem.addActionListener(this); openItem.addActionListener(this); countItem.addActionListener(this); // display menu components fileMenu.add(openItem); fileMenu.add(quitItem); reportsMenu.add(countItem); menus = new JMenuBar(); menus.add(fileMenu); menus.add(reportsMenu); setJMenuBar(menus); } } Geyser Code: import java.util.Scanner; public class Geyser { String geyserName; int count = 0; public Geyser (String name){ geyserName = name; } public void increment (){ count++; } public String getName() { return geyserName; } public int getNumEruptions() { return count; } public static void main(String args[]) { Geyser g = new Geyser("xyz"); if (g.getName().equals("xyz")) { System.out.println("getName worked well."); } else { System.out.println("getName did not work well."); } if (g.getNumEruptions() == 0) { System.out.println("getNumEruptions worked well."); } else { System.out.println("getNumEruptions did not work well."); } g.increment(); if (g.getNumEruptions() == 1) { System.out.println("getNumEruptions worked well."); } else { System.out.println("getNumEruptions did not work well."); } } } Eruption Code: import java.util.Scanner; public class Eruption { int month; int day; int year; int hour; int minute; String geyserName; public Eruption(String info){ Scanner scnr = new Scanner(info); scnr.useDelimiter("/|,|:"); month = scnr.nextInt(); day = scnr.nextInt(); year = scnr.nextInt(); geyserName = scnr.next(); hour = scnr.nextInt(); minute = scnr.nextInt(); } public int getMonth(){ return month; } public int getDay(){ return day; } public int getYear(){ return year; } public int getHour(){ return hour; } public int getMinute(){ return minute; } public String getGeyserName(){ return geyserName; } public String toString( ){ String geyserString = geyserName + " " + "on" + month +"/"+ day +"/" + year + "at" + hour +":"+ minute; return geyserString; } public static void main(String [] args){ Eruption e = new Eruption("1/2/2016,Old Faithful,10:46"); if (e.getMonth() == 1) { System.out.println("getMonth worked well"); } } }
Array Required, but java.lang.String found
I'm trying to hide a random word which I retrieved from a list in a text file, but the code keeps giving me the following error: Array Required, but java.lang.String found import java.awt.*; import java.awt.event.*; import java.util.Arrays; import javax.swing.*; import java.io.*; import java.util.ArrayList; import java.util.Random; import java.util.List; public class Hangman extends JFrame { private static final char HIDECHAR = '_'; String imageName = null; String Path = "D:\\Varsity College\\Prog212Assign1_10-013803\\images\\"; static int guesses =0; private String original = readWord(); private String hidden; int i = 0; static JPanel panel; static JPanel panel2; static JPanel panel3; static JPanel panel4; public Hangman(){ JButton[] buttons = new JButton[26]; this.original = original; this.hidden = this.createHidden(); panel = new JPanel(new GridLayout(0,9)); panel2 = new JPanel(); panel3 = new JPanel(); panel4 = new JPanel(); JButton btnRestart = new JButton("Restart"); btnRestart.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { } }); JButton btnNewWord = new JButton("Add New Word"); btnNewWord.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { try { FileWriter fw = new FileWriter("Words.txt", true); PrintWriter pw = new PrintWriter(fw, true); String word = JOptionPane.showInputDialog("Please enter a word: "); pw.println(word); pw.close(); } catch(IOException ie) { System.out.println("Error Thrown" + ie.getMessage()); } } }); JButton btnHelp = new JButton("Help"); btnHelp.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { String message = "The word to guess is represented by a row of dashes, giving the number of letters and category of the word." + "\nIf the guessing player suggests a letter which occurs in the word, the other player writes it in all its correct positions." + "\nIf the suggested letter does not occur in the word, the other player draws one element of the hangman diagram as a tally mark." + "\n" + "\nThe game is over when:" + "\nThe guessing player completes the word, or guesses the whole word correctly" + "\nThe other player completes the diagram"; JOptionPane.showMessageDialog(null,message, "Help",JOptionPane.INFORMATION_MESSAGE); } }); JButton btnExit = new JButton("Exit"); btnExit.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { System.exit(0); } }); JLabel lblWord = new JLabel(original); if(guesses >= 0) imageName = "Hangman1.jpg"; if(guesses >= 1) imageName = "Hangman2.jpg"; if(guesses >= 2) imageName = "Hangman3.jpg"; if(guesses >= 3) imageName = "Hangman4.jpg"; if(guesses >= 4) imageName = "Hangman5.jpg"; if(guesses >= 5) imageName = "Hangman6.jpg"; if(guesses >= 6) imageName = "Hangman7.jpg"; ImageIcon icon = null; if(imageName != null){ icon = new ImageIcon(Path + File.separator + imageName); } JLabel label = new JLabel(); label.setIcon(icon); String b[]={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"}; for(i = 0; i < buttons.length; i++) { buttons[i] = new JButton(b[i]); panel.add(buttons[i]); } panel2.add(label); panel3.add(btnRestart); panel3.add(btnNewWord); panel3.add(btnHelp); panel3.add(btnExit); panel4.add(lblWord); } public String readWord() { try { BufferedReader reader = new BufferedReader(new FileReader("Words.txt")); String line = reader.readLine(); List<String> words = new ArrayList<String>(); while(line != null) { String[] wordsLine = line.split(" "); boolean addAll = words.addAll(Arrays.asList(wordsLine)); line = reader.readLine(); } Random rand = new Random(System.currentTimeMillis()); String randomWord = words.get(rand.nextInt(words.size())); return randomWord; }catch (Exception e){ return null; } } private String printWord(){ StringBuilder sb = new StringBuilder(); for (int i = 0; i < this.original.length(); i++){ sb.append(HIDECHAR); } return sb.toString(); } public boolean check(char input){ boolean found = false; for (int i = 0; i < this.original.length(); i++){ if(this.original.charAt(i)== input)){ found = true; this.hidden[i] = this.original.charAt(i); } } return found; } public static void main(String[] args) { System.out.println(); Hangman frame = new Hangman(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Box mainPanel = Box.createVerticalBox(); frame.setContentPane(mainPanel); mainPanel.add(panel, BorderLayout.NORTH); mainPanel.add(panel2); mainPanel.add(panel4); mainPanel.add(panel3); frame.pack(); frame.setVisible(true); } } Okay there's the whole code< the error is now on line 151 and 149... I've also tried to fix it according to one of the posts
You can't use array subscripts: [], to index into a String, and both hidden and original are Strings. You can instead use original.charAt(i) to read a character at an index. As for writing a character at an index: java Strings are immutable, so you can't change individual characters. Instead make hidden a StringBuilder, or simply a char[]: // in your class member declarations: char hidden[] = createHidden(); // possible implementation of createHidden: char[] createHidden() { if (original != null) return new char[original.length()]; else return null; } And then your loop can use original.charAt like so: if (this.original.charAt(i) == input) { found = true; this.hidden[i] = this.original.charAt(i);
1. As you are using original.length() its a String, as length() method works with String, not with Array, as for array, length is an Instance variable. 2. Try it like this.... this.hidden[i] = original.charAt(i); 3. And as char is Not an object but a primitive, use "==" if (this.original[i] == input)
Change java applet to java application
I have an applet that runs a GUI. I want to call this GUI from my other program. I know that I need to turn this applet into an application. I have an init() and a actionPerformed(ActionEvent ae). How can I do it? My code: import java.applet.*; import java.awt.*; import java.awt.event.*; import java.util.*; import java.io.*; public class survey extends Applet implements ActionListener { private TextField question; private Button enter, start; int count = 0; int a = 0; int b = 0; int c = 0; int d = 0; String text, input; private Label intro1, intro2, intro3; private Label qone1, qone2, qone3, qone4, qone5, qone6, qone7, qone8, qone9, qone10, qone11, qone12; private Label qtwo1, qtwo2, qtwo3, qtwo4, qtwo5, qtwo6, qtwo7, qtwo8, qtwo9, qtwo10, qtwo11, qtwo12; private Label qthree1, qthree2, qthree3, qthree4, qthree5, qthree6, qthree7, qthree8, qthree9, qthree10, qthree11, qthree12; private Label qfour1, qfour2, qfour3, qfour4, qfour5, qfour6, qfour7, qfour8, qfour9, qfour10, qfour11, qfour12; private Label qfive1, qfive2, qfive3, qfive4, qfive5, qfive6, qfive7, qfive8, qfive9, qfive10, qfive11, qfive12; private Label qsix1, qsix2, qsix3, qsix4, qsix5, qsix6, qsix7, qsix8, qsix9, qsix10, qsix11, qsix12; private Label qseven1, qseven2, qseven3, qseven4, qseven5, qseven6, qseven7, qseven8, qseven9, qseven10, qseven11, qseven12; private Label qeight1, qeight2, qeight3, qeight4, qeight5, qeight6, qeight7, qeight8, qeight9, qeight10, qeight11, qeight12; private Label qnine1, qnine2, qnine3, qnine4, qnine5, qnine6, qnine7, qnine8, qnine9, qnine10, qnine11, qnine12; private Label qten1, qten2, qten3, qten4, qten5, qten6, qten7, qten8, qten9, qten10, qten11, qten12; private Label qeleven1, qeleven2, qeleven3, qeleven4, qeleven5, qeleven6, private Label finish1, finish2, finish3; public void init() { setLayout(null); start = new Button ("Start"); question = new TextField(10); enter = new Button ("Enter"); if (count == 0) { setBackground( Color.yellow); intro1 = new Label("Target Advertising", Label.CENTER); intro1.setFont(new Font("Times-Roman", Font.BOLD, 16)); intro2 = new Label("Welcome to this questionnaire. First, we would like to know more about your personal preferences."); intro3 = new Label("For each question, Input a rating between 0-9 (zero = least interested, 9 = most interested) in the text box. Click enter for next question."); add(intro1); add(intro2); add(intro3); intro1.setBounds(0,0,800,20); intro2.setBounds(15,20,800,20); intro3.setBounds(15,40,800,20); add(start); start.setBounds(370,60,70,23); start.addActionListener(this); } if(count == 1) { setBackground( Color.yellow ); qone1 = new Label("Question 1", Label.LEFT); qone1.setFont(new Font("Times-Roman", Font.BOLD, 16)); qone2 = new Label("How much do you like action movies?"); qone3 = new Label("0"); qone4 = new Label("1"); qone5 = new Label("2"); qone6 = new Label("3"); qone7 = new Label("4"); qone8 = new Label("5"); qone9 = new Label("6"); qone10 = new Label("7"); qone11 = new Label("8"); qone12 = new Label("9"); add(qone1); add(qone2); add(qone3); add(qone4); add(qone5); add(qone6); add(qone7); add(qone8); add(qone9); add(qone10); add(qone11); add(qone12); qone1.setBounds(15,0,800,20); qone2.setBounds(15,20,800,15); qone3.setBounds(15,60,800,15); qone4.setBounds(15,80,800,15); qone5.setBounds(15,100,800,15); qone6.setBounds(15,120,800,15); qone7.setBounds(15,140,800,15); qone8.setBounds(15,160,800,15); qone9.setBounds(15,180,800,15); qone10.setBounds(15,200,800,15); qone11.setBounds(15,220,800,15); qone12.setBounds(15,240,800,15); add(question); add(enter); question.setBounds(15,260,70,15); enter.setBounds(90,260,110,23); question.addActionListener(this); enter.addActionListener(this); } if (count == 2) { qtwo1 = new Label("Question 2", Label.LEFT); qtwo1.setFont(new Font("Times-Roman", Font.BOLD, 16)); qtwo2 = new Label("How much do you like Science Fiction?"); qtwo3 = new Label("0"); qtwo4 = new Label("1"); qtwo5 = new Label("2"); qtwo6 = new Label("3"); qtwo7 = new Label("4"); qtwo8 = new Label("5"); qtwo9 = new Label("6"); qtwo10 = new Label("7"); qtwo11 = new Label("8"); qtwo12 = new Label("9"); add(qtwo1); add(qtwo2); add(qtwo3); add(qtwo4); add(qtwo5); add(qtwo6); add(qtwo7); add(qtwo8); add(qtwo9); add(qtwo10); add(qtwo11); add(qtwo12); qtwo1.setBounds(15,0,800,20); qtwo2.setBounds(15,20,800,15); qtwo3.setBounds(15,60,800,15); qtwo4.setBounds(15,80,800,15); qtwo5.setBounds(15,100,800,15); qtwo6.setBounds(15,120,800,15); qtwo7.setBounds(15,140,800,15); qtwo8.setBounds(15,160,800,15); qtwo9.setBounds(15,180,800,15); qtwo10.setBounds(15,200,800,15); qtwo11.setBounds(15,220,800,15); qtwo12.setBounds(15,240,800,15); add(question); add(enter); question.setBounds(15,260,70,15); enter.setBounds(90,260,110,23); question.addActionListener(this); enter.addActionListener(this); } if(count == 3) { qthree1 = new Label("Question 3", Label.LEFT); qthree1.setFont(new Font("Times-Roman", Font.BOLD, 16)); qthree2 = new Label("How much do you like comedy?"); qthree3 = new Label("0"); qthree4 = new Label("1"); qthree5 = new Label("2"); qthree6 = new Label("3"); qthree7 = new Label("4"); qthree8 = new Label("5"); qthree9 = new Label("6"); qthree10 = new Label("7"); qthree11 = new Label("8"); qthree12 = new Label("9"); add(qthree1); add(qthree2); add(qthree3); add(qthree4); add(qthree5); add(qthree6); add(qthree7); add(qthree8); add(qthree9); add(qthree10); add(qthree11); add(qthree12); qthree1.setBounds(15,0,800,20); qthree2.setBounds(15,20,800,15); qthree3.setBounds(15,60,800,15); qthree4.setBounds(15,80,800,15); qthree5.setBounds(15,100,800,15); qthree6.setBounds(15,120,800,15); qthree7.setBounds(15,140,800,15); qthree8.setBounds(15,160,800,15); qthree9.setBounds(15,180,800,15); qthree10.setBounds(15,200,800,15); qthree11.setBounds(15,220,800,15); qthree12.setBounds(15,240,800,15); add(question); add(enter); question.setBounds(15,260,70,15); enter.setBounds(90,260,110,23); question.addActionListener(this); enter.addActionListener(this); } if(count == 4) { qfour1 = new Label("Question 4", Label.LEFT); qfour1.setFont(new Font("Times-Roman", Font.BOLD, 16)); qfour2 = new Label("How much do you like luxary cars?"); qfour3 = new Label("0"); qfour4 = new Label("1"); qfour5 = new Label("2"); qfour6 = new Label("3"); qfour7 = new Label("4"); qfour8 = new Label("5"); qfour9 = new Label("6"); qfour10 = new Label("7"); qfour11 = new Label("8"); qfour12 = new Label("9"); add(qfour1); add(qfour2); add(qfour3); add(qfour4); add(qfour5); add(qfour6); add(qfour7); add(qfour8); add(qfour9); add(qfour10); add(qfour11); add(qfour12); qfour1.setBounds(15,0,800,20); qfour2.setBounds(15,20,800,15); qfour3.setBounds(15,60,800,15); qfour4.setBounds(15,80,800,15); qfour5.setBounds(15,100,800,15); qfour6.setBounds(15,120,800,15); qfour7.setBounds(15,140,800,15); qfour8.setBounds(15,160,800,15); qfour9.setBounds(15,180,800,15); qfour10.setBounds(15,200,800,15); qfour11.setBounds(15,220,800,15); qfour12.setBounds(15,240,800,15); add(question); add(enter); question.setBounds(15,260,70,15); enter.setBounds(90,260,110,23); question.addActionListener(this); enter.addActionListener(this); } if(count == 5) { qfive1 = new Label("Question 5", Label.LEFT); qfive1.setFont(new Font("Times-Roman", Font.BOLD, 16)); qfive2 = new Label("How much do you like trucks?"); qfive3 = new Label("0"); qfive4 = new Label("1"); qfive5 = new Label("2"); qfive6 = new Label("3"); qfive7 = new Label("4"); qfive8 = new Label("5"); qfive9 = new Label("6"); qfive10 = new Label("7"); qfive11 = new Label("8"); qfive12 = new Label("9"); add(qfive1); add(qfive2); add(qfive3); add(qfive4); add(qfive5); add(qfive6); add(qfive7); add(qfive8); add(qfive9); add(qfive10); add(qfive11); add(qfive12); qfive1.setBounds(15,0,800,20); qfive2.setBounds(15,20,800,15); qfive3.setBounds(15,60,800,15); qfive4.setBounds(15,80,800,15); qfive5.setBounds(15,100,800,15); qfive6.setBounds(15,120,800,15); qfive7.setBounds(15,140,800,15); qfive8.setBounds(15,160,800,15); qfive9.setBounds(15,180,800,15); qfive10.setBounds(15,200,800,15); qfive11.setBounds(15,220,800,15); qfive12.setBounds(15,240,800,15); add(question); add(enter); question.setBounds(15,260,70,15); enter.setBounds(90,260,110,23); question.addActionListener(this); enter.addActionListener(this); } if(count == 7) { finish1 = new Label("Thank You." , Label.CENTER); finish1.setFont(new Font("Times-Roman", Font.BOLD, 50)); finish2 = new Label("Questionnaire Completed.", Label.CENTER); finish2.setFont(new Font("Times-Roman", Font.BOLD, 50)); add(finish1); add(finish2); finish1.setBounds(0,200,800,60); finish2.setBounds(0,300,800,60); } } public void actionPerformed(ActionEvent ae) { String button = ae.getActionCommand(); text = question.getText(); b = 0; c = 0; if (count == 6) { input = text.toUpperCase(); remove(enter); remove(question); question.setText(""); remove(qsix1); remove(qsix2); remove(qsix3); remove(qsix4); remove(qsix5); remove(qsix6); remove(qsix7); remove(qsix8); remove(qsix9); remove(qsix10); remove(qsix11); remove(qsix12); try{ FileWriter fstream = new FileWriter("lets3.txt",true); BufferedWriter out = new BufferedWriter(fstream); out.write(new String(input)); out.write("\n"); out.close(); } catch (Exception e){ System.err.println("Error: " + e.getMessage()); } if(input.equals("OL")) { b = 1; count = 7; init(); } else { b = 2; count = 7; init(); } } if (count == 5) { input = text.toUpperCase(); remove(enter); remove(question); question.setText(""); remove(qfive1); remove(qfive2); remove(qfive3); remove(qfive4); remove(qfive5); remove(qfive6); remove(qfive7); remove(qfive8); remove(qfive9); remove(qfive10); remove(qfive11); remove(qfive12); try{ FileWriter fstream = new FileWriter("lets3.txt",true); BufferedWriter out = new BufferedWriter(fstream); out.write(new String(input)); out.write("\n"); out.close(); } catch (Exception e){ System.err.println("Error: " + e.getMessage()); } if(input.equals("BR")) { b = 1; count = 6; init(); } else { b = 2; count = 6; init(); } } if (count == 4) { input = text.toLowerCase(); remove(enter); remove(question); question.setText(""); remove(qfour1); remove(qfour2); remove(qfour3); remove(qfour4); remove(qfour5); remove(qfour6); remove(qfour7); remove(qfour8); remove(qfour9); remove(qfour10); remove(qfour11); remove(qfour12); try{ FileWriter fstream = new FileWriter("lets3.txt",true); BufferedWriter out = new BufferedWriter(fstream); out.write(new String(input)); out.write("\n"); out.close(); } catch (Exception e){ System.err.println("Error: " + e.getMessage()); } if(input.equals("no")) { b = 1; count = 5; init(); } else { b = 2; count = 5; init(); } } if (count == 3) { input = text.toLowerCase(); remove(enter); remove(question); question.setText(""); remove(qthree1); remove(qthree2); remove(qthree3); remove(qthree4); remove(qthree5); remove(qthree6); remove(qthree7); remove(qthree8); remove(qthree9); remove(qthree10); remove(qthree11); remove(qthree12); try{ FileWriter fstream = new FileWriter("lets3.txt",true); BufferedWriter out = new BufferedWriter(fstream); out.write(new String(input)); out.write("\n"); out.close(); } catch (Exception e){ System.err.println("Error: " + e.getMessage()); } if(input.equals("black")) { b = 1; count = 4; init(); } else { b = 2; count = 4; init(); } } if (count == 2) { input = text.toLowerCase(); remove(enter); remove(question); question.setText(""); remove(qtwo1); remove(qtwo2); remove(qtwo3); remove(qtwo4); remove(qtwo5); remove(qtwo6); remove(qtwo7); remove(qtwo8); remove(qtwo9); remove(qtwo10); remove(qtwo11); remove(qtwo12); try{ FileWriter fstream = new FileWriter("lets3.txt",true); BufferedWriter out = new BufferedWriter(fstream); out.write(new String(input)); out.write("\n"); out.close(); } catch (Exception e){ System.err.println("Error: " + e.getMessage()); } if(input.equals("yes")) { b = 1; count = 3; init(); } else { b = 2; count = 3; init(); } } if (count == 1) { input = text.toUpperCase(); remove(enter); remove(question); question.setText(""); remove(qone1); remove(qone2); remove(qone3); remove(qone4); remove(qone5); remove(qone6); remove(qone7); remove(qone8); remove(qone9); remove(qone10); remove(qone11); remove(qone12); try{ FileWriter fstream = new FileWriter("lets3.txt",true); BufferedWriter out = new BufferedWriter(fstream); out.write(new String(input)); out.write("\n"); out.close(); } catch (Exception e){ System.err.println("Error: " + e.getMessage()); } if(input.equals("i")) { b = 1; count = 2; init(); } else { b = 1; count = 2; init(); } } if (count == 0) { remove(intro1); remove(intro2); remove(intro3); remove(start); count = 1; init(); } this.validate(); } }
In all honesty, you need to re-write your program from scratch so that you can incorporate OOP techniques, arrays, collections, and other advantages that Java has to offer. I recommend: First of all since your code displays a series of questions and prompts for response, don't hard-code the questions in the code but make them part of the data. Have your program read in a text file that holds the questions. This will allow you to change questions or add questions without altering code. Create a non-GUI Question class that holds questions and user responses and that is used by the GUI as its "model". Create an ArrayList of Question objects. For your GUI, code to the JPanel, not the applet or the JFrame. This will give you the option of using your GUI in a JFrame or a JApplet, or even a JDialog or embedded in another JPanel should you so desire. If you will need to swap display panels, consider using CardLayout for this purpose. If however all you'll be doing is changing the text of the question, then display the question text in a JLabel and when you want to change it, call setText(...) on the JLabel passing in the new question's text. Use the user-friendly layout managers to ease your work of laying out components in the GUI. Your current code has a lot of unnecessary redundencies. Use of arrays and collections such as ArrayLists will remove many of these redudancies and make debugging and upgrading much easier. As others have stated and as I stated in my earlier comment, you should move up to the Swing library as it is much more flexible and robust than the AWT gui library that you are currently using. The Swing tutorials will show you what you need to know to create beautiful Swing programs.
Just add a main() method, make a Frame for your applet, add the applet to the frame, and call the applet's init() and start() methods. See my Mandelbrot.java for an example: http://unixshell.jcomeau.com/src/java/com/jcomeau/Mandelbrot.java One advantage of this approach is that it can be used with any existing applet, to allow it to function as either an applet or application. Use a JFrame if you're using Swing components, otherwise it should work pretty nearly the same.
In general, you'll want to change all the non swing components to swing components. For events, they're roughly the same for both applets and swing applications. Hope it helps.
I'm not sure what you are asking, but if you want it inside a window all you need to do is this: public Object[] startNewSurvey() { java.awt.Frame f = new java.awt.Frame("You're title here."); f.setSize(new Dimension(<Width>, <Height>)); f.setResizable(false); survey s = new survey(); s.init(); f.add(s); f.setVisible(true); return new Object[] { f, s }; } That will just instance a brand new frame and put another new instance of your survey class in that frame, then display it. It also returns a 2 sized Object[] array containing the new Frame and survey instances made. Hope that helps.
https://way2java.com/applets/applet-to-application/ Following are the changes to be made from Applet to Application Delete the statement "import java.applet" package Replace extends Applet with Frame Replace the init() method with constructor Check the layout (for Applet, the default layout is FlowLayout and for Frame, it is BorderLayout) Add setXXX() methods like setSize() etc. Add the main() method HTML is not required (delete it)
JTable & JTextField used for input. JTable is updateable. DocumentListener used for JTextField. Event doesn't fire. How to get event?
import java.awt.*; import java.awt.Component; import java.lang.*; import javax.swing.*; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.event.*; import javax.swing.text.Document; import javax.swing.text.*; import javax.swing.JComponent; import javax.swing.JTable; import javax.swing.table.JTableHeader; import javax.swing.table.TableColumn; import javax.swing.table.AbstractTableModel; import javax.swing.table.*; import java.util.*; public class Test1 extends JApplet { Object dummya [][] = new Object [9][9]; // Setup 2-Dimensional Arrays int inputa [][] = new int [9][9]; int possiblea [][] = new int [81][9]; int solveda [][] = new int [9][9]; String ic = "B"; String nl = "\n"; String col_h [] = {"G1", "G2", "G3", "G4", "G5", "G6", "G7", "G8", "G9"}; Font f = new Font ("Courier", Font.BOLD, 10); Font h = new Font ("Times Roman", Font.BOLD, 14); JTextField uc = new JTextField (1); JTextField st = new JTextField (75); int gs = 55; int wl = 1; int ts = col_h.length; DefaultTableModel dm = new DefaultTableModel(dummya, col_h) { // Setup the Table Model public String getColumnName (int col) {return col_h[col];} public int getColumnCount() {return 9;} // Setup a 9x9 Table with headers public int getRowCount() {return 9;} public void setValueAt (Object foundValue, int row, int col) { // st.setText ("At setValueAt."); // inputa[row][col] = (Integer) foundValue; fireTableCellUpdated (row, col); } }; JTable table = new JTable (dm); // Create the Table public void init () { Container c = getContentPane (); // Get a Container for User View Color lc = new Color (240, 128, 128); // Set Light Coral Color c.setBackground (lc); c.setFont (f); table.getTableHeader().setResizingAllowed (false); // Setup all the Table rules table.getTableHeader().setReorderingAllowed (false); table.setSelectionMode (javax.swing.ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); for (int i = 0; i < ts; i++) { // Resize Columns & Rows to 40 pixels TableColumn column = table.getColumnModel().getColumn(i); column.setMinWidth (40); column.setMaxWidth (40); column.setPreferredWidth (40); table.setRowHeight (i, 40); } table.getModel().addTableModelListener ( new TableModelListener() { public void tableChanged(TableModelEvent e) { tableDataChanged (e); } }); c.setLayout (new FlowLayout (FlowLayout.CENTER, 340, 0)); // Setup a Layout & add Components c.add (new JLabel (" ")); c.add (new JLabel ("Challenge", SwingConstants.CENTER)); c.add (new JLabel (" ")); c.add (new JLabel ("By Author X", SwingConstants.CENTER)); c.add (new JLabel (" ")); // Add a pad line c.setFont (h); table.setGridColor (Color.red); // Setup Table View c.add (table.getTableHeader()); // Add Column Headers c.add (table); // Show the Table c.add (new JLabel (" ")); uc.setBackground (lc); c.add (new JLabel (" Enter Command (C,F,H,L,I,P,S): ", SwingConstants.CENTER)); c.add (uc); // Add a User Command Field uc.setEditable (true); // Allow Input in Command Field uc.requestFocusInWindow(); c.add (new JLabel (" ")); st.setBackground (lc); c.add (st); // Add a Status area st.setEditable (false); uc.getDocument().addDocumentListener (new DocumentListener() { // Listen for JTextField command public void changedUpdate(DocumentEvent e) { editInput(); } public void insertUpdate(DocumentEvent e) { editInput(); } public void removeUpdate(DocumentEvent e) {} }); } // The following section is driven by a user command. public void run () { // To keep the Applet running, just loop int loopcnt = 0; while (wl != -1) { loopcnt++; if (loopcnt == 100) { try { Thread.sleep (10000); } // Sleep for 10 seconds to allow solve catch (InterruptedException e) {} // thread to run. loopcnt = 0; } } } private void editInput () { // Scan user command try { ic = uc.getText (0, 1); } // Pick up user command catch (BadLocationException be) { return; } st.setText (" User Input is: " + ic); if (ic == "C" || ic == "c") clearComponents (); else if (ic == "E" || ic == "e") { st.setText (" User Exit."); wl = -1; } else if (ic == "H" || ic == "h") newFrame(); // else if (ic == "F" || ic == "f") getHintAtFirst(); // Get a hint where only 2 values possible // else if (ic == "L" || ic == "l ") getHintAtLast(); // else if (ic == "I" || ic == "i") StartThread(); // Look into wait and Notify // else if (ic == "P" || ic == "p") printGrid(); // else if (ic == "S" || ic == "s") solveAndShow(); // else st.setText (" Invalid Command, try again."); } public void clearComponents () { // Clear Arrarys and Table View for (int i = 0; i < ts; i++) { for (int j = 0; j < ts; j++) { dummya[i][j] = null; inputa[i][j] = 0; possiblea[i][j] = 0; solveda[i][j] = 0; table.setValueAt (null, i, j); } } st.setText (" Table Cleared."); } private void newFrame () { // Setup the Possibles frame JFrame possibles = new JFrame ("Grid Possibilities"); possibles.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); possibles.setBounds (550, 0, 440, 580); JTextArea ta = new JTextArea (); JScrollPane sp = new JScrollPane (); possibles.add (ta); possibles.add (sp); possibles.pack (); possibles.validate (); possibles.setVisible (true); } public void tableDataChanged (TableModelEvent e) { // Process & Edit user input int row = e.getFirstRow(); int col = e.getColumn(); // TableModel model = (TableModel) e.getSource(); // String cn = model.getColumnName (col); for (int i = row; i < ts; i++) { // Scan the input for values for (int j = col; i < ts; j++) { dummya [row][col] = table.getValueAt (i, j); int newValue = (Integer) dummya [row][col]; int rc = integerEditor (1, 9, newValue); // Go check the user input if (rc == 0) { st.setText ("Input Value is " + newValue); inputa [row][col] = (Integer) dummya [row][col]; // Store the grid value } else st.setText ("Input Value is invalid at " + row+1 + "," + col+1 + "."); } } } private int integerEditor (int va, int vb, int value) { // Edit user input if (value < va || value > vb) return -1; return 0; } }
DefaultCellEditor dce = (DefaultCellEditor)table.getDefaultEditor(Object.class); JTextField editor = (JTextField)dce.getComponent(); editor.addDocumentListener(...);