Variables in GUI application not updating - java

I am currently making a very simple Java GUI application, but have run into the problem that my variables are unable to update. The application is a simple basketball scorekeeper and the score integers do not update nor does the text of the labels showing them. There are no errors so I am unsure as of why nothing is updating. The code:
ScoreWindow.java
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.SpringLayout;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.FlowLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
public class ScoreWindow implements ScoreListener {
private JFrame frmScorewindow;
public volatile JLabel homeScoreLabel;
public JLabel awayScoreLabel;
public volatile int homeScore, awayScore;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ScoreWindow window = new ScoreWindow();
window.frmScorewindow.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ScoreWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
// Init Scores
homeScore = 0;
awayScore = 0;
frmScorewindow = new JFrame();
frmScorewindow.setResizable(false);
frmScorewindow.setTitle("Score Keeper");
frmScorewindow.setBounds(100, 100, 551, 348);
frmScorewindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmScorewindow.getContentPane().setLayout(null);
JButton homeScore2 = new JButton("+2");
homeScore2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ScoreListener listener = new ScoreWindow();
listener.homeScore(2);
}
});
homeScore2.setBounds(110, 129, 117, 29);
frmScorewindow.getContentPane().add(homeScore2);
JButton homeScore3 = new JButton("+3");
homeScore3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ScoreListener listener = new ScoreWindow();
listener.homeScore(3);
}
});
homeScore3.setBounds(110, 156, 117, 29);
frmScorewindow.getContentPane().add(homeScore3);
JButton awayScore2 = new JButton("+2");
awayScore2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ScoreListener listener = new ScoreWindow();
listener.awayScore(2);
}
});
awayScore2.setBounds(332, 129, 117, 29);
frmScorewindow.getContentPane().add(awayScore2);
JButton awayScore3 = new JButton("+3");
awayScore3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ScoreListener listener = new ScoreWindow();
listener.awayScore(3);
}
});
awayScore3.setBounds(332, 156, 117, 29);
frmScorewindow.getContentPane().add(awayScore3);
JButton resetButton = new JButton("Reset");
resetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ScoreListener listener = new ScoreWindow();
listener.reset();
}
});
resetButton.setBounds(225, 220, 117, 29);
frmScorewindow.getContentPane().add(resetButton);
homeScoreLabel = new JLabel("000");
homeScoreLabel.setFont(new Font("Lucida Grande", Font.PLAIN, 24));
homeScoreLabel.setHorizontalAlignment(SwingConstants.CENTER);
homeScoreLabel.setBounds(138, 88, 61, 29);
frmScorewindow.getContentPane().add(homeScoreLabel);
awayScoreLabel = new JLabel("000");
awayScoreLabel.setHorizontalAlignment(SwingConstants.CENTER);
awayScoreLabel.setFont(new Font("Lucida Grande", Font.PLAIN, 24));
awayScoreLabel.setBounds(361, 88, 61, 29);
frmScorewindow.getContentPane().add(awayScoreLabel);
JLabel lblHome = new JLabel("Home");
lblHome.setHorizontalAlignment(SwingConstants.CENTER);
lblHome.setBounds(138, 60, 61, 16);
frmScorewindow.getContentPane().add(lblHome);
JLabel lblAway = new JLabel("Away");
lblAway.setHorizontalAlignment(SwingConstants.CENTER);
lblAway.setBounds(361, 60, 61, 16);
frmScorewindow.getContentPane().add(lblAway);
JLabel title = new JLabel("Score Keeper App");
title.setHorizontalAlignment(SwingConstants.CENTER);
title.setBounds(180, 33, 200, 16);
frmScorewindow.getContentPane().add(title);
}
#Override
public void reset() {
print("reset();");
homeScore = 0;
awayScore = 0;
awayScoreLabel.setText("" + awayScore);
homeScoreLabel.setText("" + homeScore);
}
#Override
public void awayScore(int n) {
print("awayScore();");
awayScore+=n;
awayScoreLabel.setText("" + awayScore);
}
#Override
public void homeScore(int n) {
print("homeScore();");
print(homeScoreLabel.getText());
homeScore = homeScore + n;
homeScoreLabel.setText("" + homeScore);
homeScoreLabel.repaint();
homeScoreLabel.revalidate();
}
static void print(Object o) {
System.out.println(o);
}
}
ScoreListener.java
public interface ScoreListener {
public void reset();
public void awayScore(int n);
public void homeScore(int n);
}
Thank you!!

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ScoreWindow window = new ScoreWindow();
window.frmScorewindow.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
You create your window with the above code.
JButton homeScore2 = new JButton("+2");
homeScore2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ScoreListener listener = new ScoreWindow();
listener.homeScore(2);
}
});
But then you create a second instance of the window.
Don't do this. You only need to create once instance of your class. All other code to reference this instance.
Your ActionListner class is defined in the ScoreWindow class you you can just reference the "homeScore()" method directly.

Related

Need help implementing a pop up to show an ArrayList on a flight arrivals map in Java Eclipse

