Output to TextArea
This is for a college assignment. I'm trying to output some text
into a GUI TextArea instead of the console. How is this done? I want to execute the method from the GUI, and display the text in a TextArea.
Here is part of the method:
if (roomAvailable == false)
System.out.println("No bedrooms available"); //this to TextArea
}//end then
else
String custName = JOptionPane.showInputDialog(
"Enter name of customer booking bedroom: ");
customerName = custName;
String payName = JOptionPane.showInputDialog(
"Enter name of payee (company name or \"PRIVATE\"): ");
payeeName = payName;
System.out.println(customerName + " is booked into bedroom " + (counter + 6));//this to TextArea
bedrooms[counter--].occupyRoom(customerName, payeeName);
Any help wuold be appreciated.
Thanks
I want to call the method from another
class.Specifically, I am putting the GUI components
and layout in one class, and then calling this method
from here by instantiating an object of its class. My
problem is that the text output is embedded in this
method - how do I chage this output to my TextArea?Make this method return the String that you want to put in the TextArea and then have your GUI class call this method and load the TextArea with the return value as the above poster showed you how to.
Similar Messages
-
Button wont trigger output in textarea
I am doing something wrong here and cant figure out why my second set of buttons will not give output in my textarea. I would appreciate it if anyone could help shed some light on why its not working...
public void actionPerformed(ActionEvent e)//creates the action event
if(e.getSource() == calculateBtn)
if (loanSlctBx.getSelectedItem().equals("7 years at 5.35%"))//array used to selcted term and APR bassed on the Combo Box
apr=b[0];//tells to store the 1st value to the varible
term=a[0];
else if (loanSlctBx.getSelectedItem().equals("15 years at 5.5%"))
apr=b[1];
term=a[1];//tells to store the 2nd value to the varible
else if (loanSlctBx.getSelectedItem().equals("30 years at 5.75%"))
apr=b[2];//tells to store the 3rd value to the varible
term=a[2];
// Makes all the calculation needed for the output
amnt = Double.parseDouble(amntFld.getText());
amntFld.setText(currencyComposition(amnt)); // Formats the value to use a US currencey composistion
mTerm = term*12; //sets the mTerm variable
mApr = (apr / 100) / 12; //sets the mApr with the monthly interest
pay = amnt * (mApr / (1 - Math.pow((1 + mApr), -mTerm)));//sets the pay varible with the results
double newAmnt = amnt;//sets new variable for new loan amount
//Loop to run the calulations thorughout the life of the loan
for (int i=0; i<mTerm;i++)
if (i==36||i==72||i==108||i==144||i==180||i==216||i==252||i==288||i==326||i==360)
try
Thread.sleep(500);//sleep timer
catch (InterruptedException e1)
//Prints the output for the calculations in the JTextAera one line at a time
payFld.append(i+1 +" "+currencyComposition(pay)+" "+currencyComposition(newAmnt*mApr)+" "+currencyComposition(pay-(newAmnt*(mApr))) +" "+currencyComposition(newAmnt)+"\n");
newAmnt -= pay-(newAmnt*(mApr));
if(e.getSource() == calculateBtn2)
if (e.getActionCommand().equals(calculateBtn2.getActionCommand()))
String amnt2 = amntFld2.getText();
String term2 = termFld2.getText();
String apr2 = aprFld2.getText();
else if (e.getActionCommand().equals(resetBtn.getActionCommand())) // Resets all fields
amntFld2.setText(null);
aprFld2.setText(null);
termFld2.setText(null);
payFld.setText(null);
// Makes all the calculation needed for the output
//amnt2 = Double.parseDouble(amntFld2.getText());
//amntFld2.setText(currencyComposition(amnt2)); // Formats the value to use a US currencey composistion
mTerm2 = term2*12; //sets the mTerm variable
mApr2 = (apr2 / 100) / 12; //sets the mApr with the monthly interest
pay = amnt2 * (mApr2 / (1 - Math.pow((1 + mApr2), -mTerm2)));//sets the pay varible with the results
double newAmnt2 = amnt2;//sets new variable for new loan amount
//Loop to run the calulations thorughout the life of the loan
for (int i=0; i<mTerm2;i++)
if (i==36||i==72||i==108||i==144||i==180||i==216||i==252||i==288||i==326||i==360)
try
Thread.sleep(500);//sleep timer
catch (InterruptedException e1)
//Prints the output for the calculations in the JTextAera one line at a time
payFld.append(i+1 +" "+currencyComposition(pay)+" "+currencyComposition(newAmnt2*mApr2)+" "+currencyComposition(pay-(newAmnt2*(mApr2))) +" "+currencyComposition(newAmnt2)+"\n");
newAmnt2 -= pay2-(newAmnt2*(mApr2));
// Formats the numeric values to readable currency
private String currencyComposition(double input) {
DecimalFormat df = new DecimalFormat("$###,###,###.00");
df.setMaximumFractionDigits(2);
String formattedString = df.format(input);
return formattedString;
}Does your code compile? I ask because in your "if (e.getActionCommand().equals(calculateBtn2.getActionCommand()))" block you declare a String variable amnt2 inside an if block but then use it outside the block to initialise newAmnt2.
This could work, I guess, if there were an instance variable amnt2 but that would be confusing. Actually if you are looking for light get rid of any variables of the form thingN, newThingN etc. Make the names descriptive: each variable descriptive of what it is a variable for.
To address your question (why the field doesn't change when you click the button): insert some System.out.println()s to check what code is actually being executed. Ie right at the start of actionPerformed(), again after the "if(e.getSource() == calculateBtn2)" etc. Basically everywhere you think the code should be getting to.
Also if "e.getSource() == calculateBtn2" is true won't the actionCommand of e and calculateBtn2 be the same? If so I don't really understand the intent of the code that checks them for equality. -
Can someone give me a clue on how to make the URL displayed in the TextArea hyperlinkable. The Program displays http://www.yahoo.com but I want to be able to click on it and have it open into a new browser. It currently runs fine without the hyperlink but has compile errors. Thanks :^)
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
import javax.swing.JEditorPane.*;
import javax.swing.text.html.*;
public class Hyperlinkdemo
public static void main(String[] args)
JEditorPane myEditorPane;
myEditorPane.addHyperlinkListener(new MyHyperlinkListener());
final String website = "http://www.yahoo.com";
JLabel msgLabel = new JLabel("Hyperlinkable Test Program");
JButton runButton = new JButton("Run");
final TextArea output = new TextArea(10,30);
JScrollPane scroller = new JScrollPane(output);
JFrame frame = new JFrame("Hyperlinkdemo");
JPanel buttonbox = new JPanel();
JPanel jp = new JPanel();
JPanel northPanel = new JPanel();
frame.getContentPane().setLayout(new BorderLayout());
jp.setLayout(new FlowLayout());
jp.add(scroller);
northPanel.add(msgLabel);
northPanel.add(runButton);
website.add(myEditorPane);
frame.getContentPane().add(northPanel, "North");
frame.getContentPane().add(jp, "South");
runButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
output.append(website + "\n");
frame.pack();
frame.show();
class MyHyperlinkListener implements HyperlinkListener {
public void hyperlinkUpdate(HyperlinkEvent evt) {
HyperlinkEvent.EventType type = evt.getEventType();
if (type.equals(HyperlinkEvent.EventType.ACTIVATED)) {
myEditorPane.setPage(evt.getURL());
}Well i'm sure there are a lot of others that can help you better than myself, but i think the key to your problem is in your JEditorPane call setEditable(false). The Java API itself has a good example under JEditorPane.
Here's what i came up with after modifying your code
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.text.html.*;
import java.io.*;
public class Hyperlinkdemo
JEditorPane myEditorPane;
final String website = "http://www.yahoo.com";
public void init()
myEditorPane = new JEditorPane("text/html","");
myEditorPane.addHyperlinkListener(new MyHyperlinkListener());
myEditorPane.setEditable(false);
JLabel msgLabel = new JLabel("Hyperlinkable Test Program");
JButton runButton = new JButton("Run");
JScrollPane scroller = new JScrollPane();
scroller.setViewportView(myEditorPane);
scroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
//scroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
JFrame frame = new JFrame("Hyperlinkdemo");
JPanel buttonbox = new JPanel();
JPanel northPanel = new JPanel();
northPanel.add(msgLabel);
northPanel.add(runButton);
frame.getContentPane().add(northPanel, "North");
frame.getContentPane().add(scroller);
runButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
myEditorPane.setText("<a href=\"http://www.yahoo.com\">www.yahoo.com</a>");
System.out.println(myEditorPane.getContentType());
frame.addWindowListener(new MyWindowAdapter());
frame.pack();
frame.setSize(300,300);
frame.show();
class MyWindowAdapter extends WindowAdapter
public void windowClosing(WindowEvent e)
System.exit(0);
public static void main(String args[])
Hyperlinkdemo demo = new Hyperlinkdemo();
demo.init();
class MyHyperlinkListener implements HyperlinkListener
public void hyperlinkUpdate(HyperlinkEvent e)
HyperlinkEvent.EventType type = e.getEventType();
if (type.equals(HyperlinkEvent.EventType.ACTIVATED))
JEditorPane pane = (JEditorPane) e.getSource();
JEditorPane another = new JEditorPane();
JFrame newframe = new JFrame("New window");
if (e instanceof HTMLFrameHyperlinkEvent)
HTMLFrameHyperlinkEvent evt = (HTMLFrameHyperlinkEvent)e;
HTMLDocument doc = (HTMLDocument)pane.getDocument();
doc.processHTMLFrameHyperlinkEvent(evt);
else
try
another.setPage(e.getURL());
newframe.getContentPane().add(another);
newframe.pack();
newframe.setSize(100,100);
newframe.show();
catch (Throwable t)
t.printStackTrace();
It provides a hyperlink after the RUN button is clicked, and pops the clicked result in another frame. Hope this helps -
How can I change my JApplet into a JApplication?
I am working with a JApplet and am finding that some of my code only works in applications.
So being new to this, I am clueless as to how to change my Applet into an Application. I understand the difference in definition between the two, but when it comes to looking at Applet Code and Application Code, I am not able to see a difference. (Other than an Applet stating "Applet")
So, that being said how can I change my code so that it runs as an application and not an applet? Here is my current layout code
import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.text.NumberFormat;
import java.text.DecimalFormat;
// Creating the main class
public class test extends JApplet implements ActionListener
// Defining of format information
JLabel heading = new JLabel("McBride Financial Services Mortgage Calculator");
Font newFontOne = new Font("TimesRoman", Font.BOLD, 20);
Font newFontTwo = new Font("TimesRoman", Font.ITALIC, 16);
Font newFontThree = new Font("TimesRoman", Font.BOLD, 16);
Font newFontFour = new Font("TimesRoman", Font.BOLD, 14);
JButton calculate = new JButton("Calculate");
JButton exitButton = new JButton("Quit");
JButton clearButton = new JButton("Clear");
JLabel instructions = new JLabel("Please Enter the Principal Amount Below");
JLabel instructions2 = new JLabel("and Select a Loan Type from the Menu");
// Declaration of variables
private double principalAmount;
private JLabel principalLabel = new JLabel("Principal Amount");
private NumberFormat principalFormat;
private JTextField enterPrincipal = new JTextField(10);
private double finalPayment;
private JLabel monthlyPaymentLabel = new JLabel(" Monthly Payment \t Interest Paid \t \t Loan Balance");
private NumberFormat finalPaymentFormat;
private JTextField displayMonthlyPayment = new JTextField(10);
private JTextField displayInterestPaid = new JTextField(10);
private JTextField displayBalance = new JTextField(10);
// Creation of the String of arrays for the ComboBox
String [] list = {"7 Years @ 5.35%", "15 Years @ 5.50%", "30 Years @ 5.75%"};
JComboBox selections = new JComboBox(list);
// Creation of the textArea that will display the output
private TextArea txtArea = new TextArea(5, 10);
StringBuffer buff = null;
// Initializing the interface
public void init()
// Creation of the panel design and fonts
JPanel upper = new JPanel(new BorderLayout());
JPanel middle = new JPanel(new BorderLayout());
JPanel lower = new JPanel(new BorderLayout());
JPanel areaOne = new JPanel(new BorderLayout());
JPanel areaTwo = new JPanel(new BorderLayout());
JPanel areaThree = new JPanel(new BorderLayout());
JPanel areaFour = new JPanel(new BorderLayout());
JPanel areaFive = new JPanel(new BorderLayout());
JPanel areaSix = new JPanel(new BorderLayout());
Container con = getContentPane();
getContentPane().add(upper, BorderLayout.NORTH);
getContentPane().add(middle, BorderLayout.CENTER);
getContentPane().add(lower, BorderLayout.SOUTH);
upper.add(areaOne, BorderLayout.NORTH);
middle.add(areaTwo, BorderLayout.NORTH);
middle.add(areaThree, BorderLayout.CENTER);
middle.add(areaFour, BorderLayout.SOUTH);
lower.add(areaFive, BorderLayout.NORTH);
lower.add(areaSix, BorderLayout.SOUTH);
heading.setFont(newFontOne);
instructions.setFont(newFontTwo);
instructions2.setFont(newFontTwo);
principalLabel.setFont(newFontThree);
monthlyPaymentLabel.setFont(newFontFour);
displayInterestPaid.setFont(newFontFour);
displayBalance.setFont(newFontFour);
areaOne.add(heading, BorderLayout.NORTH);
areaOne.add(instructions, BorderLayout.CENTER);
areaOne.add(instructions2, BorderLayout.SOUTH);
areaTwo.add(principalLabel, BorderLayout.WEST);
areaTwo.add(enterPrincipal, BorderLayout.EAST);
areaThree.add(selections, BorderLayout.NORTH);
areaFour.add(calculate, BorderLayout.CENTER);
areaFour.add(exitButton, BorderLayout.EAST);
areaFour.add(clearButton, BorderLayout.WEST);
areaFive.add(monthlyPaymentLabel, BorderLayout.CENTER);
areaSix.add(txtArea, BorderLayout.CENTER);
// Using the ActionListener to determine when each button is clicked
calculate.addActionListener(this);
exitButton.addActionListener(this);
clearButton.addActionListener(this);
enterPrincipal.requestFocus();
selections.addActionListener(this);
}baftos wrote:
Here is one of the sites that explains the procedure:
[http://leepoint.net/notes-java/deployment/applications_and_applets/70applets.html].
But maybe you should try to fix the code that does not work as applet?
Which one is it?
>Here is one of the sites that explains the procedure:
[http://leepoint.net/notes-java/deployment/applications_and_applets/70applets.html].
But maybe you should try to fix the code that does not work as applet?
Which one is it?
The code that doesn't work in my applet is the exit button code
else if (source == exitButton)
System.exit(1);
}I also can't get my program to properly validate input. When invalid input is entered and the user presses calculate, an error window should pop up. Unfortunately it isn't. I compile and run my applications/applets through TextPad. So when I try to test the error window by entering in invalid info, the applet itself shows nothing but the command prompt window pops up and lists errors from Java. Anyhow, here is the method I was told to use to fix it.
private static boolean validate(JTextField in)
String inText = in.getText();
char[] charInput = inText.toCharArray();
for(int i = 0; i < charInput.length; i++)
int asciiVal = (int)charInput;
if((asciiVal >= 48 && asciiVal <= 57) || asciiVal == 46)
else
JOptionPane.showMessageDialog(null, "Invalid Character, Please Use Numeric Values Only");
return false;
return true;
}My Instructor told me to try the following, but I still can't get it to work.String content = textField.getText();
if (content.length() != 0) {
try { Integer.parseInt(content);
} catch (NumberFormatException nfe) {} -
Need help with Java, have a few questions about my Applet
Purpose of the program: To create a mortgage calculator that will allow the user to input the loan principal then select 1 of 3 choices from a combo-box (7 years @ 5.35%, 15 years @ 5.50%, 30 years @ 5.75%).
Problem: My program was working properly (so I thought). I can get the program to properly compile and run through TextPad. However, I noticed that when the user clicks the calculate more than once (with the same input), it slightly alters the output calculations. So that is my first question, Why is it doing that? How can I get it only calculate that information once unless the user changes it etc?
My next question is regarding my exit button. I was told by my instructor (who has already stated he won't help any of us) that my exit button does not work for an applet and only for an application. So, how can I create an exit button that will work with an applet? I thought I did it right but I can't find any resources online for this.
Next question, why isn't my program properly validating invalid input? My program should only allow numeric input and nothing more.
And last question, when invalid input is entered and the user clicks calculate, why isn't my JOptionPane window for error messages not displaying?
I know my code is a little long so I have to post this in two messages. Please don't criticize me for what I am doing, that is why I am learning and have come to this forum for help. Thanks
import java.applet.Applet;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.text.NumberFormat;
import java.text.DecimalFormat;
// Creating the main class
public class test extends JApplet implements ActionListener
// Defining of format information
JLabel heading = new JLabel("McBride Financial Services Mortgage Calculator");
Font newFontOne = new Font("TimesRoman", Font.BOLD, 20);
Font newFontTwo = new Font("TimesRoman", Font.ITALIC, 16);
Font newFontThree = new Font("TimesRoman", Font.BOLD, 16);
Font newFontFour = new Font("TimesRoman", Font.BOLD, 14);
JButton calculate = new JButton("Calculate");
JButton exitButton = new JButton("Quit");
JButton clearButton = new JButton("Clear");
JLabel instructions = new JLabel("Please Enter the Principal Amount Below");
JLabel instructions2 = new JLabel("and Select a Loan Type from the Menu");
// Declaration of variables
private double principalAmount;
private JLabel principalLabel = new JLabel("Principal Amount");
private NumberFormat principalFormat;
private JTextField enterPrincipal = new JTextField(10);
private double finalPayment;
private JLabel monthlyPaymentLabel = new JLabel(" Monthly Payment \t Interest Paid \t \t Loan Balance");
private NumberFormat finalPaymentFormat;
private JTextField displayMonthlyPayment = new JTextField(10);
private JTextField displayInterestPaid = new JTextField(10);
private JTextField displayBalance = new JTextField(10);
// Creation of the String of arrays for the ComboBox
String [] list = {"7 Years @ 5.35%", "15 Years @ 5.50%", "30 Years @ 5.75%"};
JComboBox selections = new JComboBox(list);
// Creation of the textArea that will display the output
private TextArea txtArea = new TextArea(5, 10);
StringBuffer buff = null;
Edited by: LoveMyAJ on Jan 19, 2009 1:49 AM// Initializing the interface
public void init()
// Creation of the panel design and fonts
JPanel upper = new JPanel(new BorderLayout());
JPanel middle = new JPanel(new BorderLayout());
JPanel lower = new JPanel(new BorderLayout());
JPanel areaOne = new JPanel(new BorderLayout());
JPanel areaTwo = new JPanel(new BorderLayout());
JPanel areaThree = new JPanel(new BorderLayout());
JPanel areaFour = new JPanel(new BorderLayout());
JPanel areaFive = new JPanel(new BorderLayout());
JPanel areaSix = new JPanel(new BorderLayout());
Container con = getContentPane();
getContentPane().add(upper, BorderLayout.NORTH);
getContentPane().add(middle, BorderLayout.CENTER);
getContentPane().add(lower, BorderLayout.SOUTH);
upper.add(areaOne, BorderLayout.NORTH);
middle.add(areaTwo, BorderLayout.NORTH);
middle.add(areaThree, BorderLayout.CENTER);
middle.add(areaFour, BorderLayout.SOUTH);
lower.add(areaFive, BorderLayout.NORTH);
lower.add(areaSix, BorderLayout.SOUTH);
heading.setFont(newFontOne);
instructions.setFont(newFontTwo);
instructions2.setFont(newFontTwo);
principalLabel.setFont(newFontThree);
monthlyPaymentLabel.setFont(newFontFour);
displayInterestPaid.setFont(newFontFour);
displayBalance.setFont(newFontFour);
areaOne.add(heading, BorderLayout.NORTH);
areaOne.add(instructions, BorderLayout.CENTER);
areaOne.add(instructions2, BorderLayout.SOUTH);
areaTwo.add(principalLabel, BorderLayout.WEST);
areaTwo.add(enterPrincipal, BorderLayout.EAST);
areaThree.add(selections, BorderLayout.NORTH);
areaFour.add(calculate, BorderLayout.CENTER);
areaFour.add(exitButton, BorderLayout.EAST);
areaFour.add(clearButton, BorderLayout.WEST);
areaFive.add(monthlyPaymentLabel, BorderLayout.CENTER);
areaSix.add(txtArea, BorderLayout.CENTER);
// Using the ActionListener to determine when each button is clicked
calculate.addActionListener(this);
exitButton.addActionListener(this);
clearButton.addActionListener(this);
enterPrincipal.requestFocus();
selections.addActionListener(this);
// The method that will perform specific actions defined below
public void actionPerformed(ActionEvent e)
Object source = e.getSource();
buff = new StringBuffer();
// Outcome of pressing the calculate button
if (source == calculate)
// Used to call upon the user chosen selection
int selection = selections.getSelectedIndex();
// If statement to call upon Loan One's Method
if (selection == 0)
Double data = (Double)calculateLoanOne();
String sourceInput = data.toString();
displayMonthlyPayment.setText(sourceInput);
txtArea.setText(buff.toString());
// If statement to call upon Loan Two's Method
else if (selection == 1)
Double data = (Double)calculateLoanTwo();
String sourceInput = data.toString();
displayMonthlyPayment.setText(sourceInput);
txtArea.setText(buff.toString());
// If statement to call upon Loan Three's Method
else if (selection == 2)
Double data = (Double)calculateLoanThree();
String sourceInput = data.toString();
displayMonthlyPayment.setText(sourceInput);
txtArea.setText(buff.toString());
// Outcome of pressing the clear button
else if (source == clearButton)
enterPrincipal.setText("");
displayMonthlyPayment.setText("");
selections.setSelectedIndex(0);
txtArea.setText("");
// Outcome of pressing the quit button
else if (source == exitButton)
System.exit(1);
// Method used to validate user input
private static boolean validate(JTextField in)
String inText = in.getText();
char[] charInput = inText.toCharArray();
for(int i = 0; i < charInput.length; i++)
int asciiVal = (int)charInput;
if((asciiVal >= 48 && asciiVal <= 57) || asciiVal == 46)
else
JOptionPane.showMessageDialog(null, "Invalid Character, Please Use Numeric Values Only");
return false;
return true; -
Button not appearing (obvious fix most likely (no errors))
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class ChatClient
private TextArea output;
private TextField input;
private Button sendButton;
private Button quitButton;
private JButton button;
private ImageIcon image;
private ImageIcon image1;
private Panel p1;
private Frame frame;
private Panel p2;
public ChatClient()
output = new TextArea(10,50);
input = new TextField(50);
frame = new Frame("Chat Room");
sendButton = new Button("Send");
quitButton = new Button("Quit");
button = new JButton(image);
image = new ImageIcon("c:/aztecsun.jpg");
image1 = new ImageIcon("c:/aztecsun.jpg");
p1 = new Panel();
p2 = new Panel();
public void launchFrame()
button.setContentAreaFilled(false);
button.setBorderPainted(false);
button.setFocusPainted(false);
button.setPressedIcon(image1);
p1.add(sendButton);
p1.add(quitButton);
p2.add(button);
// Use the Border Layout for the frame
frame.setLayout(new BorderLayout());
frame.add(output, BorderLayout.WEST);
frame.add(input, BorderLayout.SOUTH);
frame.add(p1, BorderLayout.EAST);
frame.add(p2, BorderLayout.CENTER);
// Add the button panel to the center
frame.pack();
frame.setVisible(true);
//frame.addWindowListener(this);
sendButton.addActionListener(new sendHandler());
input.addActionListener(new inputHandler());
button.addActionListener(new azteca());
quitButton.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
System.exit(0);
frame.addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent we)
System.exit(0);
/* class windowTerminate implements WindowListener
public void windowClosing(WindowEvent we)
System.exit(0);
public void windowDeactivated(WindowEvent we)
public void windowIconified(WindowEvent we)
public void windowDeiconified(WindowEvent we)
public void windowActivated(WindowEvent we)
public void windowOpened(WindowEvent we)
public void windowClosed(WindowEvent we)
class azteca implements ActionListener
public void actionPerformed(ActionEvent ae)
if(ae.getSource() == button)
String text = input.getText();
output.setText(output.getText() + text + "/n");
input.setText("");
public void copyText()
String text = input.getText();
output.setText(output.getText() + text + "\n");
input.setText("");
class sendHandler implements ActionListener
public void actionPerformed(ActionEvent ae)
copyText();
class inputHandler implements ActionListener
public void actionPerformed(ActionEvent ae)
copyText();
public static void main(String[] args)
ChatClient c = new ChatClient();
c.launchFrame();
}I'm practicing with events/buttons with icons and the button is not appearing...
Yes the image is in the correct directory... (for the obvious fix type of people)...
But yeah...
Thanks!I know the fix but I do not know how to do it... I haven't added the image button correctly therefore it is not appearing, but I lack the necessary skills to fix the problem.
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.*;
public class ChatClient
private JTextArea output;
private JTextField input;
private JButton sendButton;
private JButton quitButton;
private JButton button;
private ImageIcon image;
private ImageIcon image1;
private JPanel p1;
private JFrame frame;
private JPanel p2;
public ChatClient()
output = new JTextArea(10,50);
input = new JTextField(50);
frame = new JFrame("Chat Room");
sendButton = new JButton("Send");
quitButton = new JButton("Quit");
button = new JButton(image);
image = new ImageIcon("c:/aztecsun.jpg");
image1 = new ImageIcon("c:/aztecsun.jpg");
p1 = new JPanel();
p2 = new JPanel();
public void launchFrame()
button.setContentAreaFilled(false);
button.setBorderPainted(false);
button.setFocusPainted(false);
button.setPressedIcon(image1);
p1.add(sendButton);
p1.add(quitButton);
p2.add(button);
// Use the Border Layout for the frame
frame.setLayout(new BorderLayout());
frame.add(output, BorderLayout.WEST);
frame.add(input, BorderLayout.SOUTH);
frame.add(p1, BorderLayout.EAST);
frame.add(p2, BorderLayout.CENTER);
// Add the button panel to the center
frame.pack();
frame.setVisible(true);
//frame.addWindowListener(this);
sendButton.addActionListener(new sendHandler());
input.addActionListener(new inputHandler());
button.addActionListener(new azteca());
quitButton.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
System.exit(0);
frame.addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent we)
System.exit(0);
/* class windowTerminate implements WindowListener
public void windowClosing(WindowEvent we)
System.exit(0);
public void windowDeactivated(WindowEvent we)
public void windowIconified(WindowEvent we)
public void windowDeiconified(WindowEvent we)
public void windowActivated(WindowEvent we)
public void windowOpened(WindowEvent we)
public void windowClosed(WindowEvent we)
class azteca implements ActionListener
public void actionPerformed(ActionEvent ae)
if(ae.getSource() == button)
String text = input.getText();
output.setText(output.getText() + text + "/n");
input.setText("");
public void copyText()
String text = input.getText();
output.setText(output.getText() + text + "\n");
input.setText("");
class sendHandler implements ActionListener
public void actionPerformed(ActionEvent ae)
copyText();
class inputHandler implements ActionListener
public void actionPerformed(ActionEvent ae)
copyText();
public static void main(String[] args)
ChatClient c = new ChatClient();
c.launchFrame();
}Edited by: Trizi on Mar 25, 2008 11:52 AM -
Chat System: ConnectException: Connection timed out: connect
Hi There,
I am developing a chat system as part of a University project.
To explain what I have implemented:
I have three java classes;
1. Chat Server class which is constantly listening for incoming socket connection on a particular socket:
while (true)
Socket client = server.accept ();
System.out.println ("Accepted from " + client.getInetAddress ());
ChatHandler c = new ChatHandler (client);
c.start ();
2. Chat Handler class uses a thread for each client to handle multiple clients:
public ChatHandler (Socket s) throws IOException
this.s = s;
i = new DataInputStream (new BufferedInputStream (s.getInputStream ()));
o = new DataOutputStream (new BufferedOutputStream (s.getOutputStream ()));
public void run ()
try
handlers.addElement (this);
while (true)
String msg = i.readUTF ();
broadcast (msg);
catch (IOException ex)
ex.printStackTrace ();
finally
handlers.removeElement (this);
try
s.close ();
catch (IOException ex)
ex.printStackTrace();
protected static void broadcast (String message)
synchronized (handlers)
Enumeration e = handlers.elements ();
while (e.hasMoreElements ())
ChatHandler c = (ChatHandler) e.nextElement ();
try
synchronized (c.o)
c.o.writeUTF (message);
c.o.flush ();
catch (IOException ex)
c.stop ();
3. Chat Client class which has a simple GUI and sends messages to the server to be broadcasted to all other clients on the same socket port:
public ChatClient (String title, InputStream i, OutputStream o)
super (title);
this.i = new DataInputStream (new BufferedInputStream (i));
this.o = new DataOutputStream (new BufferedOutputStream (o));
setLayout (new BorderLayout ());
add ("Center", output = new TextArea ());
output.setEditable (false);
add ("South", input = new TextField ());
pack ();
show ();
input.requestFocus ();
listener = new Thread (this);
listener.start ();
public void run ()
try
while (true)
String line = i.readUTF ();
output.appendText (line + "\n");
catch (IOException ex)
ex.printStackTrace ();
finally
listener = null;
input.hide ();
validate ();
try
o.close ();
catch (IOException ex)
ex.printStackTrace ();
public boolean handleEvent (Event e)
if ((e.target == input) && (e.id == Event.ACTION_EVENT)) {
try {
o.writeUTF ((String) e.arg);
o.flush ();
} catch (IOException ex) {
ex.printStackTrace();
listener.stop ();
input.setText ("");
return true;
} else if ((e.target == this) && (e.id == Event.WINDOW_DESTROY)) {
if (listener != null)
listener.stop ();
hide ();
return true;
return super.handleEvent (e);
public static void main (String args[]) throws IOException
Socket s = new Socket ("192.168.2.3",4449);
new ChatClient ("Chat test", s.getInputStream (), s.getOutputStream ());
On testing this simple app on my local host I have launched several instances of ChatClient and they interact perfectly between each other.
Although when i test this app by launching ChatClient on another machine (using a wi-fi network connection at home), on the other machine that tries to connect to the hosting server (my machine) i get a "connection timed out" on the chatClient machine.
I have added the port and ip addresses in concern to the exceptions to by-pass the firewall but i am still getting the timeout.
Any suggestions?
Thanks!Format your code with [ code ] tag pair.
If you are a young university student I don't understand why current your code uses so many of
too-too-too old APIs including deprecated ones.
For example, DataInput/OutputStream should never be used for text I/Os because they aren't
always reliable.
Use Writers and Readers in modern Java programming
Here's a simple and standard chat program example:
(A few of obsolete APIs from your code remain here, but they are no problem.
Tested both on localhost and a LAN.)
/* ChatServer.java */
import java.io.*;
import java.util.*;
import java.net.*;
public class ChatServer{
ServerSocket server;
public ChatServer(){
try{
server = new ServerSocket(4449);
while (true){
Socket client = server.accept();
System.out.println("Accepted from " + client.getInetAddress());
ChatHandler c = new ChatHandler(client);
c.start ();
catch (IOException e){
e.printStackTrace();
public static void main(String[] args){
new ChatServer();
class ChatHandler extends Thread{
static Vector<ChatHandler> handlers = new Vector<ChatHandler>();
Socket s;
BufferedReader i;
PrintWriter o;
public ChatHandler(Socket s) throws IOException{
this.s = s;
i = new BufferedReader(new InputStreamReader(s.getInputStream()));
o = new PrintWriter
(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())));
public void run(){
try{
handlers.addElement(this);
while (true){
String msg = i.readLine();
broadcast(msg);
catch (IOException ex){
ex.printStackTrace();
finally{
handlers.removeElement(this);
try{
s.close();
catch (IOException e){
e.printStackTrace();
protected static void broadcast(String message){
synchronized (handlers){
Enumeration e = handlers.elements();
while (e.hasMoreElements()){
ChatHandler c = (ChatHandler)(e.nextElement());
synchronized (c.o){
c.o.println(message);
c.o.flush();
/* ChatClient.java */
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public class ChatClient extends JFrame implements Runnable{
Socket socket;
JTextArea output;
JTextField input;
BufferedReader i;
PrintWriter o;
Thread listener;
JButton endButton;
public ChatClient (String title, Socket s){
super(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
socket = s;
try{
i = new BufferedReader(new InputStreamReader(s.getInputStream()));
o = new PrintWriter
(new BufferedWriter(new OutputStreamWriter(s.getOutputStream())));
catch (IOException ie){
ie.printStackTrace();
Container con = getContentPane();
con.add (output = new JTextArea(), BorderLayout.CENTER);
output.setEditable(false);
con.add(input = new JTextField(), BorderLayout.SOUTH);
con.add(endButton = new JButton("END"), BorderLayout.NORTH);
input.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
o.println(input.getText());
o.flush();
input.setText("");
endButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ev){
try{
socket.close();
catch (IOException ie){
ie.printStackTrace();
System.exit(0);
setBounds(50, 50, 500, 500);
setVisible(true);
input.requestFocusInWindow();
listener = new Thread(this);
listener.start();
public void run(){
try{
while (true){
String line = i.readLine();
output.append(line + "\n");
catch (IOException ex){
ex.printStackTrace();
finally{
o.close();
public static void main (String args[]) throws IOException{
Socket sock = null;
String addr = "127.0.0.1";
if (args.length > 0){
addr = args[0];
sock = new Socket(addr, 4449);
new ChatClient("Chat Client", sock);
} -
Modify the TicTacToeServer /client from deitel How to program
We've been given example code from the deitel & deitel book how to program and have to carry out the following alterations:
a) Modify the TicTacToeServer class to test for a win, loss or draw on each move in the game. Send a message to each client applet that indicates the result of the game when the game is over.
b) Modify the TicTacToeClient class to display a button that when clicked allows the client to play another game. The button should be enabled only when a game completes. Note that both class TicTacToeClient and class TicTacToeServer must be modified to reset the board and all state information. Also, the other TicTacToeClient should be notified that a new game is about to begin so its board and state can be reset.
c) Modify the TicTacToeClient class to provide a button that allows a client to terminate the program at any time. When the user clicks the button, the server and the other client should be notified. The server should then wait for a connection from another client so a new game can begin.
d) Modify the TicTacToeClient class and the TicTacToeServer class so the winner of a game can choose game piece X or O for the next game. Remember: X always goes first.
So far I have only been able to do part a) of the exercise im having a lot of difficulty with part b) which allows the client to play a new game.The code ive done so far is listed below if anyone can help i would be forever greatful. Thanks
// Fig. 18.9: TicTacToeClient.java
// Client that let a user play Tic-Tac-Toe with another across a network.
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
public class TicTacToeClient extends JApplet implements Runnable, ActionListener {
private JButton Button;
private JTextField idField;
private JTextArea displayArea;
private JPanel boardPanel, panel2;
private Square board[][], currentSquare;
private Socket connection;
private DataInputStream input;
private DataOutputStream output;
private char myMark;
private boolean myTurn;
private final char X_MARK = 'X', O_MARK = 'O';
boolean done=false;
Container container;
// Set up user-interface and board
public void init()
container = getContentPane();
// set up JTextArea to display messages to user
displayArea = new JTextArea( 4, 30 );
displayArea.setEditable( false );
container.add( new JScrollPane( displayArea ), BorderLayout.SOUTH );
// set up panel for squares in board
boardPanel = new JPanel();
boardPanel.setLayout( new GridLayout( 3, 3, 0, 0 ) );
// create board
board = new Square[ 3 ][ 3 ];
// When creating a Square, the location argument to the constructor
// is a value from 0 to 8 indicating the position of the Square on
// the board. Values 0, 1, and 2 are the first row, values 3, 4,
// and 5 are the second row. Values 6, 7, and 8 are the third row.
for ( int row = 0; row < board.length; row++ ) {
for ( int column = 0; column < board[ row ].length; column++ ) {
// create Square
board[ row ][ column ] = new Square( ' ', row * 3 + column );
boardPanel.add( board[ row ][ column ] );
// textfield to display player's mark
idField = new JTextField();
idField.setEditable( false );
container.add( idField, BorderLayout.NORTH );
Button = new JButton("New Game");
container.add(Button, BorderLayout.BEFORE_FIRST_LINE);
// set up panel to contain boardPanel (for layout purposes)
panel2 = new JPanel();
panel2.add( boardPanel, BorderLayout.CENTER );
container.add( panel2, BorderLayout.CENTER );
} // end method init
// Make connection to server and get associated streams.
// Start separate thread to allow this applet to
// continually update its output in textarea display.
public void start()
// connect to server, get streams and start outputThread
try {
// make connection
connection = new Socket( getCodeBase().getHost(), 12345 );
// get streams
input = new DataInputStream( connection.getInputStream() );
output = new DataOutputStream( connection.getOutputStream() );
// catch problems setting up connection and streams
catch ( IOException ioException ) {
ioException.printStackTrace();
// create and start output thread
Thread outputThread = new Thread( this );
outputThread.start();
} // end method start
// control thread that allows continuous update of displayArea
public void run()
// get player's mark (X or O)
try {
myMark = input.readChar();
// display player ID in event-dispatch thread
SwingUtilities.invokeLater(
new Runnable() {
public void run()
idField.setText( "You are player \"" + myMark + "\"" );
myTurn = ( myMark == X_MARK ? true : false );
// receive messages sent to client and output them
while ( !done) {
processMessage( input.readUTF() );
} // end try
// process problems communicating with server
catch ( IOException ioException ) {
ioException.printStackTrace();
} // end method run
// process messages received by client
private void processMessage( String message )
// valid move occurred
if ( message.equals( "Valid move." ) ) {
displayMessage( "Valid move, please wait.\n" );
setMark( currentSquare, myMark );
// invalid move occurred
else if ( message.equals( "Invalid move, try again" ) ) {
displayMessage( message + "\n" );
myTurn = true;
// opponent moved
else if ( message.equals( "Opponent moved" ) ) {
// get move location and update board
try {
int location = input.readInt();
int row = location / 3;
int column = location % 3;
setMark( board[ row ][ column ],
( myMark == X_MARK ? O_MARK : X_MARK ) );
displayMessage( "Opponent moved. Your turn.\n" );
myTurn = true;
} // end try
// process problems communicating with server
catch ( IOException ioException ) {
ioException.printStackTrace();
} // end else if
else if ( message.equals("Game Over") ){
displayMessage("fuck sake" );
// simply display message
else
displayMessage( message + "\n" );
} // end method processMessage
// utility method called from other threads to manipulate
// outputArea in the event-dispatch thread
private void displayMessage( final String messageToDisplay )
// display message from event-dispatch thread of execution
SwingUtilities.invokeLater(
new Runnable() { // inner class to ensure GUI updates properly
public void run() // updates displayArea
displayArea.append( messageToDisplay );
displayArea.setCaretPosition(
displayArea.getText().length() );
} // end inner class
); // end call to SwingUtilities.invokeLater
// utility method to set mark on board in event-dispatch thread
private void setMark( final Square squareToMark, final char mark )
SwingUtilities.invokeLater(
new Runnable() {
public void run()
squareToMark.setMark( mark );
// send message to server indicating clicked square
public void sendClickedSquare( int location )
if ( myTurn ) {
// send location to server
try {
output.writeInt( location );
myTurn = false;
// process problems communicating with server
catch ( IOException ioException ) {
ioException.printStackTrace();
// set current Square
public void setCurrentSquare( Square square )
currentSquare = square;
public void actionPerformed(ActionEvent e) {
// I need code here
// private inner class for the squares on the board
private class Square extends JPanel {
private char mark;
private int location;
public Square( char squareMark, int squareLocation )
mark = squareMark;
location = squareLocation;
addMouseListener(
new MouseAdapter() {
public void mouseReleased( MouseEvent e )
setCurrentSquare( Square.this );
sendClickedSquare( getSquareLocation() );
} // end Square constructor
// return preferred size of Square
public Dimension getPreferredSize()
return new Dimension( 30, 30 );
// return minimum size of Square
public Dimension getMinimumSize()
return getPreferredSize();
// set mark for Square
public void setMark( char newMark )
mark = newMark;
repaint();
// return Square location
public int getSquareLocation()
return location;
// draw Square
public void paintComponent( Graphics g )
super.paintComponent( g );
g.drawRect( 0, 0, 29, 29 );
g.drawString( String.valueOf( mark ), 11, 20 );
} // end inner-class Square
} // end class TicTacToeClient
// Fig. 18.8: TicTacToeServer.java
// This class maintains a game of Tic-Tac-Toe for two client applets.
import java.awt.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
public class TicTacToeServer extends JFrame {
private char[] board;
private JTextArea outputArea;
private Player[] players;
private ServerSocket server;
private int currentPlayer;
private final int PLAYER_X = 0, PLAYER_O = 1;
private final char X_MARK = 'X', O_MARK = 'O';
int moves=0;
// set up tic-tac-toe server and GUI that displays messages
public TicTacToeServer()
super( "Tic-Tac-Toe Server" );
board = new char[ 9 ];
for (int i = 0; i<9; i++){
board[i] = ' ';
players = new Player[ 2 ];
currentPlayer = PLAYER_X;
// set up ServerSocket
try {
server = new ServerSocket( 12345, 2 );
// process problems creating ServerSocket
catch( IOException ioException ) {
ioException.printStackTrace();
System.exit( 1 );
// set up JTextArea to display messages during execution
outputArea = new JTextArea();
getContentPane().add( outputArea, BorderLayout.CENTER );
outputArea.setText( "Server awaiting connections\n" );
setSize( 300, 300 );
setVisible( true );
} // end TicTacToeServer constructor
// wait for two connections so game can be played
public void execute()
// wait for each client to connect
for ( int i = 0; i < players.length; i++ ) {
// wait for connection, create Player, start thread
try {
players[ i ] = new Player( server.accept(), i );
players[ i ].start();
// process problems receiving connection from client
catch( IOException ioException ) {
ioException.printStackTrace();
System.exit( 1 );
// Player X is suspended until Player O connects.
// Resume player X now.
synchronized ( players[ PLAYER_X ] ) {
players[ PLAYER_X ].setSuspended( false );
players[ PLAYER_X ].notify();
} // end method execute
// utility method called from other threads to manipulate
// outputArea in the event-dispatch thread
private void displayMessage( final String messageToDisplay )
// display message from event-dispatch thread of execution
SwingUtilities.invokeLater(
new Runnable() { // inner class to ensure GUI updates properly
public void run() // updates outputArea
outputArea.append( messageToDisplay );
outputArea.setCaretPosition(
outputArea.getText().length() );
} // end inner class
); // end call to SwingUtilities.invokeLater
// Determine if a move is valid. This method is synchronized because
// only one move can be made at a time.
public synchronized boolean validateAndMove( int location, int player )
boolean moveDone = false;
// while not current player, must wait for turn
while ( player != currentPlayer ) {
// wait for turn
try {
wait();
// catch wait interruptions
catch( InterruptedException interruptedException ) {
interruptedException.printStackTrace();
// if location not occupied, make move
if ( !isOccupied( location ) ) {
// set move in board array
board[ location ] = currentPlayer == PLAYER_X ? X_MARK : O_MARK;
// change current player
currentPlayer = ( currentPlayer + 1 ) % 2;
// let new current player know that move occurred
players[ currentPlayer ].otherPlayerMoved( location );
notify(); // tell waiting player to continue
// tell player that made move that the move was valid
return true;
// tell player that made move that the move was not valid
else
return false;
} // end method validateAndMove
// determine whether location is occupied
public boolean isOccupied( int location )
if ( board[ location ] == X_MARK || board [ location ] == O_MARK )
return true;
else
return false;
void gameOverCheck() {
boolean over = false;
// Check rows
for (int start=0; start < 9; start += 3)
over = over || ((board[start] != ' ') &&
(board[start] == board[start+1]) &&
(board[start] == board[start+2]));
// Check columns
for (int start=0; start < 3; start++)
over = over || ((board[start] != ' ') &&
(board[start] == board[start+3]) &&
(board[start] == board[start+6]));
// Check diagonals
over = over || ((board[0] != ' ') &&
(board[0] == board[4]) && (board[0] == board[8]));
over = over || ((board[2] != ' ') &&
(board[2] == board[4]) && (board[2] == board[6]));
if (over || (moves>=9))
for ( int i = 0; i < players.length; i++ )
players.gameOver(over ? (currentPlayer+1)%2 : -1 );
public static void main( String args[] )
TicTacToeServer application = new TicTacToeServer();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
application.execute();
// private inner class Player manages each Player as a thread
private class Player extends Thread {
private Socket connection;
private DataInputStream input;
private DataOutputStream output;
private int playerNumber;
private char mark;
protected boolean suspended = true;
boolean done = false;
// set up Player thread
public Player( Socket socket, int number )
playerNumber = number;
// specify player's mark
mark = ( playerNumber == PLAYER_X ? X_MARK : O_MARK );
connection = socket;
// obtain streams from Socket
try {
input = new DataInputStream( connection.getInputStream() );
output = new DataOutputStream( connection.getOutputStream() );
// process problems getting streams
catch( IOException ioException ) {
ioException.printStackTrace();
System.exit( 1 );
} // end Player constructor
// send message that other player moved
public void otherPlayerMoved( int location )
// send message indicating move
try {
output.writeUTF( "Opponent moved" );
output.writeInt( location );
// process problems sending message
catch ( IOException ioException ) {
ioException.printStackTrace();
void gameOver(int winner) {
try {
output.writeUTF( "Game Over. " +
(( winner == -1 ) ? "No winner." :
( "Winner is " + ( winner == 0 ? 'X' : 'O' ) + "." ) ) );
done=true;
output.writeUTF("Game Over");
} catch( IOException e ) {
e.printStackTrace(); System.exit( 1 );
public void run()
// send client message indicating its mark (X or O),
// process messages from client
try {
displayMessage( "Player " + ( playerNumber ==
PLAYER_X ? X_MARK : O_MARK ) + " connected\n" );
output.writeChar( mark ); // send player's mark
// send message indicating connection
output.writeUTF( "Player " + ( playerNumber == PLAYER_X ?
"X connected\n" : "O connected, please wait\n" ) );
// if player X, wait for another player to arrive
if ( mark == X_MARK ) {
output.writeUTF( "Waiting for another player" );
// wait for player O
try {
synchronized( this ) {
while ( suspended )
wait();
// process interruptions while waiting
catch ( InterruptedException exception ) {
exception.printStackTrace();
// send message that other player connected and
// player X can make a move
output.writeUTF( "Other player connected. Your move." );
while ( ! done ) {
// get move location from client
int location = input.readInt();
// check for valid move
if ( validateAndMove( location, playerNumber ) ) {
displayMessage( "\nlocation: " + location );
output.writeUTF( "Valid move." );
gameOverCheck();
else
output.writeUTF( "Invalid move, try again" );
// close connection to client
} // end try
// process problems communicating with client
catch( IOException ioException ) {
ioException.printStackTrace();
System.exit( 1 );
// end method run
// set whether or not thread is suspended
public void setSuspended( boolean status )
suspended = status;
} // end class Player
} // end class TicTacToeServerreply #1:
http://forum.java.sun.com/thread.jspa?threadID=5114663
&tstart=0@Op. Don't multi/cross-post -
What is the easiest way to show a command line app in an appletviewer
I'd like to convert a command line interface application to a small applet, for use in an appletviewer. What is the easiest way to implement this.
I made something like what you are describing for a text adventure engine. It uses a big text area for output and a small text field for input.
Here's the code
public class myApplet extends java.applet.Applet
implements Runnable
TextArea output ;
TextField input ;
public void init()
width = this.size().width ;
height = this.size().height ;
public void run()
makeComponents() ;
while( true ) // loop on + on + on
try { Thread.sleep( 10 ) ; }
catch (InterruptedException e) {}
public void makeComponents()
input = new TextField() ;
input.setSize( Math.min( 200, width - 5 ), 25 ) ;
input.setLocation( 5, height - 30 ) ;
add( input ) ;
input.addActionListener( new ActionListener()
public void actionPerformed( ActionEvent e )
String temp = input.getText() ; // do something with this
output = new TextArea( "", 0, 0, TextArea.SCROLLBARS_VERTICAL_ONLY) ;
output.setSize( width - 10, height - 40 ) ;
output.setLocation( 5, 5 ) ;
add( output ) ; -
Double click on break and the end container appears to be the parent div, but if you select just break with mouse the end container is a text node. If you continue to drag your mouse past the end of break you also get the parent div. Sample html:<br />
<br />
<pre><nowiki><!doctype html>
<html>
<body>
<div id="surroundingDiv1">
Break<br/>
</div>
<p>
<a href="#" onclick="showSelectionInfo()">Show Selection Info</a>
</p>
<label for="output"></label><textarea id="output" rows="20" cols="50"></textarea>
<script>
function showSelectionInfo() {
var range = null;
var sel = window.getSelection();
if (sel.rangeCount > 0 && sel.getRangeAt(0).toString() != "") {
range = sel.getRangeAt(0);
if (range != null) {
document.getElementById("output").innerHTML =
"Text: " + range.toString() +
"\n\nendContainer - " +
"\n\tid: " + range.endContainer.id +
"\n\tnodeName: " + range.endContainer.nodeName +
"\n\tnodeValue: " + range.endContainer.nodeValue +
"\n\tnodeType: " + range.endContainer.nodeType +
"\n\nstartContainer - " +
"\n\tid: " + range.startContainer.id +
"\n\tnodeName: " + range.startContainer.nodeName +
"\n\tnodeValue: " + range.startContainer.nodeValue +
"\n\tnodeType: " + range.startContainer.nodeType;
</script>
</body>
</html></nowiki></pre>In general theory, one now has the Edit button for their posts, until someone/anyone Replies to it. I've had Edit available for weeks, as opposed to the old forum's ~ 30 mins.
That, however, is in theory. I've posted, and immediately seen something that needed editing, only to find NO Replies, yet the Edit button is no longer available, only seconds later. Still, in that same thread, I'd have the Edit button from older posts, to which there had also been no Replies even after several days/weeks. Found one that had to be over a month old, and Edit was still there.
Do not know the why/how of this behavior. At first, I thought that maybe there WAS a Reply, that "ate" my Edit button, but had not Refreshed on my screen. Refresh still showed no Replies, just no Edit either. In those cases, I just Reply and mention the [Edit].
Also, it seems that the buttons get very scrambled at times, and Refresh does not always clear that up. I end up clicking where I "think" the right button should be and hope for the best. Seems that when the buttons do bunch up they can appear at random around the page, often three atop one another, and maybe one way the heck out in left-field.
While I'm on a role, it would be nice to be able to switch between Flattened and Threaded Views on the fly. Each has a use, and having to go to Options and then come back down to the thread is a very slow process. Jive is probably incapable of this, but I can dream.
Hunt -
AIR, Fonts, CS4 and the security sandbox
I have no idea why embedding fonts in CS4 using library->new font includes every european character EXCEPT polish. You have german, french, spanish, norwegian, but not polish. Well, since embedding a font from Flash is the only way to use bitmap fonts in Flex, I had to create a library of external font files, one SWF per font size and style. Such an SWF exposes several functions, such as returning a ready to use pre-formatted textfield, returning the font name (Such as Tahoma) and the font name you actually need to use (such as Tahoma_13pt_st).
I thought I'd need an AIR application to parse through all the fonts (and there are quite a few) extract the neccesary data, such as font size, name and so on and generate an XML file, so that I can load fonts at dynamic.
The first problem I encountered was the security sandbox. A possible solution was to use the loaderInfo.childSandboxBridge. That approach didn't work however, as I was generating plain SWF files from flash CS4. childSandboxBridge is an AIR property, so I had to create an AIR file and try to set the bridge property to a simple number. So I did, but it gave me a
SecurityError: Error #3206: Caller app:/TahomaBold13.swf cannot set LoaderInfo property childSandboxBridge.
Weird. Well, I reverted the file to plain CS4 FPL10 SWF and decided to try another approach. I first loaded the SWF as a FileStream, then put the bytes into Loader.loadBytes. That should take care of security. And it did, however it created another problem.
The font library relies on being able to enumerate the embeded fonts. The SWF's constructor has a function that enumerates all fonts and isolates the font embeded in the SWF, and then extracts it's properties. When launching the SWF by itself, or loading it from another CS4 FPL10 SWF it launches perfectly and enumerates the fonts as it should. However when the SWF is executed from inside AIR, the constructor located in the font file, as well as a function called from the main application upon executing enumerateFonts(false) both give an empty array. Which is quite weird really, as the loaded SWF contains an input TextField with embedded fonts. And I can edit and type stuff in that textfield, even while it's rotated.
I thought this might be an issue of a different flash player version, but I tried to target AIR 1.5 and flash 9, neither worked and both returned no embeded fonts.
Here's the entire source of the mxml air app
<?xml version="1.0" encoding="utf-8"?>
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Panel x="0" y="0" width="100%" height="100%" layout="absolute" title="M2C Studio Font Parser Utility">
<mx:VBox x="0" y="0" width="100%" height="100%" paddingRight="10" paddingLeft="10" paddingTop="10" paddingBottom="0">
<mx:HBox x="10" y="10" width="100%" height="95%">
<mx:VBox width="50%" height="100%">
<mx:Label text="Select font directory from filelist below"/>
<mx:FileSystemTree width="100%" height="50%" id="fileTree"/>
<mx:HRule width="100%"/>
<mx:Label text="Fonts list"/>
<mx:Text width="100%" height="50%" id="fontlist"/>
</mx:VBox>
<mx:VRule height="100%"/>
<mx:VBox width="50%" height="100%">
<mx:Label text="XML Output"/>
<mx:TextArea width="100%" height="50%" backgroundColor="#ECE9E9"/>
<mx:Canvas width="100%" height="50%" id="canv">
</mx:Canvas>
</mx:VBox>
</mx:HBox>
<mx:Button label="Generate XML from directory" width="100%" click="handlePress();"/>
</mx:VBox>
</mx:Panel>
<mx:Script>
<![CDATA[
import flash.utils.setInterval;
import com.m2cstudio.archont.utility.fonts.FontLibraryItem;
import com.m2cstudio.archont.utility.fonts.IFontLibraryItem;
import mx.accessibility.AlertAccImpl;
import mx.controls.*;
import mx.events.*;
import mx.controls.Alert;
var rx:RegExp = /^.*\.swf$/;
function handlePress():void
// This also throws an error
//Security.allowDomain("*");
var file:File = fileTree.selectedItem as File;
var aLoad:Array = new Array();
if(!file)
Alert.show("You must select a folder", "Error");
return;
} else if(!file.isDirectory) {
Alert.show("You must select a folder, not a file", "Error");
return;
var aList:Array = file.getDirectoryListing();
for each (var fil:File in aList)
if(!fil.isDirectory)
if(fil.nativePath.match(rx))
// Is swf
var fs:FileStream = new FileStream();
fs.addEventListener(Event.COMPLETE, handleFileStreamLoaded);
fs.openAsync(fil, FileMode.READ);
function handleFileStreamLoaded(e:Event):void
var fs:FileStream = e.target as FileStream;
var ld:Loader = new Loader();
var lc:LoaderContext = new LoaderContext();
var ba:ByteArray = new ByteArray();
lc.allowLoadBytesCodeExecution = true;
fs.readBytes(ba);
fs.close();
ld.contentLoaderInfo.addEventListener(Event.COMPLETE, handleLoaded);
ld.loadBytes(ba, lc);
function handleLoaded(e:Event):void
var cnt:FontLibraryItem = e.target.content as FontLibraryItem;
cnt.rotation=10; // Rotation, just to be sure it's not using system fonts
canv.rawChildren.addChild(cnt);
// This doesn't output anything - neither the main app nor the loaded SWF 'see' any embedded fonts, even though the later uses them!
for each (var f:Font in Font.enumerateFonts(false))
Alert.show(f.fontName, f.fontType);
// This should retrieve the appropriate values but throws an error because the SWF can't grab the Font definition
//Alert.show(cnt.getFontName(), cnt.getFontStyle());
]]>
</mx:Script>
</mx:WindowedApplication>
Here's a screen of what it actually looks like when compiled:
Here's the source of the font library item. Note that the SWF contains only 2 items. A TextField named font with embeded characters and a boolean bt on the first frame.
package com.m2cstudio.archont.utility.fonts
import flash.display.MovieClip;
import flash.text.*;
public dynamic class FontLibraryItem extends MovieClip implements IFontLibraryItem
private var txtFont:TextField;
private var fFont:Font;
public function FontLibraryItem()
super();
// Causes an error - see below why
//init();
public function getFontName():String
return fFont.fontName;
public function getFontType():String
return fFont.fontType;
public function getFontStyle():String
return fFont.fontStyle;
public function getBitmapText():Boolean
return this.bt;
public function getBitmapTextSize():uint
if(this.bt) {
return Number(txtFont.defaultTextFormat.size);
} else {
return 0;
public function hasGlyphs(glyphs:String):Boolean
return fFont.hasGlyphs(glyphs);
public function createTextField():TextField
var tf:TextField = new TextField();
tf.embedFonts = true;
tf.defaultTextFormat = (this.font as TextField).defaultTextFormat;
return tf;
public function init():void
if(this.font) {
txtFont = this.font;
} else {
throw new Error("Document must contain a textfield named 'font' with the embedded font");
var fArr:Array = Font.enumerateFonts(false);
if(fArr.length==0) {
throw new Error("Document does not contain any embeded fonts.");
} else if (fArr.length>1) {
throw new Error("Document must contain not more than one embedded font");
fFont = fArr[0];
I'm hoping some AIR specialists will take a look at this. Frankly I'm stumped. Font support in Flash was always black magic, more or less, so I can only hope this is an issue that can be solved.
Just tell me and I'll provide more source or sceenshots.
Cheers,
-archontI even tried porting the code to Gumbo and running it there - still, no fonts are being enumerated.
If you're too lazy to read the whole above post, here's the problem in one sentence
An SWF that contains a textfield with embedded fonts, when launched by itself succeeds to return the embedded font using Font.enumerateFonts(false), however when loaded using Loader.loadBytes into AIR, it fails to see those fonts even though the textfield in it is displayed and editable.
How do I make the loaded child application and AIR see the embedded font? -
Problem on Creating Unix Termial in java like windows command prompt
hi all,
i created an unix terminal using java swing(to connect unix server and executing commands). here i redirect the console output to textarea. The problem is i can't read the input from the textarea. and another problem is how to disable the editable option in the textarea before to the command read line. The terminal is like a putty. Any One Please give a suggestion for this problem.sabre150 wrote:
georgemc wrote:
LinaGsp wrote:
5)then I run this command "jar cvfm MyJar.jar manifest.mf .class"If this is exactly what you did, and not a typo, that's probably your problem. Do you have a file called .class?It is more likely that the forum markup is getting in the way.Of course it is! D'oh! I seem to have a blind spot to that, I never take it into consideration...
OP, listen to these guys, ignore this blind old fool :-( -
Urgent!!!! problems with Toolbar
Hi ,
I have Toolbar with buttons on it. I also have 3 tables
and i'm trying to display them in a panel depending upon the button that is being clicked by the user.For this i have written action listeners which are not working properly. Following is the code and i'll be greatful if u can advise me in this regard. Any kind of suggestion or direction to helpful links is appreciated.....Treat this as
very urgent......
import javax.swing.JToolBar;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import javax.swing.AbstractButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import java.awt.*;
import java.awt.event.*;
public class ToolBarTest extends JFrame {
protected JTextArea textArea;
protected String newline = "\n";
JPanel contentPane = new JPanel();
public ToolBarTest() {
//Do frame stuff.
super("ToolBarDemo");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
//Create the toolbar.
JToolBar toolBar = new JToolBar();
addButtons(toolBar);
//Create the text area used for output.
// textArea = new JTextArea(5, 30);
TableDemo1 generaltable=new TableDemo1();
JTable table=new JTable();
table.setModel(generaltable);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setViewportView(table);
//Lay out the content pane.
// JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout());
contentPane.setPreferredSize(new Dimension(400, 100));
contentPane.add(toolBar, BorderLayout.NORTH);
contentPane.add(scrollPane, BorderLayout.CENTER);
setContentPane(contentPane);
protected void addButtons(JToolBar toolBar) {
JButton button = null;
ImageIcon general=new ImageIcon("ql3nava.gif");
//first button
button = new JButton("General",general);
button.setToolTipText("General");
button.setVerticalTextPosition(AbstractButton.BOTTOM);
button.setHorizontalTextPosition(AbstractButton.CENTER);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
repaint();
JTable table1=new JTable();
TableDemo1 test1=new TableDemo1();
table1.setModel(test1);
JScrollPane scrollPane1 = new JScrollPane(table1);
scrollPane1.setViewportView(table1);
JPanel panel1=new JPanel();
panel1.add(scrollPane1);
toolBar.add(button);
ImageIcon chart=new ImageIcon("ql3nava.gif ");
//second button
button = new JButton("BarGraph",chart);
//new ImageIcon("Chart.bmp"));
button.setToolTipText("Bar Graph");
button.setVerticalTextPosition(AbstractButton.BOTTOM);
button.setHorizontalTextPosition(AbstractButton.CENTER);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JTable table2=new JTable();
TableDemo2 test2=new TableDemo2();
table2.setModel(test2);
JScrollPane scrollPane2 = new JScrollPane(table2);
scrollPane2.setViewportView(table2);
JPanel panel2=new JPanel();
panel2.add(scrollPane2);
toolBar.add(button);
ImageIcon pie=new ImageIcon("ql3nava.gif");
//third button
button = new JButton("PieGraph",pie);
//new ImageIcon("pie.bmp"));
button.setToolTipText("Pie Graph");
button.setVerticalTextPosition(AbstractButton.BOTTOM);
button.setHorizontalTextPosition(AbstractButton.CENTER);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JTable table3=new JTable();
TableDemo3 test3=new TableDemo3();
table3.setModel(test3);
JScrollPane scrollPane3 = new JScrollPane(table3);
scrollPane3.setViewportView(table3);
JPanel panel3=new JPanel();
panel3.add(scrollPane3);
toolBar.add(button);
//Fourth Button
ImageIcon refresh=new ImageIcon("ql3nava.gif");
button = new JButton("Refresh",refresh);
//new ImageIcon("Refresh.bmp"));
button.setToolTipText("Refresh");
button.setVerticalTextPosition(AbstractButton.BOTTOM);
button.setHorizontalTextPosition(AbstractButton.CENTER);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// protected void displayResult(Component comp) {
// JPanel.add(Component comp);
// System.out.println(comp);
public static void main(String[] args) {
ToolBarTest frame = new ToolBarTest();
frame.pack();
frame.setVisible(true);
}Thanks,
AnitaAnita,
Your program misses one line in all ActionListeners
add this line after
<pre>
panel2.add(scrollPane2);
//add this
getContentPane().add(panel2);
</pre>
let me know if it helps.,
vinod -
FileDialog error :o(
Can someone please help me? I'm not sure why the class "OpenDialogFile" below is not working. I really appreciate your help.
I got this following error:
ChatClient.java:66: cannot resolve symbol
symbol : constructor FileDialog (ChatClient.OpenDialogFile,java.lang.String,int
location: class java.awt.FileDialog
fd = new FileDialog(this, "OPEN", FileDialog.LOAD);
Here is my code:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class ChatClient {
private TextArea output;
private TextField input;
private Button sendButton;
private Button quitButton;
private Button openFileButton;
public FileDialog fd;
public ChatClient() {
output = new TextArea(10,50);
input = new TextField(50);
sendButton = new Button("Send");
quitButton = new Button("Quit");
openFileButton = new Button("Open File");
public void launchFrame() {
Frame frame = new Frame("Chat Room");
frame.setLayout(new BorderLayout());
frame.add(output,BorderLayout.WEST);
frame.add(input,BorderLayout.SOUTH);
Panel p1 = new Panel();
p1.add(sendButton);
p1.add(quitButton);
p1.add(openFileButton);
frame.add(p1,BorderLayout.CENTER);
// Attach listener to the appropriate components
sendButton.addActionListener(new SendHandler());
frame.addWindowListener(new CloseHandler());
input.addActionListener(new InputHandler());
quitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
openFileButton.addActionListener(new OpenDialogFile());
frame.pack();
frame.setVisible(true);
private void copyText() {
String text = input.getText();
output.setText(output.getText()+text+"\n");
input.setText("");
private class SendHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
copyText();
private class OpenDialogFile implements ActionListener {
public void actionPerformed(ActionEvent e) {
fd = new FileDialog(this, "OPEN", FileDialog.LOAD);
fd.show();
private class CloseHandler extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
private class InputHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
copyText();
public static void main(String[] args) {
ChatClient c = new ChatClient();
c.launchFrame();
}All constructors for FileDialog require an instance of Frame as a parent. ChatClient.OpenFileDialog apparently doesn't meet this requirement hence compiler is complaining.
DB -
Drawin text using Graphics Packages!
Hello. I am a newbie to this forum. I have been writing this program for a long time now for my 6th year advanced higher project. Im planning to write a program which can take in input strings (from keyboard) and after pressing a button, the program will draw the strings onto output - say textarea/ panel etc..
Im planning to make my program multi functional in future, not just able to draw strings but also to draw shapes aswell. The first step is to make the simple task possible - draw strings which im quite stuck at. Im plannig to use swing (not sure if thats the right option).
Currently im using JPanel for the graphics to be drawn on.
below is my code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Drawing extends JFrame{
final JTextField input = new JTextField();
DrawingPanel drawingPanel = new DrawingPanel();
Container content = getContentPane();
JLabel date = new JLabel("Date:");
JTextField inputdate = new JTextField();
JButton Draw = new JButton("Draw");
JLabel initial = new JLabel("Initials:");
JLabel name = new JLabel("Name:");
JButton a = new JButton("test");
JButton b = new JButton("are");
public Drawing(){
super("Drawing Initials!!!");
drawingPanel.setPreferredSize(new Dimension(200, 100));
drawingPanel.setBorder(BorderFactory.createLineBorder(Color.black));
makeContentPane();
pack();
setVisible(true);
public Container center() {
return drawingPanel;
public Container north() {
input.setPreferredSize(new Dimension(60, 20));
JPanel inputPanel = new JPanel(new GridLayout());
inputPanel.add(name);
inputPanel.add(input);
JPanel datePanel = new JPanel(new GridLayout());
datePanel.add(date);
datePanel.add(inputdate);
JPanel top = new JPanel();
top.setLayout(new BorderLayout());
top.add(inputPanel, BorderLayout.WEST);
top.add(datePanel, BorderLayout.CENTER);
return top;
public Container south() {
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.BLUE);
buttonPanel.add(Draw);
Draw.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
DrawingPanel drawingPanel5 = new DrawingPanel(input.getText());
drawingPanel5.repaint();
content.add(drawingPanel5, BorderLayout.CENTER);
//input.setText("");
inputdate.setText("feb");
return buttonPanel;
public Container east() {
JPanel p = new JPanel(new GridLayout(2, 1));
p.add(a);
p.add(b);
JPanel flow = new JPanel();
flow.add(p);
return flow;
public void makeContentPane() {
JMenuBar menubar = new JMenuBar();
setJMenuBar(menubar);
//--------Menus in the menuBar-------//
JMenu fileMenu = new JMenu("File");
menubar.add(fileMenu);
JMenu helpMenu = new JMenu("Help");
menubar.add(helpMenu);
content.setLayout(new BorderLayout());
content.add(north(), BorderLayout.NORTH);
content.add(drawingPanel, BorderLayout.CENTER);
content.add(east(), BorderLayout.EAST);
content.add(south(), BorderLayout.SOUTH);
content.add(initial, BorderLayout.WEST);
public static void main(String[] args) {
Drawing d = new Drawing();
import java.awt.*;
import javax.swing.*;
public class DrawingPanel extends JPanel {
private int fontSize = 20;
private String message;
public DrawingPanel() {
setBackground(Color.white);
Font font = new Font("Serif", Font.PLAIN, fontSize);
setFont(font);
message = "";
//repaint();
public DrawingPanel(String m) {
message = m;
setBackground(Color.white);
Font font = new Font("Serif", Font.PLAIN, fontSize);
setFont(font);
//repaint();
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
g.drawString(message, 50, 50);
}The following above is the two class i have done already; the problem is im not sure how to take in input of strings and pass that as a parameter to (drawingpanel class) which does the actual drawing. Im still wondering if thats possible though??
feel free to post anything?
Any help - much appreciated
Many Thanks!!!You don't want to create a new DrawingPanel with each press of the button. Rather, you need to pass a string to the current drawing panel through one of its methods, say the setMessage() method that you will create. After calling this method, then call drawingPanel.repaint(); Something like so:
public Container south()
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.BLUE);
buttonPanel.add(Draw);
Draw.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ev)
drawingPanel.setMessage(input.getText()); // you will need to create this method.
drawingPanel.repaint();
//DrawingPanel drawingPanel5 = new DrawingPanel(input.getText());
//drawingPanel5.repaint();
//content.add(drawingPanel5, BorderLayout.CENTER);
//input.setText("");
//inputdate.setText("feb");
return buttonPanel;
}
Maybe you are looking for
-
Behaviors on a simple a link?
I am using DW CS3 on a mac, I have a a table which is a library item it has 9 cells with text in each, each text is an <a> link to a page. I am looking through the books I have, they describe how to set behaviors to do a lot of things, but what I wa
-
Server admin fails to start tomcat only
Hi, we just upgraded our server from 10.3 to 10.4. after the upgrade - the server admin tools fail to start tomcat only. sooooo when i start tomcat only service - the app says its running. but i can't connect to port 80 to show me the default page or
-
Version Cue Log Files Corrupted.
Address: Version Cue CS2 > config > configuration. I'm trying to create a back up of my hard drive, as a precaution whilst running an Adobe Clean script but the back up software is finding corrupt Version Cue log files. Are these files critical? Is i
-
Will osx mountain lion airplay work on my 2009 macbook
Just wondering if the new osx will work on my 2009 macbook. In particular the air play feature.
-
Customer service and training of employees
I have just got home from one of the worst experience I have every had at any retail establishment. I found that the employees were poorly trained. They had no idea how to transfer a pre paid phone from and old one to a new one. They had no idea