A friend recently asked me to make a simple Buzzer program and has found a strange "bug" in what I wrote for him.
If a key is pushed and the buzzer is reset rapidly over the course of a few seconds he observes a 2 to 3 second freeze of the program that occurs between the the first key press after the reset and the "buzz" indication. He has the following Java installation:
build 1.7.0_25-b16
However, I do not experience this problem on my computer, with the following Java installation:
$ java -version
java version "1.6.0_51"
Java(TM) SE Runtime Environment (build 1.6.0_51-b11-457-10M4509)
Java HotSpot(TM) 64-Bit Server VM (build 20.51-b01-457, mixed mode)
Upon unfreeze, the program returns the appropriate key (that is, not the last key pressed, but the first one pushed after the reset and before the freeze). This suggests that the problem is not with the listener but with the reaction to the listener.
Any thoughts on what might be causing this phenomenon? Thanks in advance for your help.
Source code:
/**
* Buzzer.java
*
* Buzzer
*/
package org.lexingtonma.lhs.nhb;
import java.awt.Color;
import java.awt.DefaultKeyboardFocusManager;
import java.awt.Font;
import java.awt.KeyEventDispatcher;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* #author Arman D. Bilge
*
*/
public class Buzzer extends JFrame implements KeyListener {
private static final long serialVersionUID = 7492374642744742658L;
private static final String BUZZ_A = "BuzzA.wav";
private static final String BUZZ_B = "BuzzB.wav";
private Clip buzz = null;
private boolean listening = true;
private final JTextField display = new JTextField(3);
private final JButton reset = new JButton("Reset");
{
DefaultKeyboardFocusManager.getCurrentKeyboardFocusManager()
.addKeyEventDispatcher(new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent e) {
keyTyped(e);
return false;
}
});
setTitle("Buzzer");
final JPanel panel = new JPanel();
setSize(256, 162);
setDefaultCloseOperation(EXIT_ON_CLOSE);
display.setFont(new Font("Helvetica", Font.BOLD, 64));
display.setForeground(Color.WHITE);
display.setVisible(true);
display.setEditable(false);
display.setHorizontalAlignment(JTextField.CENTER);
panel.add(display);
reset.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
display.setText("");
display.setBackground(Color.WHITE);
listening = true;
reset.setEnabled(false);
}
});
reset.setEnabled(false);
panel.add(reset);
add(panel);
try {
buzz = AudioSystem.getClip();
} catch (LineUnavailableException e) {
JOptionPane.showMessageDialog(this, e.getLocalizedMessage(), "FATAL ERROR", JOptionPane.ERROR_MESSAGE);
}
}
public static final void main(String args[]) {
Buzzer b = new Buzzer();
b.setVisible(true);
}
public void keyPressed(KeyEvent e) {
// Do nothing
}
public void keyReleased(KeyEvent e) {
// Do nothing
}
public void keyTyped(KeyEvent e) {
final char c = e.getKeyChar();
if (listening && Character.isLetterOrDigit(c)) {
buzz.close();
listening = false;
if (Character.isDigit(c)) {
display.setBackground(Color.RED);
try {
buzz.open(AudioSystem.getAudioInputStream(getClass().getResource(BUZZ_A)));
buzz.start();
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, ex.getLocalizedMessage(), "FATAL ERROR", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
} else {
display.setBackground(Color.BLUE);
try {
buzz.open(AudioSystem.getAudioInputStream(getClass().getResource(BUZZ_B)));
buzz.start();
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, ex.getLocalizedMessage(), "FATAL ERROR", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
}
display.setText("" + c);
reset.setEnabled(true);
}
}
}
Jar: https://www.dropbox.com/s/62fl2i97m9hrx9m/Buzzer.jar
It's safer to create a new Clip object every time and discard the old one. Try this method
public static void play(String name) {
try{
AudioInputStream sounds = AudioSystem.getAudioInputStream(Buzzer.class.getResource(name));
final Clip clip = AudioSystem.getClip();
clip.addLineListener(new LineListener() {
public void update(LineEvent e) {
LineEvent.Type type = e.getType();
if(type == type.STOP) clip.close();
}
});
clip.open(sounds);
clip.start();
} catch(Exception e){
e.printStackTrace();
}
}
As was suggested, you could give keybinding a try to see if it helps. This just shows how to do it with the Enter key.
public class Buzzer extends JFrame {
private static final String enter = "ENTER";
public Buzzer() {
// Key bound AbstractAction item
enterAction = new EnterAction();
// Gets the JFrame InputMap and pairs the key to the action
this.getInputMap().put(KeyStroke.getKeyStroke(enter), "doEnterAction");
// This line pairs the AbstractAction enterAction to the action "doEnterAction"
this.getActionMap().put("doEnterAction", enterAction);
}
private class EnterAction extends AbstractAction {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Enter was pressed.");
}
}
}
Actually I can't remember if this will work when applied to a JFrame, you might need to make a JPanel first to apply these to. Just replace 'this' with the panel name.
Related
I have created a Java application that goes through hundreds of documents after user clicks "Run" button. Is there a way to terminate the program and leave the GUI running? All I want to be able to stop is the process of reading the documents.
System.exit(0) is not the solution I am looking for as my whole app closes.
It's difficult to say something without to see your application. But probably this piece of code will help you to understand how to implement what you want:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;
import javax.swing.WindowConstants;
public class SwingWorkerTest implements Runnable {
private JButton cancelButton = new JButton("Cancel");
private JButton runButton = new JButton("Run");
private JLabel label = new JLabel("Press 'Run' to start");
private LongWorker longWorker;
#Override
public void run() {
JFrame frm = new JFrame("Long task test");
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
cancelButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
longWorker.terminate();
}
});
runButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
longWorker = new LongWorker();
runButton.setEnabled(false);
cancelButton.setEnabled(true);
label.setText("Task in progress. Press 'Cancel' to terminate.");
longWorker.execute();
}
});
JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
bottomPanel.add(runButton);
bottomPanel.add(cancelButton);
frm.add(label);
frm.add(bottomPanel, BorderLayout.SOUTH);
frm.setSize(400, 200);
frm.setLocationRelativeTo(null);
frm.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new SwingWorkerTest());
}
private class LongWorker extends SwingWorker<Void, Void> {
private volatile boolean terminated;
#Override
protected Void doInBackground() throws Exception {
// check special variable tov determine whether this task still active
for (int i = 0; i < 1000 && !terminated; i++) {
readFile();
}
return null;
}
#Override
protected void done() {
if (terminated) {
label.setText("Process terminated. Press 'Run' to restart.");
} else {
label.setText("Process done. Press 'Run' to restart.");
}
cancelButton.setEnabled(false);
runButton.setEnabled(true);
}
// dummy method - make 10 milliseconds sleep
private void readFile() {
try {
Thread.sleep(10);
} catch (InterruptedException ex) {
// Nothing here
}
}
public void terminate() {
terminated = true;
}
}
}
I have 2 separate classes. One is a magic 8 ball, the other is a Wav player that plays the Interstellar song.
import java.security.SecureRandom;
import javax.swing.JOptionPane;
import javax.swing.ImageIcon;
public class Magic8Ball {
private final static ImageIcon image = new ImageIcon("images/BuckminsterFuller.jpg");
private final static SecureRandom rand = new SecureRandom();
private final static String wisdom[] = {
"Not Synergistically feasible",
"It is geometrically analytical",
"Your question does not follow General Semantics, hazy, try again",
"Yes - Sustainable",
"No, energetically inefficient",
"Maybe a Dymaxion process. Technology not up to date.",
"Your question is negatively Entropic.",
"Everyone is born a genius, but the process of living de-geniuses them.",
"Humanity is acquiring all the right technology for all the wrong reasons.",
"We are called to be architects of the future, not its victims",};
public static void main(String[] args) {
boolean askQ = true;
while (askQ) {
String question = getUserQ();
String randomWisdom = getRandomWisdom();
showWisdom(question, randomWisdom);
askQ = userWantsToAskAnotherQ();
}
}
private static String getUserQ() {
return JOptionPane.showInputDialog(null,
"Ask a question that has to do with the structural integrity of earth:",
"Only Engineers, Scientists and Architects allowed",
JOptionPane.INFORMATION_MESSAGE);
}
private static String getRandomWisdom() {
return wisdom[rand.nextInt(wisdom.length)];
}
private static void showWisdom(String question, String randomWisdom) {
JOptionPane.showMessageDialog(null, question + "\n" + randomWisdom,
"Buckminster's Magic-8 Ball has responded.",
JOptionPane.PLAIN_MESSAGE, image);
}
private static boolean userWantsToAskAnotherQ() {
return 0 == JOptionPane.showConfirmDialog(null, "Abort Mission or Dock "
+ "while Hearing" + "\n" + "No Time for Caution? by Hans Zimmer",
"Would you like to stay on spaceship earth or abandon ship?",
JOptionPane.YES_NO_OPTION, 0, image);
}
}
So as you can see at the end of the Class the option is to abort mission or dock while hearing Hans Zimmer No time for caution. So if the user hits Yes, how can i have it active or call this class that i have for the interstellar song:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import javax.swing.*;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
public class WavPlayer extends JFrame {
JButton btn = new JButton("Play No Time For Caution");
File wavFile;
URL defaultSound;
public static Clip clip;
public static AudioInputStream audioInputStream;
public WavPlayer(String url) {
try {
setSize(300, 100);
setLocation(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel jp = new JPanel();
defaultSound = new URL (url);
jp.add(btn);
getContentPane().add(jp);
pack();
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
play();
}
});
} catch (MalformedURLException ex) {
Logger.getLogger(WavPlayer.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void play() {
try {
audioInputStream = AudioSystem.getAudioInputStream(defaultSound);
try {
clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.loop(20000);
clip.start();
} catch (LineUnavailableException e) {
}
} catch (UnsupportedAudioFileException | IOException e) {
}
}
public void stop() {
clip.stop();
}
public static void main(String args[]) {
WavPlayer t = new WavPlayer("file:C:/Users/borjax01/Desktop/Netbeans/JavaApplication/music/Interstellar.wav");
t.setVisible(true);
}
}
Edit: I already combined these 2 classes by refactoring and moving one class into the other. What i want done is that i want the 8ball class to call upon the WavPlayer class when at the end of the 8ball class, when the user gets prompted to play again, and they hit "yes" to activate the wavplayer class.....
What error did you get? "Inner classes cannot have static declarations" perhaps?
You can try another approach. Instead of nesting the wav player class, insert if after the Magic8Ball class. Both classes can exist in the same file, but as you know, only one of them may be public.
Now that both classes are present you might try something like this:
value = JOptionPane.showConfirmDialog(...)
if (value == JOptionPane.YES_OPTION) {
WavPlayer t = new WavPlayer("file:C:/Users/borjax01/Desktop/Netbeans/JavaApplication/music/Interstellar.wav");
t.setVisible(true);
}
The following is my program. the goal is to convert from a roman numeral to an Arabic number after a user types in the numeral and presses the enter key.
This is a homework assignment and we are forced to user JTextAreas in lieu of JTextFields.
My error exists on the line: enterRomanNumber.addActionListener(handler);
The error reads:
"The method addActionListener(ArabicToRomanGUI.HandlerForTextArea) is
undefined for the type JTextArea"
I can't seem to figure out why I am getting this error or how to correct it, can someone please advise.
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class ArabicToRomanGUI extends JFrame
{
private static final long serialVersionUID = 1L;
private JTextArea enterRomanNumber = new JTextArea();
JLabel label = new JLabel();
JPanel panel = new JPanel();
JFrame frame = new JFrame();
//TestArea contructor adds jtextArea to jframe
public ArabicToRomanGUI()
{
super("Convert a Roman Numeral");
setLayout(new FlowLayout());
//Text field to enter a roman numeral
enterRomanNumber = new JTextArea(1,25);
enterRomanNumber.setText("Delete this text and Enter a Roman Numerial Here!");
//enterRomanNumber.setAlignmentX(0);
//enterRomanNumber.setAlignmentY(0);
add(enterRomanNumber);
HandlerForTextArea handler = new HandlerForTextArea();
enterRomanNumber.addActionListener(handler);
}
private class HandlerForTextArea implements ActionListener
{
//used to process textArea events
#Override
public void actionPerformed(ActionEvent e)
{
String userInput = "";
userInput = enterRomanNumber.getText();
userInput = userInput.toUpperCase();
ConversionLogic.ConvertFromRomanToArabic(userInput); //converts user string of Roman numerals to an int in arabic
String arabicNumberAsString = ConversionLogic.getConvertedRomanNumeral();
enterRomanNumber.setText(arabicNumberAsString);
//user pressed enter in JTextField enterNumberField
if(e.getSource() == enterRomanNumber)
{
//enterRomanNumber.setText(arabicNumberAsString);
if (ConversionLogic.getCheckFail() == true)
{
JOptionPane.showMessageDialog(frame, "The Roman Numeral entered is Invalid", "Error", JOptionPane.ERROR_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(frame, "The arabic equivalent is " + arabicNumberAsString + "." , "Conversion Successful", JOptionPane.PLAIN_MESSAGE);
}
}
}
}
}//end inner class TextAreaHandler
For a better answer, see #MadProgrammer 's answer.
My solution:
There is no ActionListener for JTextArea.
So just use KeyListener instead
HandlerForTextArea handler = new HandlerForTextArea();
enterRomanNumber.addKeyListener(handler);
Implements KeyListener
private class HandlerForTextArea implements KeyListener
{
#Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
if (arg0.getKeyCode() == VK_ENTER){
// TODO Your bussiness
}
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
KeyListeners are NEVER appropriate solutions to use with text components, if you want to be notified when a text component changes, you use a DocumentListener, if you want to change/filter what can be entered into a text component, you use a DocumentFilter, if you need to change a special key, like Enter, you should use a key binding
See How to Use Key Bindings for more details.
One of the problems you could have with KeyListener is not knowing when the key stroke is processed by the text component, in your case, it may not be a major issue, but it could change the way the program works on different platforms.
Instead, you can override the JTextArea's key binding for the Enter key (named insert-break). This provides you with the ability to actually change the behavior of the key stroke, or, in your case, manage how you process the event. For example, this replaces the Action for the text area's Enter key, but retains the previous/default behavior...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class KeyBindingsTest {
public static void main(String[] args) {
new KeyBindingsTest();
}
public KeyBindingsTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextArea ta;
public TestPane() {
ta = new JTextArea(10, 20);
ActionMap am = ta.getActionMap();
Action proxy = am.get("insert-break");
am.put("insert-break", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
// You can process the event through the original action BEFORE
// you do your own processing
//proxy.actionPerformed(e);
System.out.println("You pressed the enter key, you can have candy");
// Or you can process the event through the original action AFTER
// you do your own processing, you have now gained control
proxy.actionPerformed(e);
}
});
setLayout(new BorderLayout());
add(ta);
}
}
}
Now, you could even go to the extent for creating your own JTextArea which supported ActionPerformed...
public class ActionableTextArea extends JTextArea {
private String actionCommand;
public ActionableTextArea() {
installKeyBindings();
}
public ActionableTextArea(String text) {
super(text);
installKeyBindings();
}
public ActionableTextArea(int rows, int columns) {
super(rows, columns);
installKeyBindings();
}
public ActionableTextArea(String text, int rows, int columns) {
super(text, rows, columns);
installKeyBindings();
}
public ActionableTextArea(Document doc) {
super(doc);
installKeyBindings();
}
public ActionableTextArea(Document doc, String text, int rows, int columns) {
super(doc, text, rows, columns);
installKeyBindings();
}
protected void installKeyBindings() {
ActionMap am = getActionMap();
Action proxy = am.get("insert-break");
am.put("insert-break", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
// You can process the event through the original action BEFORE
// you do your own processing
//proxy.actionPerformed(e);
fireActionPerformed();
// Or you can process the event through the original action AFTER
// you do your own processing, you have now gained control
proxy.actionPerformed(e);
}
});
}
public void addActionListener(ActionListener listener) {
listenerList.add(ActionListener.class, listener);
}
public void removeActionListener(ActionListener listener) {
listenerList.remove(ActionListener.class, listener);
}
public void setActionCommand(String actionCommand) {
this.actionCommand = actionCommand;
}
public String getActionCommand() {
return actionCommand;
}
protected void fireActionPerformed() {
ActionListener[] listeners = listenerList.getListeners(ActionListener.class);
if (listeners.length > 0) {
ActionEvent evt = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, getActionCommand());
for (ActionListener listener : listeners) {
listener.actionPerformed(evt);
}
}
}
}
I want to have a button that, when clicked, opens the default browser and points to a URI.
I have some code that works in my testing, when run in Netbeans 7.x, but it fails when deployed as a JAR. My Java app runs on Linux only.
Anyone see the problem or know of another solution?
This code is in my main form:
linkBtnTest = new LinkButton(
new URI("http://www.example.com/some-page"),
"Click here for blah blah blah");
linkBtnTest.init();
} catch (Exception ex) {
Logger.log(ex);
}
Accessibility.increaseFontSize(linkBtnTest,
ApplicationContext.get().getFontIncreaseSize());
TestPanel.add(linkBtnTest);
Here's the class. I didn't write this code and I'm open to other suggestions:
package com.example.client;
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URI;
import javax.swing.JButton;
public class LinkButton extends JButton
implements ActionListener {
/** The target or href of this link. */
private URI target;
final static private String defaultText = "<HTML>Click the <FONT color=\"#000099\"><U>link</U></FONT>"
+ " to go to the example website.</HTML>";
public LinkButton(URI target, String text) {
super(text);
this.target = target;
//this.setText(text);
this.setToolTipText(target.toString());
}
public LinkButton(URI target) {
this( target, target.toString() );
}
public void init() {
this.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
open(target);
}
class OpenUrlAction implements ActionListener {
#Override public void actionPerformed(ActionEvent e) {
open(target);
}
}
private static void open(URI uri) {
if (Desktop.isDesktopSupported()) {
try {
Desktop.getDesktop().browse(uri);
} catch (IOException e) { /* TODO: error handling */ }
} else { /* TODO: error handling */ }
}
}
}
I am attempting to print to my JTextArea from another class. I have the class ActivityLogger call method Alert inside of my main class Risk_Mgnt_Manager which is where the JTextArea is located. I am able to pass the string into this method and print to counsel but it won't append or setText to the JTextArea. What am I missing?
My goal is to have different classes send messages to the class ActivityLogger which in turn sends it to the JTextArea.
Any examples are appreciated and Thank you in advance.
Main class
package risk_mgnt_manager;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
public class Risk_Mgnt_Manager extends JFrame{
boolean begin = false;
String message = null;
JTextArea text = new JTextArea();
JButton Start = new JButton("Start");//exit program button
JButton End = new JButton("End");//Ok button executes message creation
JButton Exit = new JButton("Exit Program");
public void Alert(String a){
System.out.println(a); // This is printing correctly
text.append(a + "\n"); // why won't this display the string?
}
public Risk_Mgnt_Manager(){
text.setEditable(false);
text.setWrapStyleWord(true);
text.setLineWrap(true);
JScrollPane scroll = new JScrollPane(text);
setLayout(new GridLayout(2, 3, 5, 5)); //LayoutManager Setup
JPanel myPanel = new JPanel(new GridLayout(3,0));
//JPanel myPanel2 = new JPanel(new GridLayout(1, 1));
//JPanel myPanel3 = new JPanel(new GridLayout(1, 1));
JPanel myPanel4 = new JPanel(new GridLayout(1, 1));
myPanel.add(new JLabel("Start Automated Processes: "));
myPanel.add(Start);
myPanel.add(new JLabel("End Automated Processes: "));
myPanel.add(End);
myPanel.add(new JLabel(" "));
myPanel.add(Exit);
myPanel4.add(text);
Start.addActionListener(new startActions());//Listener for button 1
End.addActionListener(new stopActions());//Listener for button 2
Exit.addActionListener(new Quit());//Listener for button 2
add(myPanel);
//add(myPanel2);
//add(myPanel3);
add(myPanel4);
}
public void StartAutomation(boolean start) throws SAXException, ParserConfigurationException, IOException, SQLException{
//calls test class
Test t = new Test();
t.mainTest(begin);
//ignore these classes
// Step one import settlement data from FIX 1 settlement tables
ImportSettles tbl = new ImportSettles();
//tbl.DataTransfer(begin);
// Step two import Real-Time price data from t_span_price on FIX 1
ImportSpanPrice tbl2 = new ImportSpanPrice();
//tbl2.DataTransfer1(begin);
// Step three import from xml file
ImportTradeData tbl3 = new ImportTradeData();
//tbl3.parseXML(begin);
// Step four not used as of 11/26/2013
ImportFirmRpt tbl4 = new ImportFirmRpt();
// Step five import poew.csv file
ImportPOEW tbl5 = new ImportPOEW();
//tbl5.csvImportPOEW(begin);
// Step six import paycollect.csv file
ImportPaycollect tbl6 = new ImportPaycollect();
//tbl6.csvImportPaycollect(begin);
// Step seven import data from RISK 1
ImportSecDeposit tbl7 = new ImportSecDeposit();
//tbl7.DataTransfer2(begin);
// Step 8 import FCM financial info, WinJammer not used as of 11/26/2013
ImportFCM tbl8 = new ImportFCM();
// Step nine import CGM_post.csv file
ImportCGMPost tbl9 = new ImportCGMPost();
//tbl9.csvImportCGMPost(begin);
// Step ten import RM_Intraday_paycollect.csv
ImportIntraday tbl10 = new ImportIntraday();
//tbl10.csvImportIntra(begin);
}
private static void ProjectFrame(){
Risk_Mgnt_Manager projectFrame = new Risk_Mgnt_Manager();
projectFrame.setSize(500, 300); //JFrame size set
projectFrame.setLocationRelativeTo(null); //JFrame centered to center of screen
projectFrame.setTitle("Automation Control"); //JFrame Title
projectFrame.setVisible(true);//JFrame is visible upon start of program
projectFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
ProjectFrame();
}
static class Quit implements ActionListener {
public void actionPerformed (ActionEvent e) {
//Once Exit JButton is pressed the program exits
System.exit(0);
}
}
public class startActions implements ActionListener {
public void actionPerformed (ActionEvent e) {
//Once Exit JButton is pressed the program exits
begin = true;
try {
StartAutomation(begin);
} catch (SAXException ex) {
Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public class stopActions implements ActionListener {
public void actionPerformed (ActionEvent e) {
//Once Exit JButton is pressed the program exits
begin = false;
try {
StartAutomation(begin);
} catch (SAXException ex) {
Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Test class
package risk_mgnt_manager;
import java.util.Date;
/**
*
* #author bgilbert
*/
public class Test {
public void mainTest(boolean a){
ActivityLogger act = new ActivityLogger();
act.logger("Testing message reporting " + new Date(), 1, true);
}
}
ActivityLogger class
package risk_mgnt_manager;
/**
*
* #author MLaMeyer
*/
public class ActivityLogger{
private String message;
// this will perform different purposes once I can print to JTextArea
public void logger(String log, int type, boolean execution){
if (execution == true) {
message = log;
}
if (execution == false) {
message = log;
}
print();
}
// calls method Alert in main class and passes the string correctly
public void print(){
Risk_Mgnt_Manager m = new Risk_Mgnt_Manager();
m.Alert(message);
}
}
Your program prints out to the other class, just not in the object displayed:
public void print(){
Risk_Mgnt_Manager m = new Risk_Mgnt_Manager();
m.Alert(message);
}
When you create a new Risk_Mgnt_Manager, you do just that, create a new completely unique Risk_Mgnt_Manager object, one that is not displayed. Printing to it will have no effect on the displayed one.
A the solution is to pass in a reference to your logger class to the actual displayed Risk_Mgnt_Manager object.
public class ActivityLogger{
private String message;
private Risk_Mgnt_Manager m; // ***** added
public ActivityLogger(Risk_Mgnt_Manager m) {
this.m = m; // ****** added
}
// this will perform different purposes once I can print to JTextArea
public void logger(String log, int type, boolean execution){
if (execution == true) {
message = log;
}
if (execution == false) {
message = log;
}
print();
}
// calls method Alert in main class and passes the string correctly
public void print(){
// Risk_Mgnt_Manager m = new Risk_Mgnt_Manager();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
m.Alert(message);
}
});
}
}
Whatever you do, don't attempt to solve this my making anything static as that road will lead to misery.
You need to update the UI in separate Thread, I mean UI related operations should run on the Event dispatch thread. Add constructor in your ActivityLogger class like Hovercraft's solution then try,
SwingUtilities.invokeLater(new Runnable() {
public void run() {
text.append(a+"\n");
}
});
First of all make the frame visible in your constructor.
public Risk_Mgnt_Manager(){
setVisible(true);
}
Then as per solution by Hovercraft pass by reference.