I have been trying to create a flight arrivals map program using windowbuilder however I have been stuck on displaying in the incoming flights for each airport
For context this map[ should display incoming flights when you hover your mouse on the letters(i.e hovering on YYZ will display incoming flight arrivals for Toronto airport)
I have an set of ArrayLists from a java file. Lets call it Aeroports.java which scans a csv file and scans it adding a line into a certain arraylist depending on its airport code(e.g YYZFlights)
The CSV file is in the format
DateOfFlight[0],DepartureTime1,ArrivalTime2,FlightDuration[3]
I have posted the full code below. I had to change the format of the dat so it could be read
Below is the program which stores the setters(procedures) and getters(functions) for each object
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Date;
public class Flights {
private String flightNo;
private String departureCity;
private String departureAirport;
private String ArrivalAirport;
private int delayedTime;
private LocalTime newArrivalTime;
private LocalTime ArrivalTime;
private LocalTime departureTime;
private LocalDate FlightDate;
public void setFlightNo(String flightNo)///sets the flightNo for each object
{
this.flightNo = flightNo;
}
public String getFlightNo()
{
return flightNo;
}
public void setdepartureCity(String departureCity)///sets the departure city for each object
{
this.departureCity = departureCity;
}
public String getdepartureCity()
{
return departureCity;
}
public void setdepartureAirport(String departureAirport)///sets the departure airport for each object
{
this.departureAirport = departureAirport;
}
public String getdepartureAirport()
{
return departureAirport;
}
public void setdelayedTime(int delayedTime)
{
this.delayedTime = delayedTime;
}
public int getdelayedTime()
{
return delayedTime;
}
public void setnewArrivalTime(LocalTime newArrivalTime)
{
this.newArrivalTime = newArrivalTime;
}
public LocalTime getnewArrivalTime()
{
return newArrivalTime;
}
public void setArrivalTime(LocalTime newArrivalTime)
{
this.ArrivalTime = newArrivalTime;
}
public LocalTime getArrivalTime()
{
return ArrivalTime;
}
public void setdepartureTime(LocalTime departureTime)
{
this.departureTime = departureTime;
}
public LocalTime getdepartureTime()
{
return departureTime;
}
public void setArrivalAirport(String ArrivalAirport)
{
this.ArrivalAirport = ArrivalAirport;
}
public String getArrivalAirport()
{
return ArrivalAirport;
}
public void setFlightDate( LocalDate FlightDate)
{
this.FlightDate = FlightDate;
}
public LocalDate getFlightDate( )
{
return FlightDate;
}
}
Listed below is the main program where delayed flights are calculated for each object and stores the ArrayLists that I intend to use in the future
import java.util.ArrayList;
import java.util.Date;
import java.time.format.DateTimeFormatter;
import java.io.*;
import java.util.Scanner;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Timer;
import java.util.TimerTask;
import java.time.*;
public class BCLAirport {
static ArrayList<Flights> allFlights = new ArrayList<Flights>();
static ArrayList<Flights> alldelayedFlights = new ArrayList<Flights>();
static ArrayList<Flights> BCLFlights = new ArrayList<Flights>();///Array list for Airport with code BCL the ones for the others are listed below
static ArrayList<Flights> SYDFlights = new ArrayList<Flights>();
static ArrayList<Flights> DXBFlights = new ArrayList<Flights>();
static ArrayList<Flights> DELFlights = new ArrayList<Flights>();
static ArrayList<Flights> BKKFlights = new ArrayList<Flights>();
static ArrayList<Flights> DUBFlights = new ArrayList<Flights>();
static ArrayList<Flights> CDGFlights = new ArrayList<Flights>();
static ArrayList<Flights> GRUFlights = new ArrayList<Flights>();
static ArrayList<Flights> YYZFlights = new ArrayList<Flights>();
static ArrayList<Flights> JFKFlights = new ArrayList<Flights>();
static ArrayList<Flights> MEXFlights = new ArrayList<Flights>();
static ArrayList<Flights> ARNFlights = new ArrayList<Flights>();
static ArrayList<Flights> CAIFlights = new ArrayList<Flights>();
static ArrayList<Flights> LOSFlights = new ArrayList<Flights>();
static ArrayList<Flights> AMSFlights = new ArrayList<Flights>();
static ArrayList<Flights> LVSFlights = new ArrayList<Flights>();
static ArrayList<Flights> DFWFlights = new ArrayList<Flights>();
static ArrayList<Flights> JNBFlights = new ArrayList<Flights>();
static ArrayList<Flights> HNDFlights = new ArrayList<Flights>();
static ArrayList<Flights> SVOFlights = new ArrayList<Flights>();
static ArrayList<Flights> LISFlights = new ArrayList<Flights>();
static ArrayList<Flights> MADFlights = new ArrayList<Flights>();
static ArrayList<Flights> RAKFlights = new ArrayList<Flights>();
static ArrayList<Flights> ATHFlights = new ArrayList<Flights>();
static ArrayList<Flights> FCOFlights = new ArrayList<Flights>();
public static void mainrun() throws ParseException ///
{
try
{
File myObj = new File("C:/Flights.csv"//this leads to flight csv file imagine this in a format); //Scans for the csv file
Scanner myReader = new Scanner(myObj);///gets input of csv file
while (myReader.hasNextLine())
{
String[] data = myReader.nextLine().split(",");///splits the line by the commas
Flights Flights = new Flights();//creayes new object
Flights.setdepartureAirport(data[6]);///sets the departure airport
Flights.setdepartureCity(data[7]);/// sets the departure city
Flights.setFlightNo(data[10]);//sets the flight number
Flights.setdelayedTime(Integer.parseInt(data[5]));// sets the delayed time
Flights.setdepartureTime(LocalTime.parse(data[1]));///sets the departure Time
Flights.setArrivalAirport(data[8]);
Flights.setArrivalTime(LocalTime.parse(data[2]));
String[] dating = data[0].split("/");
String newdating = dating[2]+"-"+dating[1]+"-"+dating[0];
data[0]=newdating;//writes the date in the new format
LocalDate todaysDate = LocalDate.now();
Flights.setFlightDate(LocalDate.parse(data[0]));
int delayTime = Integer.parseInt(data[5]);/// integer for the delayed time in minutes
if (LocalDate.parse(newdating).equals(todaysDate)) {
System.out.println("yes");
if (Flights.getArrivalAirport() == "BCL") {///Array lists for each airport
BCLFlights.add(Flights);
} else if (Flights.getArrivalAirport() == "SYD") {
SYDFlights.add(Flights);
} else if (Flights.getArrivalAirport() == "DXB") {
DXBFlights.add(Flights);
} else if (Flights.getArrivalAirport() == "DEL") {
DELFlights.add(Flights);
} else if (Flights.getArrivalAirport() == "BKK") {
BKKFlights.add(Flights);
} else if (Flights.getArrivalAirport() == "DUB") {
DUBFlights.add(Flights);
} else if (Flights.getArrivalAirport() == "CDG") {
CDGFlights.add(Flights);
} else if (Flights.getArrivalAirport() == "GRU") {
GRUFlights.add(Flights);
} else if (Flights.getArrivalAirport() == "YYZ") {
YYZFlights.add(Flights);
} else if (Flights.getArrivalAirport() == "JFK") {
JFKFlights.add(Flights);
} else if (Flights.getArrivalAirport() == "MEX") {
MEXFlights.add(Flights);
} else if (Flights.getArrivalAirport() == "ARN") {
ARNFlights.add(Flights);
} else if (Flights.getArrivalAirport() == "CAI") {
CAIFlights.add(Flights);
} else if (Flights.getArrivalAirport() == "LOS") {
LOSFlights.add(Flights);
} else if (Flights.getArrivalAirport() == "AMS") {
AMSFlights.add(Flights);
} else if (Flights.getArrivalAirport() == "LVS") {
LVSFlights.add(Flights);
} else if (Flights.getArrivalAirport() == "DFW") {
DFWFlights.add(Flights);
} else if (Flights.getArrivalAirport() == "JNB") {
JNBFlights.add(Flights);
} else if (Flights.getArrivalAirport() == "HND") {
HNDFlights.add(Flights);
} else if (Flights.getArrivalAirport() == "SVO") {
SVOFlights.add(Flights);
} else if (Flights.getArrivalAirport() == "LIS") {
LISFlights.add(Flights);
} else if (Flights.getArrivalAirport() == "MAD") {
MADFlights.add(Flights);
} else if (Flights.getArrivalAirport() == "RAK") {
RAKFlights.add(Flights);
} else if (Flights.getArrivalAirport() == "ATH") {
ATHFlights.add(Flights);
} else if (Flights.getArrivalAirport() == "FCO") {
FCOFlights.add(Flights);
}
if (delayTime >= 30) {
LocalTime oldTime = Flights.getArrivalTime();
// Flights.setArrivalTime(oldTime);formatter.format(today)
LocalTime newTime = oldTime.plusMinutes(delayTime);/// adds the delayed time
Flights.setnewArrivalTime(newTime);
alldelayedFlights.add(Flights);
}
}
//........
//if flightdate .equals date;
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date today = new Date();
//System.out.println(formatter.format(today));
// "2022-03-03"*/
// Date todayWithZeroTime = formatter.parse(formatter.format(today));
}
myReader.close();// closes the reader
//for(int i = 0; i < allFlights.size();i++)
///{
///System.out.println(allFlights.get(i).getdepartureCity() + " " +allFlights.get(i).getdepartureAirport() + " " + allFlights.get(i).getFlightNo() + " delayed by " + allFlights.get(i).getdelayedTime() + " minutes") ;
///}
for(int i = 0; i < alldelayedFlights.size();i++)///for the length of the array list delayed flights
{
//System.out.println(alldelayedFlights.get(i).getdepartureTime() + " " +alldelayedFlights.get(i).getdepartureAirport() + " " + alldelayedFlights.get(i).getArrivalAirport() + " " + alldelayedFlights.get(i).getArrivalTime() + " " + alldelayedFlights.get(i).getdelayedTime() + " " + alldelayedFlights.get(i).getnewArrivalTime() + " " + alldelayedFlights.get(i).getFlightDate()) ;
}
}
catch (FileNotFoundException e)
{
System.out.println("File cannot be found");
e.printStackTrace();
}
}
}
In another GUI java program I have used the pop up method to show a window depending on which airport I click on.
lblNewLabel_11 = new JLabel("HND");
lblNewLabel_11.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
lblNewLabel_11.setFont(new Font("Tahoma", Font.BOLD, 10));
lblNewLabel_11.setBounds(817, 277, 27, 13);
contentPane.add(lblNewLabel_11);
lblNewLabel_12 = new JLabel("SYD");
lblNewLabel_12.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
lblNewLabel_12.setFont(new Font("Tahoma", Font.BOLD, 10));
lblNewLabel_12.setBounds(855, 503, 45, 13);
contentPane.add(lblNewLabel_12);
lblNewLabel_13 = new JLabel("JNB");
lblNewLabel_13.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
Below is the UI file which uses window builder to build a UI
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTextPane;
import javax.swing.JLabel;
import javax.swing.JScrollBar;
import javax.swing.JTextField;
import java.awt.Font;
import javax.swing.JPasswordField;
import javax.swing.ImageIcon;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import com.toedter.calendar.JCalendar;
import javax.swing.JTextArea;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class MainFrame extends JFrame {
private JPanel contentPane;
private JPasswordField passwordField;
private JLabel lblNewLabel;
private JLabel lblNewLabel_1;
private JLabel lblMad;
private JLabel lblNewLabel_2;
private JLabel lblNewLabel_3;
private JLabel lblNewLabel_4;
private JLabel lblNewLabel_5;
private JLabel lblNewLabel_6;
private JLabel lblNewLabel_7;
private JLabel lblNewLabel_8;
private JLabel lblNewLabel_9;
private JLabel lblNewLabel_10;
private JLabel lblNewLabel_11;
private JLabel lblNewLabel_12;
private JLabel lblNewLabel_13;
private JLabel lblNewLabel_14;
private JLabel lblNewLabel_15;
private JLabel lblNewLabel_16;
private JLabel lblNewLabel_17;
private JLabel lblNewLabel_18;
private JLabel lblNewLabel_19;
private JLabel lblNewLabel_20;
private JLabel lblNewLabel_21;
private JLabel lblNewLabel_22;
private JLabel lblNewLabel_23;
private JLabel lblNewLabel_24;
private JLabel lblNewLabel_25;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
BCLAirport.mainrun();
MainFrame frame = new MainFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1351, 770);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
lblNewLabel_18 = new JLabel("DFW");
lblNewLabel_18.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
lblNewLabel_18.setFont(new Font("Tahoma", Font.BOLD, 10));
lblNewLabel_18.setBounds(105, 290, 27, 13);
contentPane.add(lblNewLabel_18);
lblNewLabel_16 = new JLabel("LVS");
lblNewLabel_16.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
lblNewLabel_16.setFont(new Font("Tahoma", Font.BOLD, 10));
lblNewLabel_16.setBounds(52, 267, 55, 13);
contentPane.add(lblNewLabel_16);
lblNewLabel_4 = new JLabel("YYZ\r\n");
lblNewLabel_4.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
lblNewLabel_4.setFont(new Font("Tahoma", Font.BOLD, 10));
lblNewLabel_4.setBounds(187, 231, 33, 13);
contentPane.add(lblNewLabel_4);
lblNewLabel_2 = new JLabel("DUB");
lblNewLabel_2.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
lblNewLabel_2.setFont(new Font("Tahoma", Font.BOLD, 10));
lblNewLabel_2.setBounds(388, 216, 27, 13);
contentPane.add(lblNewLabel_2);
lblNewLabel_1 = new JLabel("BCL");
lblNewLabel_1.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
lblNewLabel_1.setFont(new Font("Tahoma", Font.BOLD, 10));
lblNewLabel_1.setBounds(420, 210, 27, 24);
contentPane.add(lblNewLabel_1);
lblNewLabel_3 = new JLabel("JFK");
lblNewLabel_3.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
lblNewLabel_3.setFont(new Font("Tahoma", Font.BOLD, 10));
lblNewLabel_3.setBounds(193, 267, 27, 13);
contentPane.add(lblNewLabel_3);
lblMad = new JLabel("MAD");
lblMad.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
lblMad.setFont(new Font("Tahoma", Font.BOLD, 10));
lblMad.setBounds(414, 267, 33, 13);
contentPane.add(lblMad);
lblNewLabel_5 = new JLabel("LIS");
lblNewLabel_5.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
lblNewLabel_5.setFont(new Font("Tahoma", Font.BOLD, 10));
lblNewLabel_5.setBounds(383, 267, 21, 13);
contentPane.add(lblNewLabel_5);
lblNewLabel_6 = new JLabel("CAI");
lblNewLabel_6.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
lblNewLabel_6.setFont(new Font("Tahoma", Font.BOLD, 10));
lblNewLabel_6.setBounds(502, 309, 27, 13);
contentPane.add(lblNewLabel_6);
lblNewLabel_7 = new JLabel("DXB");
lblNewLabel_7.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
lblNewLabel_7.setFont(new Font("Tahoma", Font.BOLD, 10));
lblNewLabel_7.setBounds(569, 321, 27, 13);
contentPane.add(lblNewLabel_7);
lblNewLabel_8 = new JLabel("DEL");
lblNewLabel_8.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
lblNewLabel_8.setFont(new Font("Tahoma", Font.BOLD, 10));
lblNewLabel_8.setBounds(647, 309, 21, 13);
contentPane.add(lblNewLabel_8);
lblNewLabel_9 = new JLabel("BKK");
lblNewLabel_9.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
lblNewLabel_9.setFont(new Font("Tahoma", Font.BOLD, 10));
lblNewLabel_9.setBounds(727, 343, 27, 13);
contentPane.add(lblNewLabel_9);
lblNewLabel_10 = new JLabel("HKG");
lblNewLabel_10.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
lblNewLabel_10.setFont(new Font("Tahoma", Font.BOLD, 10));
lblNewLabel_10.setBounds(756, 309, 27, 13);
contentPane.add(lblNewLabel_10);
lblNewLabel_11 = new JLabel("HND");
lblNewLabel_11.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
lblNewLabel_11.setFont(new Font("Tahoma", Font.BOLD, 10));
lblNewLabel_11.setBounds(817, 277, 27, 13);
contentPane.add(lblNewLabel_11);
lblNewLabel_12 = new JLabel("SYD");
lblNewLabel_12.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
lblNewLabel_12.setFont(new Font("Tahoma", Font.BOLD, 10));
lblNewLabel_12.setBounds(855, 503, 45, 13);
contentPane.add(lblNewLabel_12);
lblNewLabel_13 = new JLabel("JNB");
lblNewLabel_13.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
lblNewLabel_13.setFont(new Font("Tahoma", Font.BOLD, 10));
lblNewLabel_13.setBounds(484, 503, 21, 13);
contentPane.add(lblNewLabel_13);
lblNewLabel_14 = new JLabel("LOS");
lblNewLabel_14.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
lblNewLabel_14.setFont(new Font("Tahoma", Font.BOLD, 10));
lblNewLabel_14.setBounds(433, 371, 21, 13);
contentPane.add(lblNewLabel_14);
lblNewLabel_15 = new JLabel("RAK");
lblNewLabel_15.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
lblNewLabel_15.setFont(new Font("Tahoma", Font.BOLD, 10));
lblNewLabel_15.setBounds(381, 290, 34, 13);
contentPane.add(lblNewLabel_15);
lblNewLabel_17 = new JLabel("GRU");
lblNewLabel_17.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
lblNewLabel_17.setFont(new Font("Tahoma", Font.BOLD, 10));
lblNewLabel_17.setBounds(264, 480, 27, 13);
contentPane.add(lblNewLabel_17);
lblNewLabel_19 = new JLabel("MEX");
lblNewLabel_19.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
lblNewLabel_19.setFont(new Font("Tahoma", Font.BOLD, 10));
lblNewLabel_19.setBounds(93, 321, 27, 13);
contentPane.add(lblNewLabel_19);
lblNewLabel_20 = new JLabel("ATH");
lblNewLabel_20.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
lblNewLabel_20.setFont(new Font("Tahoma", Font.BOLD, 10));
lblNewLabel_20.setBounds(478, 267, 27, 13);
contentPane.add(lblNewLabel_20);
lblNewLabel_21 = new JLabel("CDG");
lblNewLabel_21.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
lblNewLabel_21.setFont(new Font("Tahoma", Font.BOLD, 10));
lblNewLabel_21.setBounds(420, 244, 27, 13);
contentPane.add(lblNewLabel_21);
lblNewLabel_22 = new JLabel("ARN");
lblNewLabel_22.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
lblNewLabel_22.setFont(new Font("Tahoma", Font.BOLD, 10));
lblNewLabel_22.setBounds(453, 186, 27, 13);
contentPane.add(lblNewLabel_22);
lblNewLabel_23 = new JLabel("AMS");
lblNewLabel_23.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
lblNewLabel_23.setFont(new Font("Tahoma", Font.BOLD, 10));
lblNewLabel_23.setBounds(453, 216, 27, 13);
contentPane.add(lblNewLabel_23);
lblNewLabel_24 = new JLabel("SVO");
lblNewLabel_24.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
lblNewLabel_24.setFont(new Font("Tahoma", Font.BOLD, 10));
lblNewLabel_24.setBounds(520, 216, 45, 13);
contentPane.add(lblNewLabel_24);
lblNewLabel_25 = new JLabel("FCO");
lblNewLabel_25.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
lblNewLabel_25.setFont(new Font("Tahoma", Font.BOLD, 10));
lblNewLabel_25.setBounds(453, 255, 27, 13);
contentPane.add(lblNewLabel_25);
lblNewLabel = new JLabel("Map(don't delete)");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 10));
lblNewLabel.setBounds(0, 130, 944, 469);
lblNewLabel.setIcon(new ImageIcon("C:\\Users\\Student\\Pictures\\GUI\\map.png"));
contentPane.add(lblNewLabel);
JTextArea textArea = new JTextArea();
textArea.setBounds(970, 133, 334, 571);
contentPane.add(textArea);
JScrollPane scroll = new JScrollPane(textArea);
scroll.setBounds(970, 133, 334, 571);
contentPane.add(scroll);
JButton btnNewButton = new JButton("LVS");
lblMad.addMouseListener(new MouseAdapter() {
Popup frame = new Popup();
public void mouseEntered(MouseEvent e) {
frame.setVisible(true);
}
public void mouseExited(MouseEvent e) {
frame.setVisible(false);
}
});
btnNewButton.setBounds(52, 263, 45, 21);
contentPane.add(btnNewButton);
JLabel lblNewLabel_26 = new JLabel("Delayed Flights");
lblNewLabel_26.setFont(new Font("Tahoma", Font.BOLD, 21));
lblNewLabel_26.setBounds(1034, 72, 189, 51);
contentPane.add(lblNewLabel_26);
for (Flights f:BCLAirport.alldelayedFlights )
{
textArea.append(f.getdepartureTime() + " " +f.getdepartureAirport() + " " + f.getArrivalAirport() + " " + f.getArrivalTime() + " " + f.getdelayedTime() + " " + f.getnewArrivalTime() + " " + f.getFlightDate() + "\n" );//prints the results and goes to a new line
}
}
}
The main issue I have having is working out how to implement a way to show the incoming flightArrivals for each airport depending on which aiport I click for a reference see the picture for how the airport UI looksHere's UI normally
When I hover on the name of an airport at the moment blank window pops up but I want it to show the incoming arrivals for the day. I have been able to show delayedFlights but have been unable to show the specific arraylists for each airport which I want to show in the format
ArrivalTime, Departure City, Departure Airport, FlightNo
It should look like this when you hover on a airport nameHow it should ideally look like
If someone could help that would be great becaus I'm quite stuck
What exactly is your issue? Is it that you only see delayed flights but not all flights? You have static ArrayList<Flights> allFlights = new ArrayList<Flights>(); but as far as I see you never add a flight to it. You only add flights to the other lists.
Unrelated to your main issue, but some general observations:
Consider renaming Flights to Flight This class is a single flight, not a list of flights right?
You have an ArrayList<Flight> for every airport. This seems really difficult to work with. Maybe there is a different data structure that better fits your needs. Maybe Map<Airport, List<Flight>> flightsByAirport
It looks like each airport is it's own class? BCLAirport Maybe there is a different way to handle that.

