I am trying to create an java/swing based application which shows weather. So far I have created background and textfield + button to get the location but I do not know how to connect it so it shows and changes the background to another image. I am sorry if that's a noob question, but I never did java before (just processing and arduino plus web design) and my uni forced me to use advanced java with knowledge I never did anything like that before.
Here is my code so far:
package AppPackage;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ApplicationWidget extends JFrame implements ActionListener {
ImageIcon basic;
JLabel label1;
JFrame frame;
JLabel label;
JTextField textfield;
JButton button;
public static void main (String[]args){
ApplicationWidget gui = new ApplicationWidget();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setVisible(true);
gui.setSize(320, 480);
}
public ApplicationWidget() {
setLayout(new FlowLayout());
WeatherAPI weather = new WeatherAPI("44418");
System.out.println(WeatherAPI.theWeatherRSS);
for(int i = 0; i < WeatherAPI.weatherForecastList.size(); i++)
{
System.out.println(WeatherAPI.weatherForecastList.get(i).lowTemp + " " +
WeatherAPI.weatherForecastList.get(i).highTemp);
}
label = new JLabel("Welcome! Please Enter your location");
add(label);
textfield = new JTextField(15);
add(textfield);
for(int i = 0; i < WeatherAPI.weatherForecastList.size(); i++)
{
System.out.println(WeatherAPI.weatherForecastList.get(i).lowTemp + " " +
WeatherAPI.weatherForecastList.get(i).highTemp);
}
button = new JButton("Check weather");
add(button);
basic = new ImageIcon(getClass().getResource("basicback.jpg"));
label1 = new JLabel(basic);
add(label1);
/*add design here*/
/*add mouse interaction*/
/*add image capture*/
}
#Override
public void actionPerformed(ActionEvent e){
JButton button = (JButton) e.getSource();
if (e.getSource() == button){
String data = textfield.getText();
System.out.println(data);
}
}
}
And the WeatherAPI code:
package AppPackage;
import java.net.*;
import java.util.regex.*;
import java.util.ArrayList;
import java.io.*;
public class WeatherAPI
{
static String theWeatherRSS;
static String theCity;
static ArrayList<Forecast> weatherForecastList;
//WeatherAPI(String string) {
// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
// }
public class Forecast
{
String lowTemp;
String highTemp;
}
/**
*
* #param city
*/
public WeatherAPI(String city)
{
theCity = city;
theWeatherRSS = getWeatherAsRSS(city);
parseWeather(theWeatherRSS);
}
void parseWeather(String weatherHTML)
{
weatherForecastList = new ArrayList<Forecast>();
int startIndex = 0;
while(startIndex != -1)
{
startIndex = weatherHTML.indexOf("<yweather:forecast", startIndex);
if(startIndex != -1)
{ // found a weather forecast
int endIndex = weatherHTML.indexOf(">", startIndex);
String weatherForecast = weatherHTML.substring(startIndex, endIndex+1);
// get temp forecast
String lowString = getValueForKey(weatherForecast, "low");
String highString = getValueForKey(weatherForecast, "high");
Forecast fore = new Forecast();
fore.lowTemp = lowString;
fore.highTemp = highString;
weatherForecastList.add(fore);
// move to end of this forecast
startIndex = endIndex;
}
}
}
String getValueForKey(String theString, String keyString)
{
int startIndex = theString.indexOf(keyString);
startIndex = theString.indexOf("\"", startIndex);
int endIndex = theString.indexOf("\"", startIndex+1);
String resultString = theString.substring(startIndex+1, endIndex);
return resultString;
}
String getWeatherAsRSS(String city)
{
try{
/*
Adapted from: http://stackoverflow.com/questions/1381617/simplest-way-to-correctly-load-html-from-web-page-into-a-string-in-java
Answer provided by: erickson
*/
URL url = new URL("http://weather.yahooapis.com/forecastrss?w="+city+"&u=c");
URLConnection con = url.openConnection();
Pattern p = Pattern.compile("text/html;\\s+charset=([^\\s]+)\\s*");
Matcher m = p.matcher(con.getContentType());
/* If Content-Type doesn't match this pre-conception, choose default and
* hope for the best. */
String charset = m.matches() ? m.group(1) : "ISO-8859-1";
Reader r = new InputStreamReader(con.getInputStream(), charset);
StringBuilder buf = new StringBuilder();
while (true) {
int ch = r.read();
if (ch < 0)
break;
buf.append((char) ch);
}
String str = buf.toString();
return(str);
}
catch(Exception e) {System.err.println("Weather API Exception: "+e);}
return null;
}
}
Thanks for any help, I am truly desperate because I have mixed up the dates of submission and I have not much time left....
Assuming label1 is your background label, just use label1.setIcon(...). What you will pass to it is a new ImageIcon
Also you haven't registered the ActionListener to your button. If you don't register a listener to the button, it won't do anything. Do this
button = new JButton("Check weather");
button.addActionListener(this);
add(button);
You haven't specified where the new image is coming from, so I really can't help you any further than this.
Related
I have two different FileMenuHandler's for a GUI, I need a way to use the data stored in the TreeMap from FileMenuHadler in EditMenuHandler. EditMenuHandler is supposed to ask the user to enter a word and search in the TreeMap if the word exists.
I tried to create an instance of FMH in EMH but the Tree was always empty, how can I save the values of the tree once the file is opened and then use it for EditMenuHandler?
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class FileMenuHandler implements ActionListener{
JFrame jframe;//creating a local JFrame
public FileMenuHandler (JFrame jf){//passing WordGUI Jframe
jframe = jf;
}
private Container myContentPane;
private TextArea myTextArea1;
private TextArea myTextArea2;
protected ArrayList<Word> uwl = new ArrayList<Word>();
protected TreeMap<Word, String> tree;
private void readSource(File choosenFile){
String choosenFileName = choosenFile.getName();
TextFileInput inFile = new TextFileInput(choosenFileName);
myContentPane = jframe.getContentPane();
myTextArea1 = new TextArea();
myTextArea2 = new TextArea();
myTextArea1.setForeground(Color.blue);
myTextArea2.setForeground(Color.blue);
Font font = new Font("Times", Font.BOLD, 20);
myTextArea1.setFont(font);
myTextArea2.setFont(font);
myTextArea1.setBackground(Color.yellow);
myTextArea2.setBackground(Color.yellow);
String paragraph = "";
String line = inFile.readLine();
while(line != null){
paragraph += line + " ";
line = inFile.readLine();
}
StringTokenizer st = new StringTokenizer(paragraph);
tree = new TreeMap<Word,String>();
while(st.hasMoreTokens()){
String word = st.nextToken();
Word w = new Word(word);
uwl.add(w);
tree.put(w,w.data);
}
for(int i = 0; i < uwl.size(); i++){
myTextArea1.append(uwl.get(i).data + "\n");
}
myTextArea2.append(tree + "\n");
myContentPane.add(myTextArea1);
myContentPane.add(myTextArea2);
jframe.setVisible(true);
}
private void openFile(){
int status;
JFileChooser chooser = new JFileChooser("./");
status = chooser.showOpenDialog(null);
readSource(chooser.getSelectedFile());
}
//instance of edit menu handler
public void actionPerformed(ActionEvent event) {
String menuName = event.getActionCommand();
if (menuName.equals("Open")){
openFile();
}
else if (menuName.equals("Quit")){
System.exit(0);
}
} //actionPerformed
}
//
import java.awt.event.*;
public class EditMenuHandler implements ActionListener {
JFrame jframe;
public EditMenuHandler(JFrame jf) {
jframe = jf;
}
public void actionPerformed(ActionEvent event) {
String menuName = event.getActionCommand();
if (menuName.equals("Search")) {
JOptionPane.showMessageDialog(null, "Search");
}
}
}
there are many ways to do this,
you can declare a static filed (not recommended)
use RXJava or LiveData
use EventBus
use interface as a listener
....
I am not experienced, and only 14 tears old!
I made a little application, that would quiz me. Basically I would put in questions and answers in a notepad like this:
H
Hydrogen
O
Oxygen
K
Potassium
The program would sort the words like so↓, and display them in a TextArea with a ScrollPane
H = Hydrogen
O = Oxygen
K = Potassium
On the bottom theres, a JButton("Start Test"), and it would ask you the questions in order. E.g. ``H means? O Means? K Means? and then it would give you feedback E.g. Wrong! H means Hydrogen, or Correct!
here are the two classes! GUI is just simply the GUI. and the test is the class responsible for the testing
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class GUI extends JFrame
{
//JFrame components
public static JButton btn = new JButton("Start Test");
public static JPanel panelBtn = new JPanel();
public static JPanel panelTxt = new JPanel();
public static JTextArea txt = new JTextArea();
public static JScrollPane scroll = new JScrollPane(txt);
static String[] words;
static String link = "words.txt";
//constructor
public GUI()
{
//title
setTitle("Test");
//size
setSize(400,400);
//layout
setLayout(new BorderLayout());
//on close
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//OTHER
txt.setLineWrap(true);
txt.setWrapStyleWord(true);
txt.setEditable(false);
txt.setBackground(Color.white);
btn.setEnabled(false);
//border for panelTxt
LineBorder b1 = new LineBorder(Color.BLACK);
LineBorder b2 = new LineBorder(panelBtn.getBackground() ,5);
txt.setBorder(BorderFactory.createCompoundBorder(b2,b1));
//actionListnere
btn.addActionListener(new lst());
//add
add(scroll, BorderLayout.CENTER);
panelBtn.add(btn);
add(panelBtn, BorderLayout.SOUTH);
//visible
setVisible(true);
}
//action listener for btn
private class lst implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
new test(words);
GUI g = new GUI() ;
g.setVisible(false);
}
}
//main
public static void main(String[] args) throws IOException
{
new GUI();
final int ARRAY_LEN = getArrayLength();
words = makeArray(ARRAY_LEN);
displayArray(words);
btn.setEnabled(true);
}
//get the length of the array, using hasNext from Scanner class
private static int getArrayLength() throws IOException
{
File file = new File(link);
Scanner scanner = new Scanner(file);
int len = 0;
while(scanner.hasNext())
{
scanner.nextLine();
len++;
}
final int ARRAY_LEN = len +1;
return ARRAY_LEN;
}
//declares and initializes String array, with length of ARRAY_LEN
private static String[] makeArray(final int ARRAY_LEN) throws FileNotFoundException
{
String[] words = new String[ARRAY_LEN];
int value = 0;
int count = ARRAY_LEN;
words[value] = null;
count--;
value++;
File file = new File(link);
Scanner scanner = new Scanner(file);
do
{
words[value] = scanner.nextLine();
count--;
value++;
}while(count != 0);
return words;
}
//displays the array in text area
private static void displayArray(String[] words)
{
int len = words.length - 1;
int i = 0;
i++;
txt.setText(words[i]);
i++;
txt.setText(txt.getText() + "\t=");
txt.setText(txt.getText() + "\t" + words[i]);
do
{
i ++;
txt.setText(txt.getText() + "\n\n" + words[i]);
i++;
txt.setText(txt.getText() + "\t=");
txt.setText(txt.getText() + "\t" + words[i]);
}while(i != len);
}
}
Class 2
import javax.swing.*;
import java.util.Random;
public class test extends GUI
{
public static String[] words;
//constructor
public test(String[] word)
{
words = word;
main(word);
}
public static void main(String[] args)
{
int len = words.length;
boolean first = true;
for(int i = 0; i != len; i++)
{
if(first == true) //to skip null
{
i++;
first = false;
}
String question = words[i];
i++;
String answer = JOptionPane.showInputDialog(question+ " is?");
String rightAnswer = words[i];
if(answer.equals(rightAnswer))
JOptionPane.showMessageDialog(null, "Correct!");
else
{
JOptionPane.showMessageDialog(null, "Wrong! " + question +" means " + rightAnswer);
}
}
}
}
So here is the problem
Whenever I press the Button, it starts the test, but a new window from GUI class is created, and setVisible(false) doesn't actually do anything.
So there are 2 problmes;
1 setVisible(false) doesn't work.
2 a new window gets created at ButtonClikced(), so there are 2 identical windows, and closing one, closes the other too.
Please help because I don't know what to do
Remove the new GUI (); from the main method.
In your code, button was invisibled when action performe. But inthis time GUI object also was created. When the GUI object is created, it main method will be executed. There you are going to visible the button.
So change the
btn.setEnabled(true); to required another method.
Try this following code,
//main
public static void main(String[] args) throws IOException
{
final int ARRAY_LEN = getArrayLength();
words = makeArray(ARRAY_LEN);
displayArray(words);
// btn.setEnabled(true);
}
My program uses dates to check when an engineer has visited a machine. The only problem with this is that the date does not remain up to date. The date and time that the machine displays is the exact time that the machine was started. Not when the button was clicked. Any assistance would be helpful.
Code:
package com.perisic.beds.peripherals;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.management.ManagementFactory;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import javax.swing.*;
import org.apache.xmlrpc.WebServer;
import org.apache.xmlrpc.XmlRpcClient;
import com.perisic.beds.machine.CustomerPanel;
/**
* A Simple Graphical User Interface for the Recycling Machine.
* #author Group M
*
*/
public class RecyclingGUI extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = -5772727482959492839L;
//CustomerPanel myCustomerPanel = new CustomerPanel(new Display());
Display myDisplay = new Display();
ReceiptPrinter printer = new ReceiptPrinter();
ReceiptPrinter printer2 = new ReceiptPrinter();
CustomerPanel myCustomerPanel = new CustomerPanel(myDisplay);
CustomerPanel machineScreen = new CustomerPanel(printer2);
CustomerPanel theConsole = new CustomerPanel(printer);
CustomerPanel thePanel = new CustomerPanel(myDisplay);
private String storedPasswd = "123"; // needs some thinking with encryption etc
private String storedCookie = null; // some random string to be used for authentication
private String sessionCookie = "";
private int numberOfVisits;
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date date = new Date();
Date storedDate = date;
/**
* Web service to provide number of items in the machine.
* #param myCookie
* #return
*/
public int numberOfItems(String myCookie) {
if( storedCookie == null ) {
return -1;
} else if( myCookie.equals(storedCookie)) {
return myCustomerPanel.getNumberOfItems();
}
else {
return -1;
}
}
public int empty (String myCookie){
if(storedCookie == null){
return -1;
}else if(myCookie.equals(storedCookie)){
return myCustomerPanel.empty();
}else{
return -1;
}
}
/**
* Web service to authenticate the user with proper password.
* #param passwd
* #return
*/
public String login(String passwd) {
if( passwd.equals(storedPasswd)) {
storedCookie = "MC"+Math.random();
System.out.println("Engineer has logged in on: " + dateFormat.format(date));
storedDate = date;
numberOfVisits ++;
return storedCookie;
} else {
return "Incorrect Password";
}
}
public String visits(String myCookie){
if(numberOfVisits == 0){
return "Engineer has not visited this machine";
}else if(myCookie.equals(storedCookie)){
for(int i = 0; i < numberOfVisits; i++){
System.out.println("Engineer has visited on these dates: " + dateFormat.format(storedDate));
}
return storedCookie;
}else{
return "Engineer has visited on these date: " + dateFormat.format(storedDate);
}
}
/**
* Web service to logout from the system.
*/
public String logout(String myCookie ) {
if( storedCookie == null ) {
return "(no cookie set)";
} else if( myCookie.equals(storedCookie)) {
System.out.println("Engineer has logged out on: " + dateFormat.format(date));
storedCookie = null;
return "cookie deleted: OK";
}
else {
return "could not delete anything; authentication missing";
}
}
public static final String SUN_JAVA_COMMAND = "sun.java.command";
//This method is used to restart the application.
//It uses code that basically stores all of the necessary code it will need to successfully restart the application.
//Rather then just using System.exit(0) which, by itself would simply close the entire application.
//Using dispose() and new RecyclingGUI also doesn't work as it does not reload the JPanel upon restarting.
public void restartApplication(Runnable runBeforeRestart) throws IOException{
try {
String java = System.getProperty("java.home") + "/bin/java";
List<String> vmArguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
StringBuffer vmArgsOneLine = new StringBuffer();
for (String arg : vmArguments) {
if (!arg.contains("-agentlib")) {
vmArgsOneLine.append(arg);
vmArgsOneLine.append(" ");
}
}
final StringBuffer cmd = new StringBuffer("\"" + java + "\" " + vmArgsOneLine);
String[] mainCommand = System.getProperty(SUN_JAVA_COMMAND).split(" ");
if (mainCommand[0].endsWith(".jar")) {
cmd.append("-jar " + new File(mainCommand[0]).getPath());
} else {
cmd.append("-cp \"" + System.getProperty("java.class.path") + "\" " + mainCommand[0]);
}
for (int i = 1; i < mainCommand.length; i++) {
cmd.append(" ");
cmd.append(mainCommand[i]);
}
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
try {
Runtime.getRuntime().exec(cmd.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
});
if (runBeforeRestart!= null) {
runBeforeRestart.run();
}
System.exit(0);
} catch (Exception e) {
throw new IOException("Error while trying to restart the machine", e);
}
}
public void actionPerformed(ActionEvent e) {
/* Differentiate between the different buttons pressed and initiate appropriate
* actions
*/
try{
XmlRpcClient server = new XmlRpcClient("http://localhost:100");
//This code allows the engineer to login to the machine and when they do it reveals new buttons that only the engineer can use.
if (e.getSource().equals(login)){
String message;
boolean loginSuccess = false;
while(loginSuccess == false && (message = JOptionPane.showInputDialog("Login please"))!= null){
Vector parms1 = new Vector();
parms1.add(message);
Object result3 = server.execute("recycling.login", parms1);
String loginRequest = result3.toString();
if(loginRequest.equals("Wrong password")){
System.out.println("Wrong Password. Try Again!");
} else {
sessionCookie = loginRequest;
System.out.println("You are now logged in");
login.setVisible(false);
logout.setVisible(true);
reset.setVisible(true);
empty.setVisible(true);
items.setVisible(true);
loginSuccess = true;
}
}
}else if(e.getSource().equals(visits)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.visits", params);
System.out.println(result);
//This logs the engineer out of the machine and hides some of the buttons
}else if( e.getSource().equals(logout)) {
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.logout", params );
System.out.println("Logout: "+result);
reset.setVisible(false);
empty.setVisible(false);
items.setVisible(false);
login.setVisible(true);
logout.setVisible(false);
//This code tells the engineer how many items are currently in the machine.
}else if(e.getSource().equals(items)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.numberOfItems", params );
int resultInt = new Integer(result.toString());
if( resultInt == -1 ) {
System.out.println("Sorry no authentication there.");
} else {
System.out.println("There are "+resultInt+" items in the machine");
}
//This if statement empties all items that have been put into the machine thus far and sets the item number property to 0
}else if(e.getSource().equals(empty)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.empty", params);
int resultInt = new Integer(result.toString());
if(resultInt == -1){
System.out.println("Sorry no authentication there.");
}else{
System.out.println("The machine has been emptied.");
}
//This method coded above is called here.
}else if(e.getSource().equals(reset)){
restartApplication(null);
}else if(e.getSource().equals(slot1)) {
myCustomerPanel.itemReceived(1);
}else if(e.getSource().equals(slot2)) {
myCustomerPanel.itemReceived(2);
}else if(e.getSource().equals(slot3)) {
myCustomerPanel.itemReceived(3);
}else if(e.getSource().equals(slot4)) {
myCustomerPanel.itemReceived(4);
}else if(e.getSource().equals(receipt)) {
myCustomerPanel.printReceipt();
}else if(e.getSource().equals(display)) {
this.myCustomerPanel = thePanel;
}else if(e.getSource().equals(console)){
myCustomerPanel = theConsole;
}else if(e.getSource().equals(onScreen)){
//once this button is clicked all output is linked back into the GUI
myCustomerPanel = machineScreen;
redirectSystemStreams();
}
}catch (Exception exception) {
System.err.println("JavaClient: " + exception);
}
// System.out.println("Received: e.getActionCommand()="+e.getActionCommand()+
// " e.getSource()="+e.getSource().toString() );
}
//This Adds the controls (buttons) to the GUI
JButton slot1 = new JButton("Can");
JButton slot2 = new JButton("Bottle");
JButton slot3 = new JButton("Crate");
JButton slot4 = new JButton("Paper Bag");
JButton receipt = new JButton("Print Receipt");
JButton login = new JButton("Login");
JButton logout = new JButton("Logout");
JButton reset = new JButton("Reset");
JButton empty = new JButton("Empty");
JButton items = new JButton("#Items");
JButton visits = new JButton("visits");
JTextArea textArea = new JTextArea(20,30);
JScrollPane scroll = new JScrollPane(textArea);
JButton display = new JButton("Print to Display");
JButton console = new JButton("Print to GUI/Console");
JButton onScreen = new JButton("Show On Screen");
/** This creates the GUI using the controls above and
* adds the actions and listeners. this area of code also
* Contains the panel settings for size and some behaviours.
*/
public RecyclingGUI() {
super();
setSize(500, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(slot1);
panel.add(slot2);
panel.add(slot3);
panel.add(slot4);
slot1.addActionListener(this);
slot2.addActionListener(this);
slot3.addActionListener(this);
slot4.addActionListener(this);
panel.add(receipt);
receipt.addActionListener(this);
panel.add(display);
display.addActionListener(this);
panel.add(console);
console.addActionListener(this);
panel.add(onScreen);
onScreen.addActionListener(this);
/**Text Area controls for size, font style, font size
* the text area also has a scroll bar just in case the user enters
* a large number of items
*/
panel.add(scroll);
textArea.setLineWrap(true);
textArea.setEditable(false);
textArea.setFont(new Font("Ariel",Font.PLAIN, 14));
scroll.setPreferredSize(new Dimension(450, 450));
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
panel.add(login);
login.addActionListener(this);
panel.add(logout);
logout.setVisible(false);
logout.addActionListener(this);
panel.add(reset);
reset.setVisible(false);
reset.addActionListener(this);
panel.add(items);
items.setVisible(false);
items.addActionListener(this);
panel.add(empty);
empty.setVisible(false);
empty.addActionListener(this);
panel.add(visits);
visits.addActionListener(this);
getContentPane().add(panel);
panel.repaint();
}
public static void main(String [] args ) {
RecyclingGUI myGUI = new RecyclingGUI();
myGUI.setVisible(true);
try {
System.out.println("Starting the Recycling Server...");
WebServer server = new WebServer(100);
server.addHandler("recycling", myGUI);
server.start();
} catch (Exception exception) {
System.err.println("JavaServer: " + exception);
}
}
/** This is the code that redirects where the code is displayed
* from the console to the textArea of the GUI. it does this by
* creating a new set of output streams (for text and errors) which
* are set as default when the redirectSystemStream method is called.
* (from a previous piece of work i did in my FDg, source = from a tutorial)
*/
public void updateTextArea(final String text) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(text);
}
});
}
public void redirectSystemStreams() {
OutputStream out = new OutputStream() {
#Override
public void write(int b) throws IOException {
updateTextArea(String.valueOf((char) b));
}
#Override
public void write(byte[] b, int off, int len) throws IOException {
updateTextArea(new String(b, off, len));
}
#Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
};
System.setOut(new PrintStream(out, true));
System.setErr(new PrintStream(out, true));
}
public void print(String str) {
System.out.println(str);
}
}
You never re-initialize date, you're just updating storedDate with the existing date in login. You could change this line in login
storedDate = date;
to
storedDate = new Date();
And then (I think) you can remove date.
Date does not keep a persistent current time. Date is backed by a long that is set when the Date is instantiated and is never changed.
You can either make a new Date() in your logon method, so it would be created when the user logs on, or just use System.currentTimeMillis() to get the current time as a long.
I have been tasked with creating a recycling machine server which a engineer can log into empty, reset, etc. Each time the engineer logs into a machine it creates a string that says "Engineer has logged in on this (date)". I need to create a JButton that prints out each instance of this string being written.
So when pressed it prints out something like this:
"Engineer visited this machine on 01/01/2016"
"Engineer visited this machine on 02/01/2016"
"Engineer visited this machine on 05/04/2016"
The log in function is working and uses stored cookies to figure out if the user has input the correct information. I am however unable to figure out how to print out this summary of visits via one button click. Any help would be appreciated.
Code:
package com.perisic.beds.peripherals;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.management.ManagementFactory;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import javax.swing.*;
import org.apache.xmlrpc.WebServer;
import org.apache.xmlrpc.XmlRpcClient;
import com.perisic.beds.machine.CustomerPanel;
/**
* A Simple Graphical User Interface for the Recycling Machine.
* #author Group M
*
*/
public class RecyclingGUI extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = -5772727482959492839L;
//CustomerPanel myCustomerPanel = new CustomerPanel(new Display());
Display myDisplay = new Display();
ReceiptPrinter printer = new ReceiptPrinter();
ReceiptPrinter printer2 = new ReceiptPrinter();
CustomerPanel myCustomerPanel = new CustomerPanel(myDisplay);
CustomerPanel machineScreen = new CustomerPanel(printer2);
CustomerPanel theConsole = new CustomerPanel(printer);
CustomerPanel thePanel = new CustomerPanel(myDisplay);
private String storedPasswd = "123"; // needs some thinking with encryption etc
private String storedCookie = null; // some random string to be used for authentication
private String sessionCookie = "";
private int numberOfVisits = 0;
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date date = new Date();
Date storedDate = new Date();
/**
* Web service to provide number of items in the machine.
* #param myCookie
* #return
*/
public int numberOfItems(String myCookie) {
if( storedCookie == null ) {
return -1;
} else if( myCookie.equals(storedCookie)) {
return myCustomerPanel.getNumberOfItems();
}
else {
return -1;
}
}
public int empty (String myCookie){
if(storedCookie == null){
return -1;
}else if(myCookie.equals(storedCookie)){
return myCustomerPanel.empty();
}else{
return -1;
}
}
/**
* Web service to authenticate the user with proper password.
* #param passwd
* #return
*/
public String login(String passwd) {
if( passwd.equals(storedPasswd)) {
storedCookie = "MC"+Math.random();
System.out.println("Engineer has logged in on: " + dateFormat.format(date));
storedDate = date;
numberOfVisits ++;
return storedCookie;
} else {
return "Incorrect Password";
}
}
public String visits(String myCookie){
if(numberOfVisits == 0){
return "Engineer has not visited this machine";
}else if(myCookie.equals(storedCookie)){
for(int i = 0; i < numberOfVisits; i++){
System.out.println("Engineer has visited on these dates: " + dateFormat.format(storedDate));
}
return storedCookie;
}else{
return "Engineer has visited on these date: " + dateFormat.format(storedDate);
}
}
/**
* Web service to logout from the system.
*/
public String logout(String myCookie ) {
if( storedCookie == null ) {
return "(no cookie set)";
} else if( myCookie.equals(storedCookie)) {
System.out.println("Engineer has logged out on: " + dateFormat.format(date));
storedCookie = null;
return "cookie deleted: OK";
}
else {
return "could not delete anything; authentication missing";
}
}
public static final String SUN_JAVA_COMMAND = "sun.java.command";
//This method is used to restart the application.
//It uses code that basically stores all of the necessary code it will need to successfully restart the application.
//Rather then just using System.exit(0) which, by itself would simply close the entire application.
//Using dispose() and new RecyclingGUI also doesn't work as it does not reload the JPanel upon restarting.
public void restartApplication(Runnable runBeforeRestart) throws IOException{
try {
String java = System.getProperty("java.home") + "/bin/java";
List<String> vmArguments = ManagementFactory.getRuntimeMXBean().getInputArguments();
StringBuffer vmArgsOneLine = new StringBuffer();
for (String arg : vmArguments) {
if (!arg.contains("-agentlib")) {
vmArgsOneLine.append(arg);
vmArgsOneLine.append(" ");
}
}
final StringBuffer cmd = new StringBuffer("\"" + java + "\" " + vmArgsOneLine);
String[] mainCommand = System.getProperty(SUN_JAVA_COMMAND).split(" ");
if (mainCommand[0].endsWith(".jar")) {
cmd.append("-jar " + new File(mainCommand[0]).getPath());
} else {
cmd.append("-cp \"" + System.getProperty("java.class.path") + "\" " + mainCommand[0]);
}
for (int i = 1; i < mainCommand.length; i++) {
cmd.append(" ");
cmd.append(mainCommand[i]);
}
Runtime.getRuntime().addShutdownHook(new Thread() {
#Override
public void run() {
try {
Runtime.getRuntime().exec(cmd.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
});
if (runBeforeRestart!= null) {
runBeforeRestart.run();
}
System.exit(0);
} catch (Exception e) {
throw new IOException("Error while trying to restart the machine", e);
}
}
public void actionPerformed(ActionEvent e) {
/* Differentiate between the different buttons pressed and initiate appropriate
* actions
*/
try{
XmlRpcClient server = new XmlRpcClient("http://localhost:100");
//This code allows the engineer to login to the machine and when they do it reveals new buttons that only the engineer can use.
if (e.getSource().equals(login)){
String message;
boolean loginSuccess = false;
while(loginSuccess == false && (message = JOptionPane.showInputDialog("Login please"))!= null){
Vector parms1 = new Vector();
parms1.add(message);
Object result3 = server.execute("recycling.login", parms1);
String loginRequest = result3.toString();
if(loginRequest.equals("Wrong password")){
System.out.println("Wrong Password. Try Again!");
} else {
sessionCookie = loginRequest;
System.out.println("You are now logged in");
login.setVisible(false);
logout.setVisible(true);
reset.setVisible(true);
empty.setVisible(true);
items.setVisible(true);
loginSuccess = true;
}
}
}else if(e.getSource().equals(visits)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.visits", params);
System.out.println(result);
//This logs the engineer out of the machine and hides some of the buttons
}else if( e.getSource().equals(logout)) {
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.logout", params );
System.out.println("Logout: "+result);
reset.setVisible(false);
empty.setVisible(false);
items.setVisible(false);
login.setVisible(true);
logout.setVisible(false);
//This code tells the engineer how many items are currently in the machine.
}else if(e.getSource().equals(items)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.numberOfItems", params );
int resultInt = new Integer(result.toString());
if( resultInt == -1 ) {
System.out.println("Sorry no authentication there.");
} else {
System.out.println("There are "+resultInt+" items in the machine");
}
//This if statement empties all items that have been put into the machine thus far and sets the item number property to 0
}else if(e.getSource().equals(empty)){
Vector params = new Vector();
params.add(sessionCookie);
Object result = server.execute("recycling.empty", params);
int resultInt = new Integer(result.toString());
if(resultInt == -1){
System.out.println("Sorry no authentication there.");
}else{
System.out.println("The machine has been emptied.");
}
//This method coded above is called here.
}else if(e.getSource().equals(reset)){
restartApplication(null);
}else if(e.getSource().equals(slot1)) {
myCustomerPanel.itemReceived(1);
}else if(e.getSource().equals(slot2)) {
myCustomerPanel.itemReceived(2);
}else if(e.getSource().equals(slot3)) {
myCustomerPanel.itemReceived(3);
}else if(e.getSource().equals(slot4)) {
myCustomerPanel.itemReceived(4);
}else if(e.getSource().equals(receipt)) {
myCustomerPanel.printReceipt();
}else if(e.getSource().equals(display)) {
this.myCustomerPanel = thePanel;
}else if(e.getSource().equals(console)){
myCustomerPanel = theConsole;
}else if(e.getSource().equals(onScreen)){
//once this button is clicked all output is linked back into the GUI
myCustomerPanel = machineScreen;
redirectSystemStreams();
}
}catch (Exception exception) {
System.err.println("JavaClient: " + exception);
}
// System.out.println("Received: e.getActionCommand()="+e.getActionCommand()+
// " e.getSource()="+e.getSource().toString() );
}
//This Adds the controls (buttons) to the GUI
JButton slot1 = new JButton("Can");
JButton slot2 = new JButton("Bottle");
JButton slot3 = new JButton("Crate");
JButton slot4 = new JButton("Paper Bag");
JButton receipt = new JButton("Print Receipt");
JButton login = new JButton("Login");
JButton logout = new JButton("Logout");
JButton reset = new JButton("Reset");
JButton empty = new JButton("Empty");
JButton items = new JButton("#Items");
JButton visits = new JButton("visits");
JTextArea textArea = new JTextArea(20,30);
JScrollPane scroll = new JScrollPane(textArea);
JButton display = new JButton("Print to Display");
JButton console = new JButton("Print to GUI/Console");
JButton onScreen = new JButton("Show On Screen");
/** This creates the GUI using the controls above and
* adds the actions and listeners. this area of code also
* Contains the panel settings for size and some behaviours.
*/
public RecyclingGUI() {
super();
setSize(500, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(slot1);
panel.add(slot2);
panel.add(slot3);
panel.add(slot4);
slot1.addActionListener(this);
slot2.addActionListener(this);
slot3.addActionListener(this);
slot4.addActionListener(this);
panel.add(receipt);
receipt.addActionListener(this);
panel.add(display);
display.addActionListener(this);
panel.add(console);
console.addActionListener(this);
panel.add(onScreen);
onScreen.addActionListener(this);
/**Text Area controls for size, font style, font size
* the text area also has a scroll bar just in case the user enters
* a large number of items
*/
panel.add(scroll);
textArea.setLineWrap(true);
textArea.setEditable(false);
textArea.setFont(new Font("Ariel",Font.PLAIN, 14));
scroll.setPreferredSize(new Dimension(450, 450));
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
panel.add(login);
login.addActionListener(this);
panel.add(logout);
logout.setVisible(false);
logout.addActionListener(this);
panel.add(reset);
reset.setVisible(false);
reset.addActionListener(this);
panel.add(items);
items.setVisible(false);
items.addActionListener(this);
panel.add(empty);
empty.setVisible(false);
empty.addActionListener(this);
panel.add(visits);
visits.addActionListener(this);
getContentPane().add(panel);
panel.repaint();
}
public static void main(String [] args ) {
RecyclingGUI myGUI = new RecyclingGUI();
myGUI.setVisible(true);
try {
System.out.println("Starting the Recycling Server...");
WebServer server = new WebServer(100);
server.addHandler("recycling", myGUI);
server.start();
} catch (Exception exception) {
System.err.println("JavaServer: " + exception);
}
}
/** This is the code that redirects where the code is displayed
* from the console to the textArea of the GUI. it does this by
* creating a new set of output streams (for text and errors) which
* are set as default when the redirectSystemStream method is called.
* (from a previous piece of work i did in my FDg, source = from a tutorial)
*/
public void updateTextArea(final String text) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(text);
}
});
}
public void redirectSystemStreams() {
OutputStream out = new OutputStream() {
#Override
public void write(int b) throws IOException {
updateTextArea(String.valueOf((char) b));
}
#Override
public void write(byte[] b, int off, int len) throws IOException {
updateTextArea(new String(b, off, len));
}
#Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
};
System.setOut(new PrintStream(out, true));
System.setErr(new PrintStream(out, true));
}
public void print(String str) {
System.out.println(str);
}
}
So after working around with the code for a while I discovered that there was one simple piece of code that was causing it to not display the information I wanted.
private int numberOfVisits = 0;
Defining the int as a 0 to begin with caused the code to reset the value of the int every time I pressed the "visits" button.
Removing the 0 fixed this issue.
private int numberOfVisits;
So I am trying to highlight the keywords in java,which I have stored in a text file, as the user opens a .java file or writes to .java file. I think I know how to tell if the file is of the right type. However, I do not know how to change the color of certain keywords. If anyone could help out that would be great because right now it's pretty confusing. I was wondering if I could use my replace function somehow. I have tried to go about trying to do this with the few methods I have, yet it's still not clear. I have taken out he majority of the methods and listeners, just know they are there but kept out to make it easier to read.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.DocumentListener;
import javax.swing.event.DocumentEvent;
import java.util.Scanner;
import java.io.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
import javax.swing.text.Highlighter.HighlightPainter;
import javax.swing.text.JTextComponent;
import java.net.URI;
import java.util.*;
public class MyTextEditor extends JFrame implements ActionListener
{
private JPanel panel = new JPanel(new BorderLayout());
private JTextArea textArea = new JTextArea(0,0);
private static final Color TA_BKGRD_CL = Color.BLACK;
private static final Color TA_FRGRD_CL = Color.GREEN;
private static final Color TA_CARET_CL = Color.WHITE;
private JScrollPane scrollPane;
private MenuBar menuBar = new MenuBar();
public MyTextEditor()
{
this.setSize(750,800);
this.setTitle("Zenith");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textArea.setFont(new Font("Consolas", Font.BOLD, 14));
textArea.setForeground(TA_FRGRD_CL);
textArea.setBackground(TA_BKGRD_CL);
textArea.setCaretColor(TA_CARET_CL);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
scrollPane.setVisible(true);
textArea.add(scrollPane,BorderLayout.EAST);
final LineNumberingTextArea lineNTA = new LineNumberingTextArea(textArea);
DocumentListener documentListen = new DocumentListener()
{
public void insertUpdate(DocumentEvent documentEvent)
{
lineNTA.updateLineNumbers();
}
public void removeUpdate(DocumentEvent documentEvent)
{
lineNTA.updateLineNumbers();
}
public void changedUpdate(DocumentEvent documentEvent)
{
lineNTA.updateLineNumbers();
}
};
textArea.getDocument().addDocumentListener(documentListen);
// Line numbers
lineNTA.setBackground(Color.BLACK);
lineNTA.setForeground(Color.WHITE);
lineNTA.setFont(new Font("Consolas", Font.BOLD, 13));
lineNTA.setEditable(false);
lineNTA.setVisible(true);
textArea.add(lineNTA);
scrollPane.setVisible(true);
scrollPane.add(textArea);
getContentPane().add(scrollPane);
}
public void findKeyWords(String ext)
{
ArrayList<String> wordsInTA = new ArrayList<String>();
int index = 0;
if(ext == "java")
{
for(String line : textArea.getText().split(" "))
{
wordsInTA.add(line);
index++;
}
try
{
while(index>0)
{
String temp = wordsInTA.get(index);
boolean isKeyWord = binarySearch(temp);
if(isKeyWord)
{
//Code that has not yet been made
}
index--;
}
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
}
private ArrayList<String> loadJavaWords() throws FileNotFoundException
{
ArrayList<String> javaWords = new ArrayList<String>();
Scanner scan = new Scanner(new File("JavaKeyWords.txt"));
while(scan.hasNext())
{
javaWords.add(scan.next());
}
scan.close();
return javaWords;
}
private boolean binarySearch(String word) throws FileNotFoundException
{
ArrayList<String> javaWords = loadJavaWords();
int min = 0;
int max = javaWords.size()-1;
while(min <= max)
{
int index = (max + min)/2;
String guess = javaWords.get(index);
int result = word.compareTo(guess);
if(result == 0)
{
return true;
}
else if(result > 0)
{
min = index +1;
}
else if(result < 0)
{
max = index -1;
}
}
return false;
}
public void replace()
{
String wordToSearch = JOptionPane.showInputDialog(null, "Word to replace:");
String wordToReplace = JOptionPane.showInputDialog(null, "Replacement word:");
int m;
int total = 0;
int wordLength = wordToSearch.length();
for (String line : textArea.getText().split("\\n"))
{
m = line.indexOf(wordToSearch);
if(m == -1)
{
total += line.length() + 1;
continue;
}
String newLine = line.replaceAll(wordToSearch, wordToReplace);
textArea.replaceRange(newLine, total, total + line.length());
total += newLine.length() + 1;
}
}
public static void main(String args[])
{
MyTextEditor textEditor = new MyTextEditor();
textEditor.setVisible(true);
}
}