Painting from outside main class

Im writing some generic code and im having trouble trying to get the called class to paint correctly. I have this code so far, and it works, but I dont like it. I pass in graphics as a parameter and it doesnt use the natural repaint method, so I was hoping someone could show me how to do this the "right way". I also want to avoid using threads, im pretty sure theyre not absolutely necessary.
Theres 2 classes, essentially its
class 1: paint a green splashscreen, user presses button> call class 2
class 2: paint a white screen and moving ball
(the while loop has been commented out so i can check the state of repaint. My normal programs automatically repaint if i minimise them, this one wont repaint properly).
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public class Multi extends Applet implements ActionListener{
Mgame game=new Mgame();
private Button host;
    public void init() {
    setLayout(null) ;
    setButtons();
    public void paint(Graphics g) {
    g.setColor(Color.green);   
    g.fillRect(0,0,700,500); 
     public void setButtons() {
    host= new Button ("Host Game");
    host.setBounds(470,395,100,30);
    add(host);
    host.addActionListener(this);
     public void actionPerformed(ActionEvent event)
              Graphics g = getGraphics();
              game.gamerun(g);
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
class Mgame{
int ballx = 0;
Graphics g;
public void xpaint(){
    g.setColor(Color.white);   
    g.fillRect(0,0,700,500);         
    g.setColor(Color.red);   
    g.fillOval(ballx, 40, 90, 90);
public void gamerun(Graphics graphics){
    g=graphics;
    //while(true){
    ballx=ballx+1;
    if (ballx==500) {ballx=10;}
    try { Thread.sleep(100); } catch (Exception e) {}
    xpaint();
}Thanks for any help.

How would I fix that then?
I tried using
class Mgame extends Multi{
<etc>
}Which means that the program now compiles, but now the program seems to skip the Mgame.gamerun repaint() line, so the program looks like its freezed up.
New code listing is:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
public class Multi extends Applet implements ActionListener{
Mgame game;
private Button host;
    public void init() {
    game=new Mgame();
    setLayout(null) ;
    setButtons();
    public void paint(Graphics g) {
    g.setColor(Color.green);   
    g.fillRect(0,0,700,500); 
     public void setButtons() {
    host= new Button ("Host Game");
    host.setBounds(470,395,100,30);
    add(host);
    host.addActionListener(this);
     public void actionPerformed(ActionEvent event)
              game.gamerun();
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
class Mgame extends Multi{
int ballx = 0;
public void paint(Graphics g){
    g.setColor(Color.white);   
    g.fillRect(0,0,700,500);         
    g.setColor(Color.red);   
    g.fillOval(ballx, 40, 90, 90);
public void gamerun(){
    while(true){
    ballx=ballx+1;
    if (ballx==500) {ballx=10;}
    try { Thread.sleep(100); } catch (Exception e) {}
    repaint();
}

Similar Messages

  • Accessing a thread from a main class, please help!

    Hi, I have a thread, T1, that I need to access from my main class. I cannot use runnable, it's got to be done with extands thread. I can start it alright, but I cannot stop it;
    MAIN CLASS
    public class Uppgift1 {
    public static void main(String args[]) throws InterruptedException {
    // Start Thread 1
         Thread trad1 = new T1( );
         trad1.start( );
         //Wait for 5 seconds
         Thread.sleep(5000);
         //Stop the Thread
         trad1.stopIt();
    public class T1 extends Thread {
         boolean go = true;
    public void run ( ) {
    while(go){
         System.out.println("T1: Trad 1");
    try{
    Thread.sleep(1000);
    } catch( InterruptedException e ) {
    public void stopIt(){
    go = false;
    Why can't I run stopIt from my main class?
    Please help me.

    manswide wrote:
    The reason I have to use Thread is that it's for a school thing; I guess I gotta learn to do it the bad way in order to learn why to love the good way later on.Good plan. Making mistakes is a fantastic learning tool
    How do I declare a reference to my own class?
    T1 t1 = new T1();

  • Gui doesn't show when the Thread is dispatched from the main class

    Hi all,
    I've tried to write a file unzipper class that shows a small frame with 2 progress bars.
    The unzipper extends Thread class in order to make it an independant service.
    However, when I debug it and use a main function that's written within the class, it works fine, and when I run it by calling it from another main, I only see a frame where the progress window should be, but no window.
    Does anyone know what I'm doing wrong? (About the GUI, I know my unzipper isn't the most efficient one:
    import javax.swing.*;
    import java.awt.*;
    import java.io.*;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;
    import java.util.zip.ZipInputStream;
    * User: Administrator
    * Date: 14/10/2005
    * Time: 18:26:47
    * This is a file Unzipper;
    * It takes a zipped archive, reads it, and decompresses the files within it
    * It is a stand alone thread since the user doesn't need to wait for it or whatever;
    * It also shows a nice progress bar gui for the user to know how the decompressing works
    public class FileUnZip extends Thread{
    private ZipEntry zipEntry;
    private ZipInputStream zipInStream;
    private FileInputStream fileInputStream;
    private int sChunk=8192;//8KB buffer size for optimized i/o performance
    private byte[] buff;
    private FileOutputStream entryOutputStream;
    private BufferedOutputStream bufferedOutputStream;
    private String sourceArchiveName;
    private String targetDirectoryName;
    private String targetFileName;// a string that stores the current zipped file in the archive
    private ZipFile zipFile;
    private int zipEntriesNum;
    private int readsNumber;//for knowing how many i/o approaches are required
    //for progress bar gui:
    private JProgressBar overAllProgBar;
    private JProgressBar currentFileProgBar;
    private JPanel progPanel;
    private JLabel overAllLabel;
    private JLabel currentFileLabel;
    private int currFileValue=0;
    private int currEntryValue=0;
    private JFrame progFrm;
    //constructor that produces the output in the same directory as source
    public FileUnZip(String sourceArchiveN) {
    sourceArchiveName = sourceArchiveN;
    targetDirectoryName=sourceArchiveName.substring(0,
    sourceArchiveName.length()-4);//trim ".zip"
    // for clean directory name
    File dir=new File (targetDirectoryName);
    dir.mkdir();
    this.start();
    //constructor that produces the output in the given targetDir... directory
    public FileUnZip(String sourceArchiveN, String targetFileN) {
    sourceArchiveName = sourceArchiveN;
    targetDirectoryName = targetFileN.substring(0,targetFileN.length()-4);
    // for clean directory name
    File dir=new File (targetDirectoryName);
    dir.mkdir();
    this.start();
    public void initGui(){
    JFrame.setDefaultLookAndFeelDecorated(true);
    progFrm = new JFrame("Extracting " + sourceArchiveName);
    progPanel = new JPanel(new GridLayout(2,2));
    overAllLabel = new JLabel("<html><body><font size=4 color=red>Over All"+
    "</color></size><font><body><html>");
    progPanel.add(overAllLabel);
    overAllProgBar = new JProgressBar(currEntryValue, zipEntriesNum);
    overAllProgBar.setStringPainted(true);
    progPanel.add(overAllProgBar);
    currentFileProgBar = new JProgressBar(currFileValue, sChunk);
    currentFileProgBar.setStringPainted(true);
    currentFileLabel = new JLabel("<html><body>" +
    "<font size=4 color=red>Current file"+
    "</color></size><font><body><html>") ;
    progPanel.add(currentFileLabel);
    progPanel.add(currentFileProgBar);
    progFrm.getContentPane().add(progPanel);
    progFrm.pack();
    progFrm.setResizable(false);
    progFrm.setVisible(true);
    public void initStreams(){
    try {
    zipFile = new ZipFile(sourceArchiveName);
    zipEntriesNum=zipFile.size();// get entries number from the archive,
    //used for displaying the overall progressbar
    } catch (IOException e) {
    System.out.println("can't initiate zip file");
    if (zipFile!=null) {
    try {
    zipFile.close();
    } catch (IOException e) {
    System.out.println("zip file never initiated");
    try {
    fileInputStream = new FileInputStream(sourceArchiveName);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    zipInStream = new ZipInputStream(new BufferedInputStream(
    fileInputStream));
    buff=new byte[sChunk];
    public void start(){
    initStreams();
    initGui();
    run();
    public void run(){
    File outputFile;
    int succeededReading=0;
    try {
    while((zipEntry = zipInStream.getNextEntry())!=null){
    overAllProgBar.setValue(++currEntryValue);
    readsNumber=(int)zipEntry.getSize()/sChunk;
    currentFileProgBar.setMaximum(readsNumber);
    targetFileName=targetDirectoryName +
    File.separator + zipEntry.getName();
    outputFile=new File(targetFileName);
    System.out.println("outputFile.getAbsolutePath() = "
    + outputFile.getAbsolutePath());
    if(!outputFile.exists()){
    outputFile.createNewFile();
    entryOutputStream=new FileOutputStream(outputFile);
    bufferedOutputStream = new BufferedOutputStream(
    entryOutputStream, sChunk);
    while((succeededReading=zipInStream.read(
    buff,0,sChunk))!=-1){ //extract single entry
    bufferedOutputStream.write(buff,0,succeededReading);
    currentFileProgBar.setValue(++currFileValue);
    bufferedOutputStream.flush();
    bufferedOutputStream.close();
    entryOutputStream.flush();
    currFileValue = 0;
    } catch (IOException e) {
    e.printStackTrace();
    finalize();
    public void closeStreams(){
    try {
    zipInStream.close();
    } catch (IOException e) {
    e.printStackTrace();
    try {
    fileInputStream.close();
    } catch (IOException e) {
    e.printStackTrace();
    if (entryOutputStream!=null) {
    try {
    entryOutputStream.flush();
    entryOutputStream.close();
    } catch (IOException e) {
    System.out.println("entry stream never opened");
    if(bufferedOutputStream!=null){
    try {
    bufferedOutputStream.flush();
    bufferedOutputStream.close();
    } catch (IOException e) {
    e.printStackTrace();
    public void finalize(){
    try {
    super.finalize();
    } catch (Throwable throwable) {
    throwable.printStackTrace();
    progFrm.dispose();
    closeStreams();
    endTask();
    private void endTask(){
    //play a sound when task is complete
    java.awt.Toolkit.getDefaultToolkit().beep();
    }

    import javax.swing.*;
    import java.awt.*;
    import java.io.*;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipFile;
    import java.util.zip.ZipInputStream;
    * User: Administrator
    * Date: 14/10/2005
    * Time: 18:26:47
    * This is a file Unzipper;
    * It takes a zipped archive, reads it, and decompresses the files within it
    * It is a stand alone thread since the user doesn't need to wait for it or whatever;
    * It also shows a nice progress bar gui for the user to know how the decompressing works
    public class FileUnZip extends Thread{
        private ZipEntry zipEntry;
        private ZipInputStream zipInStream;
        private FileInputStream fileInputStream;
        private int sChunk=8192;//8KB buffer size for optimized i/o performance
        private byte[] buff;
        private FileOutputStream entryOutputStream;
        private BufferedOutputStream bufferedOutputStream;
        private String sourceArchiveName;
        private String targetDirectoryName;
        private String targetFileName;// a string that stores the current zipped file in the archive
        private ZipFile zipFile;
        private int zipEntriesNum;
        private int readsNumber;//for knowing how many i/o approaches are required
    //for progress bar gui:
        private JProgressBar overAllProgBar;
        private JProgressBar currentFileProgBar;
        private JPanel progPanel;
        private JLabel overAllLabel;
        private JLabel currentFileLabel;
        private int currFileValue=0;
        private int currEntryValue=0;
        private JFrame progFrm;
    //constructor that produces the output in the same directory as source
        public FileUnZip(String sourceArchiveN) {
            sourceArchiveName = sourceArchiveN;
            targetDirectoryName=sourceArchiveName.substring(0,
                    sourceArchiveName.length()-4);//trim ".zip"
    // for clean directory name
            File dir=new File(targetDirectoryName);
            dir.mkdir();
            this.start();
    //constructor that produces the output in the given targetDir... directory
        public FileUnZip(String sourceArchiveN, String targetFileN) {
            sourceArchiveName = sourceArchiveN;
            targetDirectoryName = targetFileN.substring(0,targetFileN.length()-4);
    // for clean directory name
            File dir=new File(targetDirectoryName);
            dir.mkdir();
            this.start();
        public void initGui(){
            JFrame.setDefaultLookAndFeelDecorated(true);
            progFrm = new JFrame("Extracting " + sourceArchiveName);
            progPanel = new JPanel(new GridLayout(2,2));
            overAllLabel = new JLabel("<html><body><font size=4 color=red>Over All"+
                    "</color></size><font><body><html>");
            progPanel.add(overAllLabel);
            overAllProgBar = new JProgressBar(currEntryValue, zipEntriesNum);
            overAllProgBar.setStringPainted(true);
            progPanel.add(overAllProgBar);
            currentFileProgBar = new JProgressBar(currFileValue, sChunk);
            currentFileProgBar.setStringPainted(true);
            currentFileLabel = new JLabel("<html><body>" +
                    "<font size=4 color=red>Current file"+
                    "</color></size><font><body><html>") ;
            progPanel.add(currentFileLabel);
            progPanel.add(currentFileProgBar);
            progFrm.getContentPane().add(progPanel);
            progFrm.pack();
            progFrm.setResizable(false);
            progFrm.setVisible(true);
        public void initStreams(){
            try {
                zipFile = new ZipFile(sourceArchiveName);
                zipEntriesNum=zipFile.size();// get entries number from the archive,
    //used for displaying the overall progressbar
            } catch (IOException e) {
                System.out.println("can't initiate zip file");
            if (zipFile!=null) {
                try {
                    zipFile.close();
                } catch (IOException e) {
                    System.out.println("zip file never initiated");
            try {
                fileInputStream = new FileInputStream(sourceArchiveName);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            zipInStream = new ZipInputStream(new BufferedInputStream(
                    fileInputStream));
            buff=new byte[sChunk];
        public void start(){
            initStreams();
            initGui();
            run();
        public void run(){
            File outputFile;
            int succeededReading=0;
            try {
                while((zipEntry = zipInStream.getNextEntry())!=null){
                    overAllProgBar.setValue(++currEntryValue);
                    readsNumber=(int)zipEntry.getSize()/sChunk;
                    currentFileProgBar.setMaximum(readsNumber);
                    targetFileName=targetDirectoryName +
                            File.separator + zipEntry.getName();
                    outputFile=new File(targetFileName);
                    System.out.println("outputFile.getAbsolutePath() = "
                            + outputFile.getAbsolutePath());
                    if(!outputFile.exists()){
                        outputFile.createNewFile();
                    entryOutputStream=new FileOutputStream(outputFile);
                    bufferedOutputStream = new BufferedOutputStream(
                            entryOutputStream, sChunk);
                    while((succeededReading=zipInStream.read(
                            buff,0,sChunk))!=-1){ //extract single entry
                        bufferedOutputStream.write(buff,0,succeededReading);
                        currentFileProgBar.setValue(++currFileValue);
                    bufferedOutputStream.flush();
                    bufferedOutputStream.close();
                    entryOutputStream.flush();
                    currFileValue = 0;
            } catch (IOException e) {
                e.printStackTrace();
            finalize();
        public void closeStreams(){
            try {
                zipInStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            if (entryOutputStream!=null) {
                try {
                    entryOutputStream.flush();
                    entryOutputStream.close();
                } catch (IOException e) {
                    System.out.println("entry stream never opened");
            if(bufferedOutputStream!=null){
                try {
                    bufferedOutputStream.flush();
                    bufferedOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
        public void finalize(){
            try {
                super.finalize();
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            progFrm.dispose();
            closeStreams();
            endTask();
        private void endTask(){
    //play a sound when task is complete
            java.awt.Toolkit.getDefaultToolkit().beep();
    }

  • Receive notification of UIView changes from outside that class

    Say, I want to know when a specific UIView object receives a notification (for instance, viewDidDisappear:) but I need to know it from outside of that class, or in another class derived from NSObject. Is it possible to do at all?

    you can't access anything related to a particular class unless you have access to that class.  you don't necessarily have to open the class file and inspect/edit it.  but you do need to have a reference to a class instance.
    so, if you have a class where you create a class instance, you can use that to "try" and remove that listener (assuming its an instance method).  if the listener is a static method, it's even easier.

  • Having a problem calling and displaying a page,from outside the class?? :-(

    Hi,
    I seem to be having a problem displaying a class from a different page, it is called but all i get is a blank page, even though when i compile and run it by itself it works fine?? I call it like:
    if(source == animateVMS)
                   {ImageSequence i = new ImageSequence();
                    i.setSize(Toolkit.getDefaultToolkit().getScreenSize());
                    i.show();
                    this.dispose();
                   }but it only displays a blank screen?? I think it is sumthing to do with the contructor of the following class?
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class ImageSequence extends JFrame implements ActionListener
       {    static ImageSequence controller = new ImageSequence();
                 ImageSQPanel imageSQPanel;   
            static int frameNumber = -1;   
            int delay;   
            Thread animatorThread;   
            static boolean frozen = false;   
            Timer timer;    
            //Invoked only when this is run as an application.   
        public static void main(String[] args) {
              Image[] waving = new Image[10];        
              for (int i = 1; i <= 10; i++) {
                    waving[i-1] = Toolkit.getDefaultToolkit().getImage("images/T" + i + ".gif");
              JFrame f = new JFrame("ImageSequenceTimer");
              f.addWindowListener(new WindowAdapter() {
                 public void windowClosing(WindowEvent e) {               
                                System.exit(0);           
             //ImageSequence controller = new ImageSequence();
             controller.buildUI(f.getContentPane(), waving);
             controller.startAnimation();
             f.setSize(Toolkit.getDefaultToolkit().getScreenSize());       
             f.setVisible(true);    }    
             //Note: Container must use BorderLayout, which is the    
             //default layout manager for content panes.   
             void buildUI(Container container, Image[] dukes) {
                          int fps = 10;        
             //How many milliseconds between frames?       
             delay = (fps > 0) ? (1000 / fps) : 100;        
             //Set up a timer that calls this object's action handler       
             timer = new Timer(delay, new TimerListener());       
             timer.setInitialDelay(0);       
             timer.setCoalesce(true);        
             JPanel buttonPanel = new JPanel();        
             JButton play = new JButton("PLAY");       
             play.addActionListener(this);
             JButton stop = new JButton("STOP");       
             stop.addActionListener(this);
             JButton back = new JButton("Back");        
             back.addActionListener(this);
             imageSQPanel = new ImageSQPanel(dukes);       
             container.add(imageSQPanel, BorderLayout.CENTER);        
             container.add(buttonPanel, BorderLayout.SOUTH);       
             buttonPanel.add(play);       
             buttonPanel.add(stop);               
             buttonPanel.add(back);   
          public void start() {       
             startAnimation();   
          public void stop() {       
             stopAnimation();   
          public synchronized void startAnimation() {
                       if (frozen) {            
          //Do nothing. The user has requested that we            
          //stop changing the image.       
                         else {           
          //Start animating!           
          if (!timer.isRunning()) {               
          timer.start();           
          public synchronized void stopAnimation() {       
          //Stop the animating thread.       
          if (timer.isRunning()) {           
          timer.stop();       
       /**     * Listener for the play, stop, restart, and back buttons.     */   
       public void actionPerformed(ActionEvent e) {       
       JButton button = (JButton)e.getSource();       
       String label = button.getActionCommand();       
       if("PLAY".equals(label))           
       start();       
       if("STOP".equals(label))           
       stop();
       if("BACK".equals(label))
       {varsity v = new varsity();
        v.setSize(Toolkit.getDefaultToolkit().getScreenSize());
        v.show();
        this.dispose();
       /**     *  Listener for the animation timer.     */   
       private class TimerListener implements ActionListener {       
         public void actionPerformed(ActionEvent e)        {            
       //Advance the animation frame.           
       frameNumber++;             
       //Display it.           
       imageSQPanel.repaint();       
        class ImageSQPanel extends JPanel {       
        Image dukesWave[];        
        public ImageSQPanel(Image[] dukesWave) {           
        this.dukesWave = dukesWave;         }        
        //Draw the current frame of animation.       
        public void paintComponent(Graphics g) {           
        super.paintComponent(g);
        //paint background            
        //Paint the frame into the image.           
        try {               
        g.drawImage(dukesWave[ImageSequenceTimer.frameNumber%10],0, 0, this);            
        catch (ArrayIndexOutOfBoundsException e) {               
        //On rare occasions, this method can be called                
        //when frameNumber is still -1. Do nothing.               
        return;           
    }Could someone please try to help me fix my problem!
    Kind Regards
    RSH

    cheers that did the trick!! : - )
    I was wondeing if you could help me with one more thing, its about getting rid of an old page after you press a button to go to a new page! this.dispose doesnt wrk below:
            JButton back = new JButton("BACK");
            back.addActionListener(new ActionListener()       
                  public void actionPerformed(ActionEvent e)           
                       VowelmSound s = new VowelmSound();
                        s.setSize(Toolkit.getDefaultToolkit().getScreenSize());
                        s.show();
                        //this.dispose();           
             });        and this is main
    public static void main(String[] args)
    JFrame draw = new punjabidraw();   
    draw.setVisible(true);   
    }I was wondering what I could use to get rid of the old page??
    Kind Regards
    Raj

  • Forwarding events from my menubar class to main class

    I'm brand new to swing. I'm trying write an app, and wanted to encapsulate my JToolBar and JMenuBar items, so I made classes to handle each of them. Then from my "main" class I could just call a function and voila.
    However the one obvious problem is that my "main" class doesn't know when JToolBar or JMenuBar items have actions. Those classes each handle their own event listening. I was hoping (probably through magic) that I could then forward that action to the main class somehow.
    The obvious solution would be to expose the individual toolbar JButtons and JMenuItems and call addActionListener(this) on those items from the "main" class. However I'm hoping to avoid having to expose those items, probably just because I'm anal.
    One idea that I've seen but seems kind of not-very-elegant was to create an item to track the state of all things, and pass that item around. Then in my individual actionPerformed() functions I could manipulate that item so that the main class could see those changes.
    I imagine I'll have this same issue when I get into more complicated parts of my would-be application than just the menubar. Any help would be appreciated.

    OK so I can define the new actions in my main class and then in my toolbar/menubar items I just tell them to use those main class Actions? Hopefully I have as somewhat firm a grasp on this as I think I have. I'll try that out now.

  • Referencing main class from created instances

    The quick setup:
    My Main class creates a JFrame and adds a few custom JPanels. One of the JPanels has a mouse listener and responses to the mouse clicks, and it works great.
    I'd like to know if there's a way to have that JPanel invoke public, non-static methods from the Main class (the class which created it) without passing a reference for the instance of the Main class to the JPanel when it's (the JPanel) is created. Or is that the way you're supposed to do it?
    A (sort of) similar question: can a component invoke methods of it's parent container? If so, how?
    Thanks so much,
    Matt

    Hi Rhesus21,
    A (sort of) similar question: can a component invoke methods of it's parent container? If so, how?Yes, simply this way :
    public class MainFrame extends JFrame {
        private MyPanel panel;
        panel = new MyPanel(this);
    public class MyPanel extends JPanel {
        private MainFrame frame;
        public MyPanel(MainFrame frame) {
            this.frame = frame;
    }

  • How can i execute Spaces API in java main class?

    Hi
    I am able to execute Spaces API through portal application. However if i try to execute it in java main class, its throwing an exception
    "SEVERE: java.io.FileNotFoundException: .\config\jps-config.xml (The system cannot find the path specified)"
    oracle.wsm.common.sdk.WSMException: WSM-00145 : Keystore location or path can not be null or empty; it must be configured through JPS configuration or policy configuration override.
    How can i set this path, so that i can execute Spaces API from java main class.
    Need this main class to configure in cron job, to schedule a task.
    Regards
    Raj

    Hi Daniel
    Currently i have implemented create functionality in my portal application using Spaces API, which is working fine. Now the requirement is, i need to implement a "Cron Job" to schedule a task, which will execute to create space(for example once in a week). Cron job will execute only the main method. So I have created java main class, in which I have used Spaces API to perform create space operation. Then it was giving exception.
    Later I understood the reason, as I am executing the Space API with a simple JSE client, its failing since a simple java program has no idea of default-keystore.jks, jps-config.xml, Security Policy. Hence i have included those details in main class. Now I am getting new error,
    SEVERE: WSM-06303 The method "registerListener" was not called with required permission "oracle.wsm.policyaccess"
    For your reference i have attached the code below, please help. How can i use Spaces API in java main method(i mean public static void main(String[] args) by giving all required information.
        public static void main(String[] args) throws InstantiationException,
                                                      GroupSpaceWSException,
                                                      SpacesException {
            Class2 class2 = new Class2();
            GroupSpaceWSContext context = new GroupSpaceWSContext();
            FactoryFinder.init(null);
            context.setEndPoint("http://10.161.226.30/webcenter/SpacesWebService");
            context.setSamlIssuerName("www.oracle.com");
            context.setRecipientKeyAlias("orakey");
            Properties systemProps = System.getProperties();
            systemProps.put("java.security.policy","oracle/wss11_saml_or_username_token_with_message_protection_client_policy");
            systemProps.put("javax.net.ssl.trustStore","C:\\Oracle\\Middleware11.1.7\\wlserver_10.3\\server\\lib\\cacerts.jks");
    systemProps.put("oracle.security.jps.config","C:\\Oracle\\Middleware11.1.7\\user_projects\\domains\\workspace\\system11.1.1.7.40.64.93\\DefaultDomain\\config\\fmwconfig\\jps-config.xml");
            systemProps.put("javax.net.ssl.keyStore",C:\\Oracle\\Middleware11.1.7\\user_projects\\domains\\workspace\\system11.1.1.7.40.64.93\\DefaultDomain\\config\\fmwconfig\\consumer.jks");
            systemProps.put("javax.net.ssl.keyStorePassword", "Test12");
            System.setProperties(systemProps);
            GroupSpaceWSClient groupSpaceWSClient;
            try {
                groupSpaceWSClient = new GroupSpaceWSClient(context);
                System.out.println("URL: " +
                                   groupSpaceWSClient.getWebCenterSpacesURL());
                //delete the Space
                List<String> groupSpaces = groupSpaceWSClient.getGroupSpaces(null);
                System.out.println("GroupSpaces:: " + groupSpaces.size());
            } catch (Exception e) {
    Regards
    Raj

  • 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??

  • Determine a string from main class in an outside class

    Hello there,
    This might be stupid question but I cant think, I am so very tired. Okay here is the question, is there any way we could see or the get the value of a string(just a string which is set in main class'A', its already set, we cannot make it static r anything like that)in a method outside that main class, probably in a method 'x' in class'C'.
    Thanks
    potti

    Yes, you can, in many ways, or else Java would be moot. Excluding the static way of doing it, which by the way is evil, your class C can make an instance of class A and then access it either as a public field or as the value returned by a public method. You can also use inheritance, but it's pointless in this case, inheritance is meant to abstract, extend functionality, and prevent having to rewrite code. It's not meant for accessing fields. And by the way, inheritance, too, is evil.
    This is one way to do it.
    class A {
         public String s = "great balls of fire";
    public class C {
         public static void main(String[] args) {
              A myInstance = new A();
              String s = myInstance.s;
              System.out.println(s);
    }This is the preferred way to do it, as it encapsulates the String. The idea of encapsulation is to access fields by a method instead of directly since interfaces are less likely to change than an object's data and in the case that the object's data does change and the interface does not, the changes will remain local.
    class A {
         private String s = "great balls of fire";
         public String getS() { return s; }
    public class C {
         public static void main(String[] args) {
              A a = new A();
              String s = a.getS();
              System.out.println(s);
    }

  • How do I declare a native method outside of the main class?

    Hi
    This is a JNI particular question.
    I am having a problem with generating the header .h file after executing javah. The file is generated correctly but is empty under certain circumstances.
    This is the 'empty file:
    =================
    /* DO NOT EDIT THIS FILE - it is machine generated */
    #include <jni.h>
    /* Header for class gui_GuiMain */
    #ifndef Includedgui_GuiMain
    #define Includedgui_GuiMain
    #ifdef __cplusplus
    extern "C" {
    #endif
    #ifdef __cplusplus
    #endif
    #endif
    This is what it should look like:
    =========================
    /* DO NOT EDIT THIS FILE - it is machine generated */
    #include <jni.h>
    /* Header for class gui_GuiMain */
    #ifndef Includedgui_GuiMain
    #define Includedgui_GuiMain
    #ifdef __cplusplus
    extern "C" {
    #endif
    * Class: gui_GuiMain
    * Method: getValueOIDTestMIB
    * Signature: ()V
    JNIEXPORT void JNICALL Java_gui_GuiMain_getValueOIDTestMIB
    (JNIEnv *, jobject);
    #ifdef __cplusplus
    #endif
    #endif
    The header file becomes "empty" when the native function getValueOIDTestMIB is declared in a different class than what my main() function is declared in.
    For example something like this will work:
    class Main
    public native void getValueOIDTestMIB
    static {
    System.loadLibrary("libsnmp++");
    //............some more functions etc.............
    public static void main(String[] args)
    //............some more stuff...........................
    But when I declare this:
    public native void getValueOIDTestMIB
    static {
    System.loadLibrary("libsnmp++");
    outside the class, in another class within the same package, nothing happens.
    I am probabily doing something stupid. Can somebody help or give me some guidance to where I should look. I come from a C++ background, not a guru in Java.
    Thanks

    You need to run javah and give it as a parameter the full class name of the class which contains the native methods.
    For example (if your class is called A and its package is a.b.c)
    javah -jni a.b.c.A

  • How can I assign image file name from Main() class

    I am trying to create library class which will be accessed and used by different applications (with different image files to be assigned). So, what image file to call should be determined by and in the Main class.
    Here is the Main class
    import org.me.lib.MyJNIWindowClass;
    public class Main {
    public Main() {
    public static void main(String[] args) {
    MyJNIWindowClass mw = new MyJNIWindowClass();
    mw.s = "clock.gif";
    And here is the library class
    package org.me.lib;
    public class MyJNIWindowClass {
    public String s;
    ImageIcon image = new ImageIcon("C:/Documents and Settings/Administrator/Desktop/" + s);
    public MyJNIWindowClass() {
    JLabel jl = new JLabel(image);
    JFrame jf = new JFrame();
    jf.add(jl);
    jf.setVisible(true);
    jf.pack();
    I do understand that when I am making reference from main() method to MyJNIWindowClass() s first initialized to null and that is why clock could not be seen but how can I assign image file name from Main() class for library class without creating reference to Main() from MyJNIWindowClass()? As I said, I want this library class being accessed from different applications (means different Main() classes).
    Thank you.

    Your problem is one of timing. Consider this simple example.
    public class Example {
        public String s;
        private String message = "Hello, " + s;
        public String toString() {
            return message;
        public static void main(String[] args) {
            Example ex = new Example();
            ex.s = "world";
            System.out.println(ex.toString());
    }When this code is executed, the following happens in order:
    1. new Example() is executed, causing an object to constructed. In particular:
    2. field s is given value null (since no value is explicitly assigned.
    3. field message is given value "Hello, null"
    4. Back in method main, field s is now given value "world", but that
    doesn't change message.
    5. Finally, "Hello, null" is output.
    The following fixes the above example:
    public class Example {
        private String message;
        public Example(String name) {
            message = "Hello, " + name;
        public String toString() {
            return message;
        public static void main(String[] args) {
            Example ex = new Example("world");
            System.out.println(ex.toString());
    }

  • 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!

  • How to call a function in a class from the main timeline?

    Hey Guys
    I have a project in Flash with four external AS files, which are linked to items in the library using AS linkage.
    What I want to do is call a function in one of these files from the main timeline, how would I go about doing this? I'm not currently using a document class, most of the code is in Frame 1 of the main timeline.
    Thanks

    // change type to the class name from the instance
    ClassNameHere(this.getChildByName('instance_name')).SomeFunction();

  • Noobie question: How do I add something to the display list from a non-main class?

    I know how to use addChild() within the main class to add
    something to the stage display list and have it appear on the
    screen, but how do I add something to the stage display list from
    code within another class?
    So for example say I want to add some text (myTextField) to
    the stage's display list from within NotTheMainClass' code, could
    you give an example of the necessary code?

    you must pass a reference to a display list object or create
    one that's available to your class.
    there are so many ways to do this i'm not sure how you want
    to proceed. but you can create a globally available reference to
    the stage and root timeline:

Maybe you are looking for

  • Is this the flashback malware?

    Please look at these logs and tell me if these names and addresses look legit.  Ever since january 12th I have had lots of problems with my computer. running slow, freezing up, my user permmisions changed, and sleep schedule changed, things like that

  • Issue in xml to tab seperated content conversion

    Hi, I am having proxy to file scenario, in few columns data is coming like "AAA""B, in moni, xml data seems to be fine, but when the Excel file is genertaed at the FTP, the leading cell values are getting appended to this value. e.g. A     B     "ABC

  • Cisco Prime Infrastructure 1.3 stops working

    Hi, I have strange behavior with our CPI at the customer site. With no apparent reason we have noticed that the web interface was not accessible. After the restart all proceses were in up and running state and we were able to log in again. This is th

  • Update geometry of a cylinder

    Hi, There is a way to update the geometry of a cylinder (radius, length) ? There is nothing about on javadoc. It's only possible to get the shape... Thanks. Edit : i will looking on http://aviatrix3d.j3d.org/javadoc/org/j3d/renderer/aviatrix3d/geom/C

  • Define Pricing Procedure for a Customized PO

    Hi I want to have a customized pricing procedure with PB00 is manually changeable even though it takes the price from info record and assign this Pricing procedure to a customized PO type. What are the steps involved, appreciated if in detailed manne