Java no UI update after Thread

So, I have got this problem in my Java Swing project where I am making a bot that automatically runs through a whileloop and outputs a text that the user can define in a textfield.
Here you can see my code for adding a textline into a jlabel into my frame:
btnAddTalking = new JButton("Add");
btnAddTalking.setBounds(144, 211, 146, 23);
btnAddTalking.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!txtTalk.getText().equals("")) {
JLabel newLabel = new JLabel(txtTalk.getText());
newLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent arg0) {
frame.remove(newLabel);
frame.repaint();
}
});
newLabel.setHorizontalAlignment(SwingConstants.CENTER);
newLabel.setBounds(159, yLabel, 101, 20);
frame.getContentPane().add(newLabel);
yLabel = yLabel + 20;
frame.getContentPane().setLayout(null);
frame.repaint();
Talk.addTalk(txtTalk.getText());
}
}
});
frame.getContentPane().add(btnAddTalking);
frame.getContentPane().add(lblNewLabel);
frame.getContentPane().add(lblDelayInMs);
After that I start my bot by pressing the following button:
btnStartTalking = new JButton("Start AutoTalk");
btnStartTalking.setBounds(144, 143, 146, 23);
btnStartTalking.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int robotDelay = Integer.parseInt(timeTalk.getText());
Talk.action = "start";
robotTalk = txtTalk.getText();
if (rdbtnRed.isSelected() == true) {
robotTalk = "red:" + txtTalk.getText();
} else if (rdbtnFlash.isSelected() == true) {
robotTalk = "flash1:" + txtTalk.getText();
} else if (rdbtnGlow.isSelected() == true) {
robotTalk = "glow1:" + txtTalk.getText();
}
autoTalkStart = new Runnable() {
public void run() {
try {
btnStartTalking.setEnabled(false);
btnStopTalking.setEnabled(true);
btnAddTalking.setEnabled(false);
Talk test = new Talk(robotDelay);
} catch (AWTException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
new Thread(autoTalkStart).start();
}
});
Via that button I start a thread which runs through a code that outputs the string. But after I've runned that Thread, my frame doesn't show newly-added jlabels anymore that you've added by clicking the btnAddTalking-button after you've run the Thread by clicking on the btnStartTalking-button! So, my question is: does anyone now how that's even possible (why my UI doesn't update anymore after i've run the thread)?
Greetz,
Jarnov
Here you can see my whole code for the two classes (class 1):
import java.awt.EventQueue;
import java.awt.event.InputEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import com.sun.glass.events.KeyEvent;
import com.sun.glass.ui.Robot;
import java.awt.AWTException;
import java.awt.BorderLayout;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JLabel;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.GroupLayout.Alignment;
import javax.swing.SpringLayout;
import javax.swing.SwingConstants;
import javax.swing.JRadioButton;
public class AutoTalker {
private static JFrame frame;
private JTextField txtTalk;
private JTextField timeTalk;
public String robotTalk;
private JButton btnStopTalking;
private JButton btnAddTalking;
private JButton btnStartTalking;
private int yLabel = 266;
private Runnable autoTalkStart;
/**
* Launch the application.
*/
public static void NewFrame() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AutoTalker window = new AutoTalker();
window.frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
* #return
*/
public AutoTalker() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 415);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("AutoTalker");
frame.getContentPane().setLayout(null);
JRadioButton rdbtnGlow = new JRadioButton("Glow");
rdbtnGlow.setBounds(6, 113, 64, 23);
rdbtnGlow.setActionCommand("glow");
frame.getContentPane().add(rdbtnGlow);
JRadioButton rdbtnFlash = new JRadioButton("Flash");
rdbtnFlash.setBounds(182, 113, 69, 23);
rdbtnGlow.setActionCommand("flash");
frame.getContentPane().add(rdbtnFlash);
JRadioButton rdbtnRed = new JRadioButton("Red");
rdbtnRed.setBounds(364, 113, 64, 23);
rdbtnGlow.setActionCommand("red");
frame.getContentPane().add(rdbtnRed);
final ButtonGroup rdbtnPressed = new ButtonGroup();
rdbtnPressed.add(rdbtnRed);
rdbtnPressed.add(rdbtnFlash);
rdbtnPressed.add(rdbtnGlow);
txtTalk = new JTextField();
txtTalk.setBounds(130, 28, 173, 20);
txtTalk.setColumns(10);
btnStopTalking = new JButton("Stop AutoTalk");
btnStopTalking.setBounds(144, 177, 146, 23);
btnStopTalking.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Talk.action = "stop";
btnStartTalking.setEnabled(true);
btnStopTalking.setEnabled(false);
btnAddTalking.setEnabled(true);
frame.repaint();
}
});
btnStartTalking = new JButton("Start AutoTalk");
btnStartTalking.setBounds(144, 143, 146, 23);
btnStartTalking.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int robotDelay = Integer.parseInt(timeTalk.getText());
Talk.action = "start";
robotTalk = txtTalk.getText();
if (rdbtnRed.isSelected() == true) {
robotTalk = "red:" + txtTalk.getText();
} else if (rdbtnFlash.isSelected() == true) {
robotTalk = "flash1:" + txtTalk.getText();
} else if (rdbtnGlow.isSelected() == true) {
robotTalk = "glow1:" + txtTalk.getText();
}
autoTalkStart = new Runnable() {
public void run() {
try {
btnStartTalking.setEnabled(false);
btnStopTalking.setEnabled(true);
btnAddTalking.setEnabled(false);
Talk test = new Talk(robotDelay);
} catch (AWTException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
new Thread(autoTalkStart).start();
frame.repaint();
}
});
timeTalk = new JTextField();
timeTalk.setBounds(174, 71, 86, 20);
timeTalk.setColumns(10);
JLabel lblNewLabel = new JLabel("Text:");
lblNewLabel.setBounds(24, 28, 46, 20);
JLabel lblDelayInMs = new JLabel("Delay in ms:");
lblDelayInMs.setBounds(24, 71, 101, 20);
frame.getContentPane().add(txtTalk);
frame.getContentPane().add(btnStartTalking);
frame.getContentPane().add(btnStopTalking);
frame.getContentPane().add(timeTalk);
btnAddTalking = new JButton("Add");
btnAddTalking.setBounds(144, 211, 146, 23);
btnAddTalking.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(!txtTalk.getText().equals("")) {
JLabel newLabel = new JLabel(txtTalk.getText());
newLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent arg0) {
frame.remove(newLabel);
frame.repaint();
}
});
newLabel.setHorizontalAlignment(SwingConstants.CENTER);
newLabel.setBounds(159, yLabel, 101, 20);
frame.getContentPane().add(newLabel);
yLabel = yLabel + 20;
frame.getContentPane().setLayout(null);
frame.repaint();
Talk.addTalk(txtTalk.getText());
}
}
});
frame.getContentPane().add(btnAddTalking);
frame.getContentPane().add(lblNewLabel);
frame.getContentPane().add(lblDelayInMs);
btnStopTalking.setEnabled(false);
}
}
class 2:
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.ArrayList;
public class Talk extends AutoTalker {
Robot robot = new Robot();
public static String action;
public static ArrayList<String> Talks = new ArrayList<String>();
public Talk(int wait) throws AWTException, InterruptedException {
robot.delay(5000);
while(action == "start") {
for(int i = 0; i < Talks.size();i++) {
String text = Talks.get(i);
type(text);
robot.delay(wait);
}
}
}
public static void addTalk(String text) {
Talks.add(text);
}
private void type(String s)
{
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
switch(c) {
case '!':
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_1);
robot.keyRelease(KeyEvent.VK_SHIFT);
robot.keyRelease(KeyEvent.VK_1);
break;
case ':':
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_SEMICOLON);
robot.keyRelease(KeyEvent.VK_SEMICOLON);
robot.keyRelease(KeyEvent.VK_SHIFT);
break;
default:
robot.keyPress(Character.toUpperCase(c));
break;
}
robot.delay(10);
}
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.delay(10);
}
}
Use instead
invalidate();
validate();

