Writing in a Text Area from a different class.

Hi,
I need to write some text in a Text Area which is in a class I've call GUI where I handle all the graphic stuff but I need to do it from another class which handles packets that come through a COM port.
Is there anyway to do that?
Thanks!

Thank you! I'll try that but I think I might have problems with that since an instance of the Gui class was already created. I'm using the NetBeans Gui design form wich already makes the code for the Gui and this is what I have public class Gui extends javax.swing.JFrame {
    Connection connection = new Connection();
    /** Creates new form Gui */
    public Gui() {
        initComponents();
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {
        bnConectar = new javax.swing.JButton();
        cbPuerto = new javax.swing.JComboBox();
        lblPuerto = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        taPuerto = new javax.swing.JTextArea();
        bnPing = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        mArchivo = new javax.swing.JMenu();
        miNuevoP = new javax.swing.JMenuItem();
        miCargarP = new javax.swing.JMenuItem();
        miGuardarP = new javax.swing.JMenuItem();
        miSalir = new javax.swing.JMenuItem();
        mEdicion = new javax.swing.JMenu();
        mMonitorizacion = new javax.swing.JMenu();
        miMonON = new javax.swing.JMenuItem();
        miMonOFF = new javax.swing.JMenuItem();
        miPing = new javax.swing.JMenuItem();
        miConfig = new javax.swing.JMenuItem();
        mAyuda = new javax.swing.JMenu();
        miAcerca = new javax.swing.JMenuItem();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Monitorizaci?n");
        bnConectar.setFont(new java.awt.Font("Tahoma", 1, 11));
        bnConectar.setText("Conectar");
        bnConectar.setToolTipText("Conecta con el puerto seleccionado.");
        bnConectar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bnConectarActionPerformed(evt);
        cbPuerto.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        lblPuerto.setFont(new java.awt.Font("Tahoma", 1, 14));
        lblPuerto.setText("Puerto");
        taPuerto.setColumns(20);
        taPuerto.setRows(5);
        jScrollPane1.setViewportView(taPuerto);
        bnPing.setFont(new java.awt.Font("Tahoma", 1, 11));
        bnPing.setText("Ping");
        bnPing.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bnPingActionPerformed(evt);
        mArchivo.setText("Archivo");
        miNuevoP.setText("Nuevo Proyecto");
        mArchivo.add(miNuevoP);
        miCargarP.setText("Cargar Proyecto");
        mArchivo.add(miCargarP);
        miGuardarP.setText("Guardar Proyecto");
        mArchivo.add(miGuardarP);
        miSalir.setText("Salir");
        mArchivo.add(miSalir);
        jMenuBar1.add(mArchivo);
        mEdicion.setText("Edici?n");
        jMenuBar1.add(mEdicion);
        mMonitorizacion.setText("Monitorizaci?n");
        miMonON.setText("Monitorizaci?n ON");
        mMonitorizacion.add(miMonON);
        miMonOFF.setText("Monitorizaci?n OFF");
        mMonitorizacion.add(miMonOFF);
        miPing.setText("Ping");
        mMonitorizacion.add(miPing);
        miConfig.setText("Configuraci?n");
        mMonitorizacion.add(miConfig);
        jMenuBar1.add(mMonitorizacion);
        mAyuda.setText("Ayuda");
        miAcerca.setText("Acerca");
        mAyuda.add(miAcerca);
        jMenuBar1.add(mAyuda);
        setJMenuBar(jMenuBar1);
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblPuerto)
                        .addGap(17, 17, 17)
                        .addComponent(cbPuerto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(bnPing)
                        .addComponent(bnConectar)))
                .addGap(45, 45, 45)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(287, Short.MAX_VALUE))
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(cbPuerto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblPuerto))
                        .addGap(18, 18, 18)
                        .addComponent(bnConectar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE)
                        .addComponent(bnPing)
                        .addContainerGap(172, Short.MAX_VALUE))))
        pack();
    }// </editor-fold>
    private void bnConectarActionPerformed(java.awt.event.ActionEvent evt) {                                          
        try{
           connection.connect();
        }catch (XBeeException e){
    private void bnPingActionPerformed(java.awt.event.ActionEvent evt) {                                      
        try{
           connection.ping();
        }catch (XBeeException e){
    * @param args the command line arguments
    public static void main(String args[]) throws Exception, InterruptedException {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
               new Gui().setVisible(true);
    }Would that be a problem?
Thanks again!

Similar Messages

  • I accidentally linked my wife's phone number with mine. Now I am getting MY text messages that I send to her. It even says my texts are from her. How can I fix it?

    I accidentally linked my wife's phone number with mine. Now I am getting MY text messages that I send to her. It even says my texts are from her. How can I fix it?

    You can't "link" phone numbers but you can, and did add her email address to your iMessage send/receive list.  This often happens when you both use the same Apple ID
    Settings > Messages  > Send & Receive > you can be reached by iMessage at >
    Settings > Messages > Send and Receive > start mew conversations from ?
    You are receiving your own messages because the same email address is on both lists

  • Invoke a method in one class from a different class

    I am working on a much larger project, but to keep this simple, I wrote out a little test that would convey the over all theory of the program.
    What I am doing is starting out with a 2 JFrames and a Class. When the program is launched, the first JFrame opens. In this JFrame is a label and a button. When the button is clicked, the second JFrame opens. This JFrame has a textField and a button. The user puts the text in the textField and presses the button. When the button is pushed, I want the text that was just put in the textField, to be displayed in the first JFrame's label. I am trying to invoke a method in the first JFrame from the second, but nothing happens. I have also tried making the Class extend from JFrame1 and invoke it from there, but no luck. So, how do I invoke a method in a class from a different class?
    JFrame1 (I omitted the layout part. I made this in Netbeans so its pretty long)
    public class NewJFrame1 extends javax.swing.JFrame {
         private NewClass1 nC = new NewClass1();
         /** Creates new form NewJFrame1 */
         public NewJFrame1() {
              initComponents();
              jLabel1.setText("Chuck");
         public void setLabels()
              jLabel1.setText(nC.getName());
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                                  
         NewJFrame2 j2 = new NewJFrame2();
         j2.setVisible(true);The class
    public class NewClass1 {
         public static String name;
         public NewClass1()
         public NewClass1(String n)
              name = n;
         public String getName()
              return name;
         public void setName(String n)
              name = n;
    }The second jFrame
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                                  
         NewClass1 nC = new NewClass1();
         NewJFrame1 nF = new NewJFrame1();     
         nC.setName(jTextField1.getText());
         nF.setLabels();
         System.out.println(nC.getName());At this point I am begging for help. I have been trying for days to figure this out, and I just feel like I am not getting anywhere.
    Thanks

    So, how do I invoke a method in a class from a different class?Demo:
    public class Main {
        public static void main(String [] args) {
         Test1 t1 = new Test1();
         Test2 t2 = new Test2();
         int i = t1.method1();
         String s = t2.method2(i);
         System.out.println(s);
    class Test1 {
        public int method1() {
         return 10;
    class Test2 {
        public String method2(int i) {
         if (i == 10)
             return "ten";
         else
             return "nothing";
    }Output is "ten".
    Edited by: newark on May 28, 2008 10:55 AM

  • Updating Jlabel from a different class?

    Hi,
    Im in the middle of developing a program but swing is making it very hard for me to structure my code. The problem is I want to update the text of a Jlable from a different class when a button is pressed. THe event handling is done by a different class than the where the Jlabel is initiated which is why i think it doesnt work. But when the button is pressed it does execute a method from the main class that has the .setText() in it. Why wont the Jlabel update? Thank you

    Thanks for your help but i am still having trouble.
    This is the code from the button handler class
    public void actionPerformed(ActionEvent e)
           if ("btn3_sender".equals(e.getActionCommand()))
                JLabel j = temp2.getlblQuestion();
               j.setText("NEW TEXT");
           This is the code from the main class where the JLabel is created:
    public JLabel getlblQuestion()
        return lblQuestion;
    }How come this does not work??

  • Updating JPanel with buttons from a different class

    I have a JPanel in a class that has a gridlayout with buttons in it for a game board. And my problem is that when I want to update a button using setIcon() the button doesn't change in the GUI because the buttons are in a different class. The JPanel is in a Client class and the buttons are in a GamePlugin class. I've tried a bunch of different things but none of them worked or it was way too slow. I'm sure theres an easy way to do it that I'm not seeing. Any suggestions? Heres part of my code for updating the GUI.
    private JPanel boardPanel = new JPanel(); 
    Container cP = getContentPane();
    cP.add(boardPanel, BorderLayout.WEST);
    boardPanel.setPreferredSize(new Dimension(400, 400));
    boardPanel.setLayout(new GridLayout(8, 8));
    cP.add(optionsPanel, BorderLayout.CENTER);
          * Gets the board panel from the selected plugin.
         public void drawGameBoard(GamePlugin plugin) {
              board = (OthelloPlugin)plugin;
              boardPanel = board.getBoardPanel();
              for (int i = 0; i < GamePlugin.BOARD_SIZE; i++)
                   for (int j = 0; j < GamePlugin.BOARD_SIZE; j++) {
                        board.boardButtons[i][j].setActionCommand("" + i + "" + j);
                        board.boardButtons[i][j].addActionListener(this);
          * This method takes a GameBoard and uses it to update this class' data
          * and GUI representation of the board.
         public void updateBoard(GamePlugin updatedBoard) {
              board = (OthelloPlugin)updatedBoard;
              for (int i = 0; i < GamePlugin.BOARD_SIZE; i++) {
                   for (int j = 0; j < GamePlugin.BOARD_SIZE; j++) {
                        int cell = board.getCell(i,j);
                        if (cell == OthelloPlugin.PLAYER1){
                             board.boardButtons[i][j].setIcon(black);
                        else if (cell == OthelloPlugin.PLAYER2)
                             board.boardButtons[i][j].setIcon(white);
                        else
                             board.boardButtons[i][j].setText("");
         }

    txp200:
    I agree that a call to validate() , possibly repaint(), should fix your problem. In the class with the panel that the buttons are on, i would create a static repaint method that call panel.repaint(). You can then call that method in your other class. Just make sure u only use methods to change the properties of the button, never make a make a new one, as then you will lose the association with the panel. Hope this helps.
    -- Brady E

  • Access text area from different video

    So here is what I have. I have a master.swf that loads
    another tester.swf into it. Below is the code for the three swf's.
    Another swf called tester2 is loaded into a higher layer of
    tester.swf. So here is how it looks and what each layer contains:
    master.swf
    loads tester.swf into layer 5
    loads tester2.swf into layer 6

    Thanks, I figured it out after trying what you told me. In
    the master.swf I needed to refer to the loadedInfo box in level 6
    and not 5.
    myLV.onLoad = function (success) {
    if (success) {
    _level6.loadedInfo.htmlText = myLV.info;
    } else {
    _level6.loadedInfo.text = "hhhhhhhng the requested
    information. Please contact the Webmaster and report your error.";
    originally _level6 was _level5. This is my myLV refers
    loadedInfo text area.

  • Reading and writing to a text file from an Applet

    I'm a novice java programming with very little formal programming training. I've pieced together enough knowledge to do what I've wanted to do so far...
    However, I've been unable to figure out how to read and write to a text file from an Applet (I can do it from a normal java program just fine). Here is a simple example of what I'd like to do (you can also look at it on my website: www.stat.colostate.edu/~leach/test02/test02.html). I know that there is some problem with permission/security but I'm not smart enough to understand what the error messages are telling or understand the few books I have. If anyone can tell me how to get this applet to work, or direct me to some referrences that would help me out I'd really appreciate it.
    Thanks,
    Andy
    import java.applet.Applet;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.io.*;
    public class test02 extends Applet {
    public Button B_go;
    public GridBagConstraints c;
    public void init() {
    this.setLayout(new GridBagLayout());
    c = new GridBagConstraints();
    c.fill = GridBagConstraints.BOTH;
    B_go = new Button("GO");
    c.gridx=1; c.gridy=0; c.gridwidth=1; c.gridheight=1;
    c.weightx = c.weighty = 0.0;
    B_go.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
    print_stuff();
    setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    this.add(B_go,c);
    public static void print_stuff() {
    try{
    File f = new File("test02.txt");
    PrintWriter out = new PrintWriter(new FileWriter(f));
    out.print("This is test02.txt");
    out.close();
    }catch(IOException e){**/}
    }

    I have almost the exact same problem, and I am in the same situation as you are with respects to the language.
    I am simply trying to create a file and output some garbage to it but my applet always spits back a security violation. I've tried eliminating the restrictions on the applet runner I use but I still get the error.
    My method:
    debug = new Label() ;
    debug.setLocation( 20, 20 ) ;
    debug.setSize( 500, 15 ) ;
    add( debug ) ;
    // output
    try
         OutputStream file = new FileOutputStream( new File( "" + getCodeBase() + "output.txt" ) ) ;
         byte[] buffer = { 1, 2, 3, 4, 5 } ;
         file.write( buffer ) ;
         file.close() ;
    } catch( Exception e )
         debug.setText( e.toString() ) ;
         Can anyone tell why this isnt working?

  • Set a value on a  text area from a lookup table and then edit it

    I work in a form of a PO system.
    On the PO_line form, there is a Select list aginst the item table (displays Item.description and returns item.ID).
    On the PO_line, the requirement is to have a text area named PO_Line.LineItemDescription where the moment of item selection will be populated with the Item.description.
    After the selection of the Item, the user must be able to edit the PO_Line.LineItemDescription and save it.
    If the user decides to go back and edit the line, if the PO_Line.LineItemDescription is manually edited it must remain as is, otherwise it must follow any item.id changes.
    Any ideas how to implement?

    Goto the property inspector of table
    in common have rowselect atribute select it as single
    then go to the datacontrol expand your view object there is one node called operation expand operation
    drag 'delete' and drop into your page create as command button.
    run your page select one row and click the button it willbe delete from the view object
    if you want to delete it from database you shoul commit it

  • Submit Query(SQL) from a text area from a form

    Hi,
    I have a form that has a big text area, while users can type in the SQL statement/query.
    When user click on the button(say Submit). He/She should able to use the SQL query they input to query the tables.
    In order to implement this, should I create a new page that will pass the value of the text area (SQL statement) and display it in that new page?
    Or Is there a quick/easier way to do this?
    Thanks,
    Angela

    Angela,
    You could create a report region of type PL/SQL function returning SQL querry, and then return the value of your text area item, so you region source would be something like this:
    return :PX_MY_QUERY;
    When creating that report region, you'll have to use generic column names, since at design time, the query isn't known.
    Regards,
    Marc

  • Updating Swing components from a different class

    I would like to use the JTextArea component in a JFrame to display fast updating text from my application. My application is very simple. When the app launches the GUI is created then my application engine would start processing and displaying text data into the GUI. After reading about Thread safety when using Swing components I concluded it would not be a good idea for my app engine class to update the JTextArea class directly using methods such as .append(String).
    I would be grateful for any suggestions on how I should approach updating Swing components from different classes.
    Many Thanks in advance Sean

    Hi
    Why don't you just implement a basic callback method?
    To do this the right way you should probably define a simple Interface that has a public method like updateProcessText(String s). Your swing class then implements this interface, basically forcing it to provide the public method you defined (this is no different than implementing ActionListener, which forces you to define actionPerformed). Secondly modify your processing class, so that it take's a class that implements the interface you just created, as one of the arguments in it's constructor. Lastly assign the argument from your construnctor to a private var - this will enable your processing class to have a handle to your swing class and update it as it pleases.
    This might sound very complex, but it's really simple once you've done it once.

  • How do I sum selected entries (currency) in one column based on criteria (specific text) set from a different column?

    Disclaimer:  I'm not a computer guy but I can be taught!
    I am tracking a checking account for a church ministry.  I have one table that holds the line items and the amounts budgeted for each item.  I want to add a column to that table that shows the actual amount spent for that line item.  The reference will come from the second table that contains that actual data.  I have a column that has a dropdown list to select the budget line item and a column that holds the actual amount spent for that transaction.  I want to auto sum the selected currency values based on the selection criteria of the certain budget line item and display it in the first table.
    Any help would be appreciated.

    Hi wcanerday,
    Thanks for the green tick and your feedback. Yes, the SUMIF function is powerful!
    When you adapt the Personal Budget template, make sure that the items in the Category Column (A) on the Budget sheet exactly match the items in the Pop-Up Menus in Column C of the Transactions sheet.
    Editing a Pop-Up Menu in Numbers 3 is easy. Please call back if you need more help.
    Regards,
    Ian.

  • Using values of two different applications that are from the same class

    Hi,
    See the following little program
    What I can't figure out is
    i) How to change the values if I add a button
    ii) How to print just app.x1 etc. The way I have it now, it will just print x1, y1 etc, from both app and app1, but I want to be able to distinguish between the two of them so I can use the values.....ie for example add app.x1 and app1.x2 (only using that as an example of what I want to use them for)
    I'd really appreciate if anyone could help me out, it's probably simple, but just cant figure it.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class drawLine extends JFrame{
    int x1, y1, x2, y2;
    JPanel topPanel;
    JButton button;
    public length l, l3;
    public drawLine(){
    super("drawLine");
    public drawLine(length l){
    this.l = l;
    topPanel = new JPanel();
    button = new JButton("Change");
    topPanel.add(button);
    getContentPane().add(topPanel, BorderLayout.NORTH);
    x1 = 100;
    y1 = 100;
    x2 = l.x2;
    y2 = l.y2;
    System.out.println(x1 + " " + y1 + " " + x2 + " " + y2);
    /*button.addActionListener(
    new ActionListener(){
    public void actionPerformed(ActionEvent e){
    l.length();
    repaint();
    public void hello(){
    System.out.println(x1 + " " + y1 + " " + x2 + " " + y2);
    public void paint(Graphics g){
    draw(g);
    public void draw(Graphics g){
    g.drawLine(x1, y1, x2, y2);
    public static void main(String args[]){
    length l1 = new length();
    length l2 = (length)l1.clone();
    l1.length();
    l2.length();
    drawLine app = new drawLine(l1);
    app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    app.setSize( 300, 300 );
    app.move(0,0) ;
    app.setVisible( true );
    drawLine app1 = new drawLine(l2);
    app1.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    app1.setSize( 300, 300 );
    app1.move(300,0) ;
    app1.setVisible( true );
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class length implements Cloneable{
    String whatlength;
    int llength;
    int x1 = 100;
    int y1 = 100;
    public int x2, y2;
    public void length(){
    whatlength = JOptionPane.showInputDialog("What is the length of the line");
    llength = Integer.parseInt(whatlength);
    x2 = x1 + llength;
    y2 = y1;
    public Object clone() {
    Object object = null;
    try {
    object = super.clone();
    catch (CloneNotSupportedException exception) {
    System.err.println("AbstractSpoon is not Cloneable");
    return object;
    }

    I've tried it like this, ie by adding an int to drawLine and trying to keep an array of lengths, which sortof works, but see the code I have commented out in the button actionListener class. What I thought I'd ba able to do is access the arrays like that.....how come it gives me an exception?
    public class drawLine extends JFrame{
    int x1, y1, x2, y2;
    JPanel topPanel;
    JButton button;
    public length[] linelength = new length[2];
    public drawLine(final length l, final int k){
    super("drawLine");
    this.linelength[k] = l;
    topPanel = new JPanel();
    button = new JButton("Change");
    topPanel.add(button);
    getContentPane().add(topPanel, BorderLayout.NORTH);
    x1 = 100;
    y1 = 100;
    x2 = linelength[k].x2;
    y2 = linelength[k].y2;
    button.addActionListener(
    new ActionListener(){
    public void actionPerformed(ActionEvent e){
    //Update the length object int's
    linelength[k].getLineLength();
    // Copy these ints back to the drawline object
    x2 = linelength[k].x2;
    y2 = linelength[k].y2;
    System.out.println(k + " " + linelength[k].x1 + " " + linelength[k].y1 + " " + linelength[k].x2 + " " + linelength[k].y2);
    repaint();
    /*********This bit gives me a null pointer exception ********
    linelength[0].x1 = linelength[1].x1;
    linelength[0].x2 = linelength[1].x2;
    linelength[0].y1 = linelength[1].y1;
    linelength[0].y2 = linelength[1].y2;
    public void paint(Graphics g){
    g.clearRect( 0, 0, getWidth(), getHeight() );
    draw(g);
    public void draw(Graphics g){
    g.drawLine(x1, y1, x2, y2);
    public static void main(String args[]){
    length l1 = new length();
    length l2 = (length)l1.clone();
    l1.getLineLength();
    l2.getLineLength();
    drawLine app = new drawLine(l1, 0);
    app.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    app.setSize( 300, 300 );
    app.move(0,0) ;
    app.setVisible( true );
    drawLine app1 = new drawLine(l2, 1);
    app1.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    app1.setSize( 300, 300 );
    app1.move(300,0) ;
    app1.setVisible( true );
    }

  • Using main class's methods from a different class in the same file

    Hi guys. Migrating from C++, hit a few snags. Hope someone can furnish a quick word of advice here.
    1. The filename is test.java, so test is the main class. This code and the topic title speak for themselves:
    class SomeClass
         public void SomeMethod()
              System.out.println(test.SomeOperation());
    public class test
         public static void main(String args[])
              SomeClass someObject = new SomeClass();
              someObject.SomeMethod();
         public static String SomeOperation()
              return "SomeThing";
    }The code works fine. What I want to know is, is there some way to use test.SomeOperation() from SomeClass without the test.?
    2. No sense opening a second topic for this, so second question: Similarly, is there a good way to refer to System.out.println without the System.out.? Like the using keyword in C++.
    Thanks.

    pfiinit wrote:
    The code works fine. What I want to know is, is there some way to use test.SomeOperation() from SomeClass without the test.?Yes you can by using a static import, but I don't recommend it. SomeOperation is a static method of the test class, and it's best to call it that way so you know exactly what your code is doing here.
    2. No sense opening a second topic for this, so second question: Similarly, is there a good way to refer to System.out.println without the System.out.? Like the using keyword in C++.Again, you could use static imports, but again, I don't recommend it. Myself, I use Eclipse and set up its template so that when I type sop it automatically spits out System.out.println(). Most decent IDE's have this capability.
    Also, you may wish to look up Java naming conventions, since if you abide by them, it will make it easier for others to understand your code.
    Much luck and welcome to this forum!

  • Accessing XML data from a different class

    Hi all,
    I have an xml class that loads xml data, I need to access the data from another class. I have imported the xml classinto the new class and created a new instance of it. However when I try to access the xml data it is coming back as null. I understand this is almost certainly because when it is called the xml data hasn't completed it's load. How can I get round this?
    xml class:
    package {
        import flash.xml.*;
        import flash.events.*;
        import flash.net.*
        import flash.display.*
        public class xml extends MovieClip
            public var xmlRequest:URLRequest;
            public var xmlLoader:URLLoader;
            public var xmlImages:XML;
            public function xml()
                xmlRequest = new URLRequest("images.xml");
                xmlLoader = new URLLoader(xmlRequest)
                xmlLoader.addEventListener(Event.COMPLETE, xmlLoaded);
                xmlLoader.load(xmlRequest);
            private function xmlLoaded(event:Event):void
                trace(xmlLoader.data);
                xmlImages = new XML(xmlLoader.data);
    Thanks in advance

    One of the ways:
    package {
         import flash.xml.*;
        import flash.events.*;
        import flash.net.*
        import flash.display.*
        public class XMLLoader extends EventDispatcher
              public var xmlRequest:URLRequest;
              public var xmlLoader:URLLoader;
              public var xmlImages:XML;
              public function XMLLoader()
              public function loadXML(url:String):void {
                   xmlLoader = new URLLoader()
                   xmlLoader.addEventListener(Event.COMPLETE, xmlLoaded);
                   xmlLoader.load(new URLRequest(url));
              private function xmlLoaded(event:Event):void
                   trace(xmlLoader.data);
                   xmlImages = new XML(xmlLoader.data);
                   dispatchEvent(event);
    Usage:
    var xmlLoader:XMLLoader = new XMLLoader();
    xmlLoader.addEventListener(Event.COMPLETE, onXMLLoad);
    xmlLoader.loadXML("images.xml"):
    function onXMLLoad(e:Event):void{
         trace(xmlLoader.xmlImages);

  • Problem Using toString method from a different class

    Hi,
    I can not get the toString method to work from another class.
    // First Class Separate file MyClass1.java
    public class MyClass1 {
         private long num1;
         private double num2;
       public MyClass1 (long num1, double num2) throws OneException, AnotherException {
            // Some Code Here...
        // Override the toString() method
       public String toString() {
            return "Number 1: " + num1+ " Number 2:" + num2 + ".";
    // Second Class Separate file MyClass2.java
    public class MyClass2 {
        public static void main(String[] args) {
            try {
               MyClass1 myobject = new MyClass1(3456789, 150000);
               System.out.println(myobject);
             } catch (OneException e) {
                  System.out.println(e.getMessage());
             } catch (AnotherException e) {
                  System.out.println(e.getMessage());
    }My problem is with the System.out.println(myobject);
    If I leave it this way it displays. Number 1: 0 Number 2: 0
    If I change the toSting method to accept the parameters like so..
    public String toString(long num1, double num2) {
          return "Number 1: " + num1 + " Number 2:" + num2 + ".";
       }Then the program will print out the name of the class with some garbage after it MyClass1@fabe9. What am I doing wrong?
    The desired output is:
    "Number 1: 3456789 Number 2: 150000."
    Thanks a lot in advance for any advice.

    Well here is the entire code. All that MyClass1 did was check the numbers and then throw an error if one was too high or too low.
    // First Class Separate file MyClass1.java public class MyClass1 {
         private long num1;
         private double num2;
         public MyClass1 (long num1, double num2) throws OneException, AnotherException {              
         // Check num2 to see if it is greater than 200,000
         if (num2 < 10000) {
                throw new OneException("ERROR!:  " +num2 + " is too low!");
         // Check num2 to see if it is greater than 200,000
         if (num2 > 200000) {
                throw new AnotherException ("ERROR!:  " +num2 + " is too high!");
         // Override the toString() method
         public String toString() {
              return "Number 1: " + num1+ " Number 2:" + num2 + ".";    
    // Second Class Separate file MyClass2.java
    public class MyClass2 {
        // Main method where the program begins.
        public static void main(String[] args) {
            // Instantiate first MyClass object.
            try {
               MyClass1 myobject = new MyClass1 (3456789, 150000);
               // if successful use MyClass1 toString() method.
               System.out.println(myobject);
                         // Catch the exceptions within the main method and print appropriate
                         // error messages.
             } catch (OneException e) {
                  System.out.println(e.getMessage());
             } catch (AnotherException e) {
                  System.out.println(e.getMessage());
             }I am not sure what is buggy. Everything else is working fine.

Maybe you are looking for