I cant get my try catch to work in java

So here is my GUI as you can see.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Frame1 {
private JFrame frame;
private JTextField textFieldnum1;
private JTextField textFieldnum2;
private JTextField textFieldAns;
private Termostat thermo;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Frame1 window = new Frame1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Frame1() {
initialize();
}
private void initialize() {
thermo = new Termostat();
frame = new JFrame();
frame.setBounds(100, 100, 696, 250);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textFieldnum1 = new JTextField();
textFieldnum1.setBounds(176, 11, 147, 46);
frame.getContentPane().add(textFieldnum1);
textFieldnum1.setColumns(10);
textFieldnum2 = new JTextField();
textFieldnum2.setBounds(176, 154, 147, 46);
frame.getContentPane().add(textFieldnum2);
textFieldnum2.setColumns(10);
JButton btnNewButton = new JButton("Convert to celcius");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double myf = thermo.convertToCelcius(Double.parseDouble(textFieldnum1.getText()));
textFieldAns.setText(String.valueOf(myf));
}
});
btnNewButton.setBounds(0, 0, 171, 68);
frame.getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("Convert to fahrenheit");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double myf = thermo.convertToFahrenheit(Double.parseDouble(textFieldnum2.getText()));
textFieldAns.setText(String.valueOf(myf));
}
});
btnNewButton_1.setBounds(0, 143, 171, 68);
frame.getContentPane().add(btnNewButton_1);
textFieldAns = new JTextField();
textFieldAns.setBounds(354, 90, 147, 46);
frame.getContentPane().add(textFieldAns);
textFieldAns.setColumns(10);
JLabel lblNewLabel = new JLabel("Converted");
lblNewLabel.setBounds(285, 94, 112, 38);
frame.getContentPane().add(lblNewLabel);
}
}
And here comes my problem. When i made my class that i wanna run the input in to calculate celcius to fahrenheit, i dont want it to crash when i type anything else than numbers. but i cant get it to work so i need you guys help to get the try catch to work.
Im very thankful for all help i get.
import javax.swing.JOptionPane;
public class Termostat {
public double convertToCelcius(double input) {
double far = 0;
try {
far = (input - 32) * 5 / 9;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Wrong input");
return far;
}
return far;
}
public double convertToFahrenheit(double input) {
double cel = 1;
try {
cel = (input * 9 / 5) + 32;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Wrong input");
return cel;
}
return cel;
}
}
This is the line where you get probably an Exception:
double myf = thermo.convertToFahrenheit(Double.parseDouble(textFieldnum2.getText()));
So guard it with a NumberFormatException (parseDouble).
You can use the NumberUtil.isNumber(str) to check if the input is a number. Here is more information
you must use try catch when you want to parse text field texts to Double using this method Double.parseDouble(text)
write them them like this and remove your try catches inside your convertToFahrenheit and convertToCelcius methods
JButton btnNewButton_1 = new JButton("Convert to fahrenheit");
btnNewButton_1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
try { // start trying to parse input string to double
double myf = thermo.convertToFahrenheit(Double.parseDouble(textFieldnum2.getText()));
textFieldAns.setText(String.valueOf(myf));
} catch (NumberFormatException ex) { // catch the exception that you mentioned
JOptionPane.showMessageDialog(null, "Wrong input");
textFieldAns.setText("");
}
}
});

Display array in textboxes in a while loop

I am creating a program that will take the data from several textboxes store in an array and when a next and previous button are pressed display the next or last position in the array, currently the next button gets stuck in a while loop without displaying and I'm not sure how to fix it, I am an amateur and I need help with this.
package major;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import java.awt.List;
import java.awt.Label;
import javax.swing.JScrollPane;
import javax.swing.JList;
import javax.swing.JButton;
import javax.swing.JScrollBar;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
public class gui {
private JFrame frame;
private JTextField websitetxt;
private JTextField usernametxt;
private JTextField passwordtxt;
private encryptedData[] dataArray;
private int dataArrayMaxIndex;
private int dataArrayMax;
private int dataArrayCurrentIndex;
private JButton btnadd;
private JButton btnnew;
private JButton btndelete;
private JTextField notestxt;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
gui window = new gui();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public gui() {
initialize();
dataArrayMax = 20;
dataArray = new encryptedData[dataArrayMax];
dataArrayMaxIndex = 0;
while (dataArrayMaxIndex < dataArrayMax) {
dataArray[dataArrayMaxIndex] = new encryptedData();
dataArrayMaxIndex++;
}
dataArrayMaxIndex = -1;
dataArrayCurrentIndex = -1;
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 569, 427);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
websitetxt = new JTextField();
websitetxt.setBounds(315, 56, 191, 38);
frame.getContentPane().add(websitetxt);
websitetxt.setColumns(10);
usernametxt = new JTextField();
usernametxt.setColumns(10);
usernametxt.setBounds(315, 105, 191, 38);
frame.getContentPane().add(usernametxt);
passwordtxt = new JTextField();
passwordtxt.setColumns(10);
passwordtxt.setBounds(315, 154, 191, 38);
frame.getContentPane().add(passwordtxt);
JLabel lblWebsite = new JLabel("Website:");
lblWebsite.setBounds(227, 68, 78, 14);
frame.getContentPane().add(lblWebsite);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setBounds(227, 117, 78, 14);
frame.getContentPane().add(lblUsername);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setBounds(227, 166, 78, 14);
frame.getContentPane().add(lblPassword);
final JButton btnadd = new JButton("Add to Database");
btnadd.setEnabled(false);
btnadd.setBounds(10, 105, 191, 38);
frame.getContentPane().add(btnadd);
JLabel lblPasswordManagerHsc = new JLabel("Password manager hsc 2014");
lblPasswordManagerHsc.setBounds(191, 11, 168, 14);
frame.getContentPane().add(lblPasswordManagerHsc);
final JButton btnnew = new JButton("New Record");
btnnew.setBounds(10, 56, 191, 38);
frame.getContentPane().add(btnnew);
JButton btndelete = new JButton("Delete Record");
btndelete.setBounds(10, 154, 191, 38);
frame.getContentPane().add(btndelete);
JButton btnprev = new JButton("Prev");
btnprev.setBounds(315, 316, 89, 23);
frame.getContentPane().add(btnprev);
JButton btnnext = new JButton("Next");
btnnext.setBounds(417, 316, 89, 23);
frame.getContentPane().add(btnnext);
notestxt = new JTextField();
notestxt.setBounds(315, 203, 191, 102);
frame.getContentPane().add(notestxt);
notestxt.setColumns(10);
JLabel lblnotes = new JLabel("Notes");
lblnotes.setBounds(227, 215, 46, 14);
frame.getContentPane().add(lblnotes);
JButton btngenerate = new JButton("Generate Password");
btngenerate.setBounds(10, 203, 191, 38);
frame.getContentPane().add(btngenerate);
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu File = new JMenu("File");
menuBar.add(File);
JMenuItem save = new JMenuItem("Save");
File.add(save);
JMenuItem load = new JMenuItem("Load");
File.add(load);
JMenuItem mntmHelp = new JMenuItem("About");
File.add(mntmHelp);
websitetxt.setEnabled(false);
usernametxt.setEnabled(false);
passwordtxt.setEnabled(false);
notestxt.setEnabled(false);
btnadd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
btnadd.setEnabled(false);
dataArrayCurrentIndex++;
dataArrayMaxIndex++;
dataArray[dataArrayCurrentIndex].username = usernametxt.getText();
dataArray[dataArrayCurrentIndex].password = passwordtxt.getText();
dataArray[dataArrayCurrentIndex].notes = notestxt.getText();
dataArray[dataArrayCurrentIndex].website = websitetxt.getText();
}
});
btnnew.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnnew) {
websitetxt.setEnabled(true);
usernametxt.setEnabled(true);
passwordtxt.setEnabled(true);
notestxt.setEnabled(true);
btnadd.setEnabled(true);
websitetxt.setText("");
usernametxt.setText("");
passwordtxt.setText("");
notestxt.setText("");
}
}
});
btndelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnprev.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnnext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = 0;
while (i < dataArrayMaxIndex) {
dataArrayCurrentIndex = i;
websitetxt.setText(dataArray[i].getWebsitename());
usernametxt.setText(dataArray[i].getUsername());
passwordtxt.setText(dataArray[i].getPassword());
notestxt.setText(dataArray[i].getNotes());
}
i++;
}
});
}
}
package major;
public class encryptedData {
public String website;
public String username;
public String password;
public String notes;
public encryptedData() {
try {
website = "";
username = "";
password = "";
notes = "";
} catch (Exception e) {
}
}
public encryptedData(String w, String u, String p, String n) {
try {
website = w;
username = u;
password = p;
notes = n;
} catch (Exception e) {
}
}
//Access methods
public String getWebsitename() {
return website;
}
public void setWebsiteName(String w) {
website = w;
}
public String getUsername() {
return username;
}
public void setUsername(String u) {
username = u;
}
public String getPassword() {
return password + "";
}
public void setPassword(String p) {
password = p;
}
public String getNotes() {
return notes + "";
}
public void setNotes(String n) {
notes = n;
}
}
You are incrementing i after the while loop in actionPerformed()!
If you had formatted your code better, this would have been obvious:
btnnext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = 0;
while (i<dataArrayMaxIndex) {
dataArrayCurrentIndex = i;
websitetxt.setText(dataArray[i].getWebsitename());
usernametxt.setText(dataArray[i].getUsername());
passwordtxt.setText(dataArray[i].getPassword());
notestxt.setText(dataArray[i].getNotes());
}
i++;
}
});
And this would have been even better:
btnnext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i<dataArrayMaxIndex; i++) {
dataArrayCurrentIndex = i;
websitetxt.setText(dataArray[i].getWebsitename());
usernametxt.setText(dataArray[i].getUsername());
passwordtxt.setText(dataArray[i].getPassword());
notestxt.setText(dataArray[i].getNotes());
}
}
});

Auto clicker UI goes black when started

i have made a simple auto clicker, but when i run it the screen goes black so i cant stop it etc. i dont have a clue what i have done wrong. I thought maybe i had to set focus, but i am not sure.
Code:
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.UIManager;
import javax.swing.JRadioButton;
public class AutoClicker1 extends JFrame {
private JPanel contentPane;
private JTextField textField;
public static int rate;
public static boolean go = false;
public static int time;
public static int multiplyer;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AutoClicker1 frame = new AutoClicker1();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public AutoClicker1() {
setTitle("Auto Clicker");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 361, 154);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNoOfClicks = new JLabel("Interval between clicks");
lblNoOfClicks.setBounds(10, 25, 149, 14);
contentPane.add(lblNoOfClicks);
textField = new JTextField();
textField.setBounds(10, 55, 139, 20);
contentPane.add(textField);
textField.setColumns(10);
JButton btnStopf = new JButton("Stop(F11)");
btnStopf.setBounds(203, 45, 89, 23);
contentPane.add(btnStopf);
JButton button = new JButton("Stop(F11)");
button.setBounds(203, 81, 89, 23);
contentPane.add(button);
final JRadioButton rdbtnSeconds = new JRadioButton("Seconds");
rdbtnSeconds.setBounds(6, 81, 65, 23);
contentPane.add(rdbtnSeconds);
final JRadioButton rdbtnMilliseconds = new JRadioButton("Milliseconds");
rdbtnMilliseconds.setBounds(71, 81, 109, 23);
contentPane.add(rdbtnMilliseconds);
btnStopf.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
go = false;
}
});
JButton btnStart = new JButton("Start(F10)");
btnStart.setBounds(203, 11, 89, 23);
contentPane.add(btnStart);
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
go = true;
if (rdbtnMilliseconds.isSelected()) {
autoClick();
} else {
if (rdbtnSeconds.isSelected()) {
multiplyer = 1000;
autoClick();
}
}
}
});
}
private void autoClick() {
requestFocus();
rate = Integer.parseInt(textField.getText());
time = (rate * multiplyer);
System.out.print(time);
try {
Robot robot = new Robot();
while (true) {
try {
Thread.sleep(rate);
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
} catch (InterruptedException ex) {}
}
} catch (AWTException e) {}
}
private void keyListner(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_F10) {
System.out.print("pressed F10");
go = true;
}
if (key == KeyEvent.VK_F11) {
go = false;
}
}
private void setTheme() {
try {
UIManager
.setLookAndFeel("com.seaglasslookandfeel.SeaGlassLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void checkRate() {
if (rate < 500) {
rate = 0;
}
}
}
You are blocking the Event Dispatch Thread in autoClick() with the while(true), instead of that you can use a Swing Timer.
I suggest not using keyListener for listen only 2 keys, you can use keybindings for that purpose. Also you shouldn't call directly setBounds rely in a proper LayoutManager to position in screen.
You break out of the program loop in your Main method when you enter the wile loop in your AutoClick method.
You could instead run your program in a "game loop".
In the main method what I would do is create a method called run()
public void run()
{
int FPS = 60;
float startTime = System.currentTimeInMillis();
while(started)
{
float currentTime = System.currentTimeInMillis();
float passedTime = currentTime - startTime;
startTime = System.currentTimeInMillis();
if(passedTime > (float) 1000/FPS)
{
update();
}
}
}
and then in the update method put the logic of the program. I know it is a totally different approach to how you are currently doing it but in my opinion it allows for more flexibility.
For example in your action listener you could have it invoke a "startClick()" method
where it sets a boolean value to true and initializes what you intialzie currently in the autoclick method. Then your update() method would look like this:
public void update()
{
if(boolean) //boolean value that startClick sets to true
{
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
}
}
This way the program isn't stuck in an infinite while-loop and you can control how often it updateswith the FPS variable.

Categories