BorderLayout & createImage

Hi all,
I'm studying Java and trying to add multiple panels layout with BorderLayout on an existing working applet.
I'm trying NOT to use Swing because I would like this applet to be able to run on Java 1.1.8 on my PDA (Psion 5MX).
Your Help welcome.

* MonPuzzleChinois - le Jeux de Puzzle Chinois.
* Il consiste en un ensemble de 7 formes g�om�triques impos�es :
* Ces formes peuvent �tre associ�s pour cr�er des figures.
* Ce programme propose notamment le carr� (figure de rangement).
* mais aussi le E, le V, le Cygne, la Fleche, le Bol, le Diamant et l'homme.
* Le Jeu consiste � juxtaposer les 7 formes sans jamais les superposer pour
* former la figure souhait�e.
* Plusieurs centaines de figures diff�rentes ont �t� recens�s dans
* des ouvrages sur le sujet.
// import des librairies applet, �v�nement, awt et math�matiques
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.lang.Math;
import java.net.URL;
// Classe principale de l'applet : MonPuzzleChinois
// Cette classe va �tre �x�cut�e dans un Thread (option runnable)
// Voir Ex�cution du Thread avec les fonctions start(), run(), destroy() et stop().
public class MonPuzzleChinois extends Applet implements Runnable{
// Cr�ation et initialisation des variables
StringBuffer MonStringBuffer;
Thread MonThread = null;
Image MonImage;
Graphics MonGraphique;
// D�finition des Formes avec des polygones en 5 points et 4 sommets maximum.
// 1er point = dernier point pour fermer la Forme.
// certains points successifs sont identiques pour les formes les plus simples.
int FormeX[][] = {{20,136,20,20,20},
{360,360,244,360,360},
{278,360,360,278,278},
{319,360,360,319,319},
{61,20,20,61,61},
{171,253,212,130,171},
{20,78,78,20,20}};
int FormeY[][] = {{264,380,380,264,264},
{264,380,380,264,264},
{40,40,122,40,40},
{191,150,232,191,191},
{191,150,232,191,191},
{40,40,81,81,40},
{40,40,98,98,40}};
// Position initiale des Formes X et Y.
int PositionX[] = {49,331,340,340,40,191,49};
int PositionY[] = {351,351,60,191,191,60,69};
// D�finition des Figures avec des polygones en 14 points maximum X et Y.
int FigureX[][] = {{108,272,272,108,108,108,108,108,108,108,108,108,108,108},
{ 74,190,306,306,190, 74, 74, 74, 74, 74, 74, 74, 74, 74},
{132,248,248,190,190,248,248,190,190,248,248,132,132,132},
{ 70,128,169,169,145,309,227,261,145, 87, 87,128,128, 70},
{103,277,277,195,219,161,161,185,267,103,103,103,103,103},
{ 74,306,306,248,272,108,132, 74, 74, 74, 74, 74, 74, 74},
{190,248,272,313,190, 67,108,132,190,190,190,190,190,190},
{103,190,149,190,231,190,277,277,248,190,132,103,103,103}};
int FigureY[][] = {{122,122,286,286,122,122,122,122,122,122,122,122,122,122},
{ 94,210, 94,210,326,210, 74, 74, 74, 74, 74, 74, 74, 74},
{ 65, 65,123,123,181,181,239,239,297,297,355,355, 65, 65},
{137, 79,120,202,226,226,308,342,342,284,202,161,137,137},
{123,123,287,205,181,181,235,211,293,293,123,123,123,123},
{140,140,198,256,280,280,256,198,140,140,140,140,140,140},
{102,160,160,201,324,201,160,160,102,102,102,102,102,102},
{164,164,123, 82,123,164,164,280,280,338,280,280,164,164}};
// Variables de travail
int FormeXbis[] = new int[5] , FormeYbis[] = new int[5];
int PositionXbis, PositionYbis, RotationX, RotationY;
int FormeSelection = 7,FormeDeplace = 0;
int SourisX, SourisY, SourisDeplaceX, SourisDeplaceY;
// un peu de trigonom�trie pour la gestion des rotations !
// constante sin(45) = 0.707107
double Sinus45x2 = 0.707107;
// Variables GUI
TextField MonFieldTextMessages ;
// Cr�ation d'une instance de classe AWT.Choice
// permet la cr�ation d'une liste d�roulante
Choice choixfigure = new Choice();
// Initialisation du Jeu
public void init(){ 
// Couleur de Fond
setBackground(new Color(255,0,0));
// On choisit le Gestionnaire d'Affichage BorderLayout
// Il d�coupe l'affichage en 5 Zones Nord, Est, Ouest, Sud et Centre
setLayout(new BorderLayout());
// Cr�ation des 5 Panels
Panel PanelNorth = new Panel();
Panel PanelCenter = new Panel();
Panel PanelSouth = new Panel();
Panel PanelEast = new Panel();
Panel PanelWest = new Panel();
// Affichage des Panels dans leur zone �cran
add("North", PanelNorth);
add("South", PanelSouth);
add("East", PanelEast);
add("West", PanelWest);
add("Center", PanelCenter);
// Gestion du PanelNorth
// Ajout des �l�ments graphiques
TextField MonTexteNord ;
MonTexteNord = new TextField();
MonTexteNord.setEditable(false);
PanelNorth.add(MonTexteNord);
MonTexteNord.setText("MonPuzzleChinois By JP Conan - Dess Simad - T3 - Java");
// Gestion du PanelWest
// Initialisation des valeurs de la Liste de s�lection des figures
choixfigure.addItem(" carre ");
choixfigure.addItem(" V ");
choixfigure.addItem(" E ");
choixfigure.addItem(" cygne ");
choixfigure.addItem(" fleche ");
choixfigure.addItem(" bol ");
choixfigure.addItem(" diamant ");
choixfigure.addItem(" homme ");
// Cr�ation d'un "listener" de s�lection d'une Figure dans la liste
choixfigure.addItemListener(new SelectionFigure());
// Affichage de la Liste d�roulante de s�lection des Figures
PanelWest.add(choixfigure);
// Cr�ation d'un Champs Texte
MonFieldTextMessages = new TextField();
MonFieldTextMessages.setEditable(false);
// Ajout du champs Texte sur
PanelSouth.add(MonFieldTextMessages);
// Ajout de 3 Boutons
PanelSouth.add(new Button("Recommencer"));
PanelSouth.add(new Button("Solution"));
PanelSouth.add(new Button("Quitter"));
// Gestion du PanelCenter
// PanelCenter.setLayout(new FlowLayout());
PanelCenter.setLayout(null);
PanelCenter.setBackground(new Color(0,255,0));
// ==============================================
// Couleur de Fond sRVB de l'Applet : Rouge
setBackground(new Color(255,0,0));
// Initialisation de l'Affichage
MonImage = PanelCenter.createImage(380,400);
MonGraphique = MonImage.getGraphics();
// MonPuzzleChinois en cours d'initialisation...
MonStringBuffer = new StringBuffer();
addItem("MonPuzzleChinois en cours d'initialisation... ");
// Instruction Voodoo pour Valider l'affichage des composants
validate();
// ==============================================
// Cr�ation d'un "listener" des �v�nements de la souris
addMouseListener(
new MouseAdapter(){
// D�tection de l'�v�nement "clic" (gauche)
public void mousePressed(MouseEvent MaSouris){
// localisation de la position initiale de la souris X et Y.
SourisX = MaSouris.getX();
SourisY = MaSouris.getY();
// Identification de la Forme s�lectionn�e (de 0 � 6)
if((PositionX[0]-SourisX)*(PositionX[0]-SourisX)+(PositionY[0]-SourisY)*(PositionY[0]-SourisY)<41*41){
FormeSelection = 0;
}else if((PositionX[1]-SourisX)*(PositionX[1]-SourisX)+(PositionY[1]-SourisY)*(PositionY[1]-SourisY)<41*41){
FormeSelection = 1;
}else if((PositionX[2]-SourisX)*(PositionX[2]-SourisX)+(PositionY[2]-SourisY)*(PositionY[2]-SourisY)<28*28){
FormeSelection = 2;
}else if((PositionX[3]-SourisX)*(PositionX[3]-SourisX)+(PositionY[3]-SourisY)*(PositionY[3]-SourisY)<20*20){
FormeSelection = 3;
}else if((PositionX[4]-SourisX)*(PositionX[4]-SourisX)+(PositionY[4]-SourisY)*(PositionY[4]-SourisY)<20*20){
FormeSelection = 4;
}else if((PositionX[5]-SourisX)*(PositionX[5]-SourisX)+(PositionY[5]-SourisY)*(PositionY[5]-SourisY)<28*28){
FormeSelection = 5;
}else if((PositionX[6]-SourisX)*(PositionX[6]-SourisX)+(PositionY[6]-SourisY)*(PositionY[6]-SourisY)<28*28){
FormeSelection = 6;
// 7 = pas de forme s�lectionn�e
}else{
FormeSelection = 7;
// Si UN seul clic (gauche) sur la souris
if(MaSouris.getClickCount() == 1){
if(FormeSelection != 7){
for(int nbSommet = 0;nbSommet < 5;nbSommet ++){
FormeXbis[nbSommet] = FormeX[FormeSelection][nbSommet] ; FormeYbis[nbSommet] = FormeY[FormeSelection][nbSommet] ;
PositionXbis = PositionX[FormeSelection] ; PositionYbis = PositionY[FormeSelection] ;
// Sinon rotation de la Forme :
// utilisation de la Fonction arrondie de la librairie Math�matique.
// utilisation de la constante Sinus45x2=sin(45) pour une rotation � 45�.
// Recalcul des valeurs des sommets de la Forme et r�affichage.
}else{
for(int nbSommet = 0;nbSommet < 5;nbSommet ++){
RotationX = FormeX[FormeSelection][nbSommet] ; RotationY = FormeY[FormeSelection][nbSommet] ;
FormeX[FormeSelection][nbSommet] = (int)(Math.round(Sinus45x2 * (RotationX - PositionX[FormeSelection] - RotationY + PositionY[FormeSelection]))) + PositionX[FormeSelection];
FormeY[FormeSelection][nbSommet] = (int)(Math.round(Sinus45x2 * (RotationX - PositionX[FormeSelection] + RotationY - PositionY[FormeSelection]))) + PositionY[FormeSelection];
// R�affichage
repaint();
// ==============================================
// Cr�ation d'un "listener"
// de D�tection des mouvements de la souris
// et du d�placement de la Forme s�lectionn�e
addMouseMotionListener(
new MouseMotionAdapter(){
public void mouseDragged(MouseEvent MaSouris){
// Localisation de la souris apr�s d�placement
SourisDeplaceX = MaSouris.getX();
SourisDeplaceY = MaSouris.getY();
// Recalcul des positions des 5 sommets de la Formes
for(int nbSommet = 0;nbSommet < 5;nbSommet ++){
FormeX[FormeSelection][nbSommet] = FormeXbis[nbSommet] + SourisDeplaceX - SourisX;
FormeY[FormeSelection][nbSommet] = FormeYbis[nbSommet] + SourisDeplaceY - SourisY;
PositionX[FormeSelection] = PositionXbis + SourisDeplaceX - SourisX ; PositionY[FormeSelection] = PositionYbis + SourisDeplaceY - SourisY ;
// R�affichage
repaint();
// Affichage des Messages divers
void addItem(String newWord) {
System.out.println(newWord);
MonStringBuffer.append(newWord);
MonFieldTextMessages.setText(newWord);
repaint();
// Classe de "listener" de s�lection de Figure
class SelectionFigure implements ItemListener{
public void itemStateChanged(ItemEvent MonEvenement){
Choice choixfigure = (Choice)MonEvenement.getSource();
switch(choixfigure.getSelectedIndex()){
case 0 :
FormeDeplace = 0 ;
break;
case 1 :
FormeDeplace = 1 ;
break;
case 2 :
FormeDeplace = 2 ;
break;
case 3 :
FormeDeplace = 3 ;
break;
case 4 :
FormeDeplace = 4 ;
break;
case 5 :
FormeDeplace = 5 ;
break;
case 6 :
FormeDeplace = 6 ;
break;
case 7 :
FormeDeplace = 7 ;
break;
// Affichage de la Figure s�lectionn�e
repaint();
// Affichage (et R�affichage) des 7 Formes et de la Figure en cours
public void paint(Graphics MonAppletGraphique){
// S�lection d'une couleur sRVB = Rouge
MonGraphique.setColor(new Color(255,0,0));
// Remplit le rectangle 400*300 avec la couleur s�lectionn�e (Rouge)
// Il s'agit du fonds de l'applet
MonGraphique.fillRect(0,0,400,300);
// Cr�e une zone plus petite 360*360 dans le Rectancgle cr�� ci-dessus
// C'est la zone de jeu
MonGraphique.clipRect(10,30,360,360);
// Remplissage du Rectangle 360*360 avec du Blanc
MonGraphique.setColor(Color.white);
MonGraphique.fillRect(10,30,360,360);
// S�lection de la couleur noire
MonGraphique.setColor(Color.black);
// Affichage du Polygone de 14 sommets de la Figure en Noir
MonGraphique.fillPolygon(FigureX[FormeDeplace],FigureY[FormeDeplace],14);
// Affichage des 7 Formes en Bleu
for(int di = 0;di <7;di ++){
// Formes en Bleu
MonGraphique.setColor(new Color(50,80,255));
MonGraphique.fillPolygon(FormeX[di],FormeY[di],5);
// Contour des Formes en Jaunes pour visualiser la solution
MonGraphique.setColor(new Color(255,255,0));
MonGraphique.drawPolygon(FormeX[di],FormeY[di],5);
// Affichage du r�sultat courant du graphique
MonAppletGraphique.drawImage(MonImage,0,0,this );
public void start(){   
// MonPuzzleChinois : Start !
addItem("MonPuzzleChinois : Start ! ");
// Cr�ation du Thread principal
if(MonThread == null){
MonThread = new Thread(this);
MonThread.start();
public void stop(){
// MonPuzzleChinois : Stop !
addItem("MonPuzzleChinois : Stop ! ");
// Arr�t du Thread
MonThread = null;
public void run(){
// MonPuzzleChinois : Run !
// R�cup�ration du Nom du Host d'o� est charg�e l'Applet
String host = getCodeBase().getHost();
addItem("Ex�cution depuis www.LouiseTV.com " + host);
// Execution du Thread principal (Pause si n�cessaire)
while (MonThread != null){
try {
Thread.sleep(30);
catch (InterruptedException e){ }
public void destroy() {
// MonPuzzleChinois : Destroy !
addItem("MonPuzzleChinois : Destroy ! ");
// Mise � jour de l'affichage principal via la m�thode update()
public void update( Graphics MonAppletGraphique ){
paint( MonAppletGraphique ) ;
// Envoie des infos de l'Applet au Syst�me
// A Afficher depuis l'AppletViewer...
public String getAppletInfo() {
return "Applet MonPuzzleChinois - Dess Multim�dia - T3 - Jean Paul CONAN - 2003";

Similar Messages

  • Rotate Image Created with createImage() ?

    I've been looking around online for a way to do this, but so far the only things I have found are 50+ lines of code. Surely there is a simple way to rotate an image created with the createImage() function?
    Here's some example code with all the tedious stuff already written. Can someone show me a simple way to rotate my image?
    import java.net.*;
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class RotImg extends JApplet implements MouseListener {
              URL base;
              MediaTracker mt;
              Image myimg;
         public void init() {
              try{ mt = new MediaTracker(this);
                   base = getCodeBase(); }
              catch(Exception ex){}
              myimg = getImage(base, "myimg.gif");
              mt.addImage(myimg, 1);
              try{ mt.waitForAll(); }
              catch(Exception ex){}
              this.addMouseListener(this);
         public void paint(Graphics g){
              super.paint(g);
              Graphics2D g2 = (Graphics2D) g;
              g2.drawImage(myimg, 20, 20, this);
         public void mouseClicked(MouseEvent e){
              //***** SOME CODE HERE *****//
              // Rotate myimg by 5 degrees
              //******** END CODE ********//
              repaint();
         public void mouseEntered(MouseEvent e){}
         public void mouseExited(MouseEvent e){}
         public void mousePressed(MouseEvent e){}
         public void mouseReleased(MouseEvent e){}
    }Thanks very much for your help!
    null

    //  <applet code="RotationApplet" width="400" height="400"></applet>
    //  use: >appletviewer RotationApplet.java
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.AffineTransform;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    public class RotationApplet extends JApplet {
        RotationAppletPanel rotationPanel;
        public void init() {
            Image image = loadImage();
            rotationPanel = new RotationAppletPanel(image);
            setLayout(new BorderLayout());
            getContentPane().add(rotationPanel);
        private Image loadImage() {
            String path = "images/cougar.jpg";
            Image image = getImage(getCodeBase(), path);
            MediaTracker mt = new MediaTracker(this);
            mt.addImage(image, 0);
            try {
                mt.waitForID(0);
            } catch(InterruptedException e) {
                System.out.println("loading interrupted");
            return image;
    class RotationAppletPanel extends JPanel {
        BufferedImage image;
        double theta = 0;
        final double thetaInc = Math.toRadians(5.0);
        public RotationAppletPanel(Image img) {
            image = convert(img);
            addMouseListener(ml);
        public void rotate() {
            theta += thetaInc;
            repaint();
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            double x = (getWidth() - image.getWidth())/2;
            double y = (getHeight() - image.getHeight())/2;
            AffineTransform at = AffineTransform.getTranslateInstance(x,y);
            at.rotate(theta, image.getWidth()/2, image.getHeight()/2);
            g2.drawRenderedImage(image, at);
        private BufferedImage convert(Image src) {
            int w = src.getWidth(this);
            int h = src.getHeight(this);
            int type = BufferedImage.TYPE_INT_RGB; // options
            BufferedImage dest = new BufferedImage(w,h,type);
            Graphics2D g2 = dest.createGraphics();
            g2.drawImage(src,0,0,this);
            g2.dispose();
            return dest;
        private MouseListener ml = new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                rotate();
    }

  • Createimage() using way way way too much CPU!

    Try the following code. Note you will need Java 5.0 to compile it. There are 3 files. Compile and run ApplicationManager.java
    ApplicationManager.java_
    import java.awt.event.ActionEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import javax.swing.JButton;
    * This is the starting point of the application. It is mainly entrusted with the task of respondong to events
    * generated by MainWindow
    public class ApplicationManager extends MouseAdapter implements ActionListener{
    MainWindow mainWin;
    static ApplicationManager application = null;
          * Main is here. The application starts here.
          * @param args
    public static void main(String[] args) {
              application = new ApplicationManager();
              application.startApp();
          * Initializes the application by doing stuffs that are needed to be done only at startup.
    public void startApp(){
         System.out.println("startApp()");
            mainWin=new MainWindow();
         //Making the main windows visible.
         mainWin.makeAppVisible();
         mainWin.addNewClientSpace("New0");
         ManagerUI m;
             try{
                 //m =mainWin.clientSpace.get(mainWin.ClientArea.getSelectedIndex());
                 m =mainWin.clientSpace.get(0);
             catch(java.lang.NullPointerException e){
               e.printStackTrace();
               return;
    public void actionPerformed(ActionEvent e) {}
    public void mouseClicked(java.awt.event.MouseEvent e){}
    MainWindow.java_
    import java.awt.event.KeyEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.Event;
    import java.awt.BorderLayout;
    import javax.swing.KeyStroke;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JMenuItem;
    import javax.swing.JMenuBar;
    import javax.swing.JMenu;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import java.awt.Dimension;
    import javax.swing.JTabbedPane;
    import java.util.ArrayList;
    class MainWindow {
         private JFrame jFrame = null;  //  @jve:decl-index=0:visual-constraint="10,10"
         private JPanel jContentPane = null;
         private JMenuBar jJMenuBar = null;
         private JMenu fileMenu = null;
         private JMenuItem exitMenuItem = null;
         private JMenuItem aboutMenuItem = null;
         JMenuItem saveMenuItem = null;
         private JLabel jLabel = null;
         private JMenuItem jMenuItem = null;
            JTabbedPane ClientArea = null;
            ArrayList<ManagerUI> clientSpace;
          * This method initializes jFrame
          * @return javax.swing.JFrame
         private JFrame getJFrame() {
              if (jFrame == null) {
                   jFrame = new JFrame();
                   jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   jFrame.setJMenuBar(getJJMenuBar());
                   jFrame.setSize(1014, 534);
                   jFrame.setContentPane(getJContentPane());
                   jFrame.setTitle("LANSim");
              return jFrame;
          * This method initializes jContentPane
          * @return javax.swing.JPanel
         private JPanel getJContentPane() {
              if (jContentPane == null) {
                   jContentPane = new JPanel();
                   jContentPane.setLayout(new BorderLayout());
                   jContentPane.add(getClientArea(), BorderLayout.CENTER);
              return jContentPane;
          * This method initializes jJMenuBar
          * @return javax.swing.JMenuBar
         private JMenuBar getJJMenuBar() {
              if (jJMenuBar == null) {
                   jJMenuBar = new JMenuBar();
                   jJMenuBar.add(getFileMenu());
              return jJMenuBar;
          * This method initializes jMenu
          * @return javax.swing.JMenu
         private JMenu getFileMenu() {
              if (fileMenu == null) {
                   fileMenu = new JMenu();
                   //fileMenu.getPopupMenu().setLightWeightPopupEnabled(false);
                   fileMenu.setText("File");
                   fileMenu.add(getSaveMenuItem());
                   fileMenu.add(getExitMenuItem());
                   fileMenu.add(getJMenuItem());  // Generated
              return fileMenu;
          * This method initializes jMenuItem
          * @return javax.swing.JMenuItem
         private JMenuItem getExitMenuItem() {
              if (exitMenuItem == null) {
                   exitMenuItem = new JMenuItem();
                   exitMenuItem.setText("Exit");
                   exitMenuItem.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             System.exit(0);
              return exitMenuItem;
          * This method initializes jMenuItem
          * @return javax.swing.JMenuItem
         private JMenuItem getSaveMenuItem() {
              if (saveMenuItem == null) {
                   saveMenuItem = new JMenuItem();
                   saveMenuItem.setText("Save");
                   saveMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
                             Event.CTRL_MASK, true));
                   saveMenuItem.addActionListener(ApplicationManager.application);
              return saveMenuItem;
          * This method initializes jMenuItem
          * @return javax.swing.JMenuItem
         private JMenuItem getJMenuItem() {
              if (jMenuItem == null) {
                   jMenuItem = new JMenuItem();
              return jMenuItem;
          * This method initializes ClientArea
          * @return javax.swing.JTabbedPane
         private JTabbedPane getClientArea() {
         if (ClientArea == null) {
                   ClientArea = new JTabbedPane();
                   ClientArea.setTabPlacement(JTabbedPane.BOTTOM);  // Generated
                   ClientArea.setPreferredSize(new Dimension(100, 100));  // Generated
                          ClientArea.addMouseListener(ApplicationManager.application);
            return ClientArea;
          * Called to create a new client space where the contents of another file can be shown or created.
          * This allows for opening and creation of multiple files.
         public void addNewClientSpace(String title){
              ClientArea.addTab(title, new JScrollPane().add(getClientRegion(title)));
          * Creates a new client Region and also updates clientSpace.
          * @return
         private ManagerUI getClientRegion(String title){
              ManagerUI m = new ManagerUI(title);
              getClientSpace();
              clientSpace.add(m);
              return m;
          *  This Method intiializes clientSpace if  is null
          *  @return  java.util.ArrayList
        private ArrayList getClientSpace(){
            if(clientSpace==null){
                  clientSpace= new  ArrayList<ManagerUI>();
            return clientSpace;
          * Makes the MainWindow visible
         public void makeAppVisible(){
              getJFrame().setVisible(true);
    ManagerUI.java_
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.Toolkit;
    import java.util.ArrayList;
    import javax.swing.JPanel;
    import java.awt.Color;
    public class ManagerUI extends JPanel implements Runnable{
    private int frame=0; //This wasn't declared in actual program.
    private Image simBuffer;
    private volatile boolean terminate;
    It does all the drawing in graphics area.
    ManagerUI(String name){
      terminate=false;
      simBuffer=null;
      Thread t;
      t=new Thread(this,name);//Starts the rendering thread.
      t.start();
    public void stop(){
      terminate=true;
    public void run(){
         System.out.println("Thread Started");
           long afterTime, beforeTime, timeDiff, sleepTime;
         long overSleepTime = 0L; //Amount of time (in ms) over slept.
         int noDelays = 0; //Counter for no. of sleeps it has skipped.
         long period = (long) (((double) 1000)/30); //Amount of time a frame maybe displayed, in ms.
         terminate = false;
         beforeTime = System.currentTimeMillis( );
         while(!terminate){
                 repaint();
              //render2buf();
              //activepaint();
              afterTime = System.currentTimeMillis( );
              timeDiff = afterTime - beforeTime;
              sleepTime = (period - timeDiff) - overSleepTime;   // time left in this loop
              if (sleepTime > 0) {   // some time left in this cycle
              try {
                   Thread.sleep(sleepTime);  // in ms
              catch(InterruptedException ex){}
              overSleepTime = (System.currentTimeMillis( ) - afterTime) - sleepTime;
              else {    // sleepTime <= 0; frame took longer than the period
                   overSleepTime = 0L;
                   if (++noDelays >= 6) {
                        Thread.yield( );   // give another thread a chance to run
                        noDelays = 0;
              beforeTime = System.currentTimeMillis( );
    public  synchronized Image render2buf(){
            if(this.getSize().height<=0 || this.getSize().width<=0) return null;
            int PHEIGHT = this.getSize().height;
             int PWIDTH = this.getSize().width;
             Graphics g=null;
             //draw the current frame to an image buffer    
            if (simBuffer == null){  //PROBLEM LINE. coment out this line and...
                 simBuffer = createImage(PWIDTH, PHEIGHT);
                if (simBuffer == null) {
                     System.out.println("simBuffer is null");
                     return null;
                }//PROBLEM LINE. ...this line
            g = simBuffer.getGraphics( );
            //Clear the background
            g.setColor(Color.white);
            g.fillRect (0, 0, PWIDTH, PHEIGHT);
             //code to draw graphics into 'g'.
             g.setColor(Color.BLACK);
             g.drawString("This is test message.",50,50);
             g.drawString("Frame No = "+(frame++),50,200);
         return simBuffer;
    public synchronized void activepaint(Graphics g){//This code is taken from OReilly Killer Game Programming in Java
             //Graphics g;
            try {
                 //g = this.getGraphics( );  // get the panel's graphic context
                  if ((g != null) && (simBuffer != null))
                       g.drawImage(simBuffer, 0, 0, null);
                  Toolkit.getDefaultToolkit( ).sync( );  // sync the display on some systems
                  if (g != null) g.dispose( );
            catch (Exception e)
                 System.out.println("Graphics context error: " + e);
                 e.printStackTrace();
    public void paintComponent(Graphics g){
         super.paintComponent(g);
         render2buf();
         activepaint(g);
    First compile and run the above program. Now in file ManagerUI.java search for two lines with the text "PROBLEM LINE". Comment out both these lines and recompile and re-run the program. Now the CPU usage shoots to above 60% from around 2% (in former case). Why is this happening? Is there a workaround? I have Kubuntu Feisty Fawn 7.04. I have Sun Java 1.6.0-b105 installed.

    Ok here is the modified and updated version. Now I have condensed the program to two files. Now compile and run Main.java
    Main.java_
    import javax.swing.*;
    import java.awt.BorderLayout;
    class Main{
         ManagerUI m;
         public static void main(String a[]){
              Main M = new Main();
              M.startapp();
              M.m.startthread();
         private void startapp(){
              JFrame jFrame = new JFrame();
              jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              jFrame.setSize(1014, 534);
              jFrame.setContentPane(getJContentPane());
              jFrame.setTitle("LANSim");
              jFrame.setVisible(true);
         private JPanel getJContentPane() {
              m = new ManagerUI();
              JPanel jContentPane;
              jContentPane = new JPanel();
              jContentPane.setLayout(new BorderLayout());
              jContentPane.add(m, BorderLayout.CENTER);
              return jContentPane;
    ManagerUI.java_
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.Toolkit;
    import java.util.ArrayList;
    import javax.swing.JPanel;
    import java.awt.Color;
    public class ManagerUI extends JPanel implements Runnable{
    private int frame=0; //This wasn't declared in actual program.
    private Image simBuffer;
    private volatile boolean terminate;
    private Thread t;
    It does all the drawing in graphics area.
    ManagerUI(){
      terminate=false;
      simBuffer=null;
    public void startthread(){
              if(t!=null){
                   terminate = true;
                   try {
                        t.join();//Wait for the thread to end.
                   } catch (InterruptedException e) {
                        System.out.println("Failed to join to ManagerUI Thread before starting another one.");
                        e.printStackTrace();
              terminate=false;
              t=new Thread(this,"Manager");
            t.start();
    public void stop(){
      terminate=true;
    public void run(){
         System.out.println("Thread Started");
           long afterTime, beforeTime, timeDiff, sleepTime;
         long overSleepTime = 0L; //Amount of time (in ms) over slept.
         int noDelays = 0; //Counter for no. of sleeps it has skipped.
         long period = (long) (((double) 1000)/30); //Amount of time a frame maybe displayed, in ms.
         terminate = false;
         beforeTime = System.currentTimeMillis( );
         while(!terminate){
              render2buf();
                 repaint();
              afterTime = System.currentTimeMillis( );
              timeDiff = afterTime - beforeTime;
              sleepTime = (period - timeDiff) - overSleepTime;   // time left in this loop
              if (sleepTime > 0) {   // some time left in this cycle
              try {
                   Thread.sleep(sleepTime);  // in ms
              catch(InterruptedException ex){}
              overSleepTime = (System.currentTimeMillis( ) - afterTime) - sleepTime;
              else {    // sleepTime <= 0; frame took longer than the period
                   overSleepTime = 0L;
                   if (++noDelays >= 6) {
                        Thread.yield( );   // give another thread a chance to run
                        noDelays = 0;
              beforeTime = System.currentTimeMillis( );
    public Image render2buf(){
            if(this.getSize().height<=0 || this.getSize().width<=0) return null;
            int PHEIGHT = this.getSize().height;
             int PWIDTH = this.getSize().width;
             Graphics g=null;
             //draw the current frame to an image buffer    
            if (simBuffer == null){  //PROBLEM LINE. coment out this line and...
                 simBuffer = createImage(PWIDTH, PHEIGHT);
                if (simBuffer == null) {
                     System.out.println("simBuffer is null");
                     return null;
            }//PROBLEM LINE. ...this line
            g = simBuffer.getGraphics( );
            //Clear the background
            g.setColor(Color.white);
            g.fillRect (0, 0, PWIDTH, PHEIGHT);
             //code to draw graphics into 'g'.
             g.setColor(Color.BLACK);
             g.drawString("This is test message.",50,50);
             g.drawString("Frame No = "+(frame++),50,200);
         return simBuffer;
    public void paintComponent(Graphics g){
         super.paintComponent(g);
         if(simBuffer!=null)
         g.drawImage(simBuffer,0,0,null);
    }Don't forget to comment out the lines with the text PROBLEM LINE

  • BorderLayout question!

    I'm trying to create a VendingMachine GUI for an AP Computer Science class, and I'm having trouble actually displaying th GUI I have created.. Here is the main() method.
    int main() {
              JFrame frame = new JFrame();
              createImages();
              BorderLayout rootframe = new BorderLayout();
              JPanel mainpad = new JPanel(createMainPad());
              JPanel numpad = new JPanel(createNumPad());
              JPanel moneypad = new JPanel(createMoneyPad());
              JTextField price = new JTextField();
              rootframe.addLayoutComponent(mainpad, BorderLayout.CENTER);
              rootframe.addLayoutComponent(numpad, BorderLayout.EAST);
              rootframe.addLayoutComponent(moneypad, BorderLayout.EAST);
              rootframe.addLayoutComponent(price, BorderLayout.EAST);
              frame.setLayout(rootframe);
              frame.pack();
              frame.setVisible(true);
              return 0;
         }When the frame pops up it is completely blank, and I'm clueless as to why! All the JPanels should be created correctly through those methods such as "createMainPad()" Is the BorderLayout causing my problems?

    This would be the normal way to add components to a JFrame. Your original code added 3 components to EAST, only 1 component can occupy each of the 5 spots. If you really want 3 components in the east you would need to create a JPanel, add the 3 components to the JPanel, then put the Panel in the east of the frame.
    int main() {
              JFrame frame = new JFrame();
              createImages();
              JPanel mainpad = new JPanel(createMainPad());
              JPanel numpad = new JPanel(createNumPad());
              JPanel moneypad = new JPanel(createMoneyPad());
              JTextField price = new JTextField();
              frame.add(mainpad, BorderLayout.CENTER);
              frame.add(numpad, BorderLayout.EAST);
              frame.add(moneypad, BorderLayout.SOUTH);
              frame.add(price, BorderLayout.NORTH);
              frame.pack();
              frame.setVisible(true);
              return 0;
         }

  • CreateImage - Double Buffer

    I don't know if I understand correctly, but Canvas.createImage(int, int)
    should be creating an Image of the Canvas with all graphics on it?
    I just get in image filled ny the background color of the Canvas(white).
    Iow, if you have a Canvas where you've drawn some Lines, Polygons, etc.
    shouldn't that be "part of the picture"?
    I was using the java.awt.Robot to do a Screen Capture, but it doesn't
    work on the Mobile Device I'm testing on. Any suggestions on how to
    achieve an exact Screen Capture with Java 1 would be greatly appreciated.

    Here's a rewritten version of your code that should work a bit better:
    import java.awt.BorderLayout;
    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Event;
    import java.awt.Frame;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    public class DrawRect extends Canvas {
      public static void main(String[] args) {
        DrawRect dr = new DrawRect();
        dr.setSize(500, 500);
        Frame f = new Frame("DrawRect");
        f.setLayout(new BorderLayout());
        f.add(BorderLayout.CENTER, dr);
        f.pack();
        f.addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            System.exit(0);
        }); // anonymous window listener
        f.setVisible(true);
      private Image backgroundImage;
      private int beginX, beginY;
      private int endX, endY;
      private Dimension prevSize;
      public DrawRect() {
        super();
      public void recreateBackground(int width, int height) {
        backgroundImage = createImage(width, height);
        paintAll(backgroundImage.getGraphics());
      public boolean mouseDown(Event evt, int x, int y) {
        beginX = endX = x;
        beginY = endY = y;
        repaint();
        return true;
      public boolean mouseDrag(Event evt, int x, int y) {
        endX = x;
        endY = y;
        repaint();
        return true;
      public boolean mouseUp(Event evt, int x, int y) {
        endX = x;
        endY = y;
        repaint();
        return true;
      public void update(Graphics g) {
        paint(g);
      public void paint(Graphics g) {
        Dimension thisSize = getSize();
        if (prevSize == null || !prevSize.equals(thisSize)) {
          recreateBackground(thisSize.width, thisSize.height);
          prevSize = thisSize;
        g.drawImage(backgroundImage, 0, 0, this);   
        paintRectangle(g);
      private void paintRectangle(Graphics g) {
        int x = Math.min(beginX, endX);
        int y = Math.min(beginY, endY);
        int width = Math.abs(endX - beginX);
        int height = Math.abs(endY - beginY);
        g.setColor(Color.YELLOW);
        g.drawRect(x - 1, y - 1, width + 2, height + 2);
        g.setColor(Color.BLACK);
        g.drawRect(x, y, width, height);
       * Simulation for map feature drawing
      public void paintAll(Graphics g) {
        int x = 1;
        int y = 10;
        for (int i = 0; i < 3000; i++) {
          g.setColor(Color.lightGray);
          g.fillOval(x, y, 10, 10);
          g.setColor(Color.gray);
          g.drawOval(x, y, 10, 10);
          x += 11;
          if (x >= getBounds().width) {
            x = 1;
            y += 11;
        g.setColor(Color.red);
        g.fillRect(10, 10, 100, 100);
        g.setColor(Color.blue);
        g.drawRect(10, 10, 100, 100);
        g.setColor(Color.green);
        g.fillOval(50, 50, 100, 100);
        g.setColor(Color.blue);
        g.fillRect(50, 200, 100, 100);

  • How can I create a single background image for a BorderLayout?

    I can create a background with an image file for the individual panel (North, West, Center, East and South) in a BorderLayout, but I've been spinning my wheel for a long while now trying to figure out how to create just one background with a single image file for all of these panels?
    In my application, a panel may contain various buttons, a listbox, a group of checkboxes, a combo box, or a canvas. Even if I used the same image file, when the panels are finally put together, one can clearly see that the end product is the result of a lot of patch works.
    Hope someone has an answer for this. BTW, I'm using AWT because it works with existing browsers without the need for a separate Java plug-in.
    Regards,
    V.V.

    Look at this :
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.awt.image.BufferedImage;
    public class PanI extends Frame
         Image map;
         Panel pan;
         myPan p8,p4,p6,p2,p5;
         BufferedImage I;
    public PanI() 
         addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);}});
         map = getToolkit().getImage("map2.gif");
         MediaTracker tracker = new MediaTracker(this);
         tracker.addImage(map,0);
         try   {tracker.waitForID(0);}
         catch (InterruptedException e){}
         I = new BufferedImage(1,1,BufferedImage.TYPE_INT_ARGB);
         setBounds(10,10,map.getWidth(null)+8,map.getHeight(null)+27);
         setLayout(new BorderLayout());
         pan = new Panel();
         add(pan,BorderLayout.CENTER);
         pan.setLayout(new BorderLayout());
         pan.setSize(map.getWidth(null),map.getHeight(null));
         p5 = new myPan(5);
         p5.setBackground(Color.red);
         pan.add(p5,BorderLayout.CENTER);
         p8 = new myPan(8);
         p8.setBackground(Color.orange);
         pan.add(p8,BorderLayout.NORTH);
         p4 = new myPan(4);
         p4.setBackground(Color.blue);
         pan.add(p4,BorderLayout.WEST);
         p6 = new myPan(6);
         p6.setBackground(Color.green);
         pan.add(p6,BorderLayout.EAST);
         p2 = new myPan(2);
         p2.setBackground(Color.pink);
         pan.add(p2,BorderLayout.SOUTH);
         setVisible(true);
    public class myPan extends Panel
         int where;
    public myPan(int i)
         super();
         where = i;
    public void paint(Graphics g)
         if (I.getWidth(null) != pan.getWidth() || I.getHeight(null) != pan.getHeight())
              I = new BufferedImage(pan.getWidth(),pan.getHeight(),BufferedImage.TYPE_INT_ARGB);
              Graphics      G = I.getGraphics();
              G.drawImage(map,0,0,pan.getWidth(),pan.getHeight(),null);     
              G.dispose();
         int x1=0;
         int x2=getWidth();
         int y1=0;
         int y2=getHeight();
         if (where == 8)
         if (where == 2)
              y1 =  p8.getHeight()+p5.getHeight();
              y2 =  getHeight()+y1;
         if (where == 4)
              y1 =  p8.getHeight();
              y2 =  y1+getHeight();
         if (where == 5)
              x1 =  p4.getWidth();
              x2 =  x1+getWidth();
              y1 =  p8.getHeight();
              y2 =  y1+getHeight();
         if (where == 6)
              x1 =  p4.getWidth()+p5.getWidth();;
              x2 =  x1+getWidth();
              y1 =  p8.getHeight();
              y2 =  y1+getHeight();
         g.drawImage(I,0,0,getWidth(),getHeight(),x1,y1,x2,y2,null);
    public void update(Graphics g)
         paint(g);
    public static void main (String[] args) 
         new PanI();
    Noah

  • Why doesn't borderlayout work?

    Borderlayout seems to not work here. I need the textfield to be north, two buttons under that, and then a label south, but it only shows the label, but if I comment out the field, I see the buttons, please help, here is my code
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.Color;
    import java.awt.Graphics;
    class GUI
         private JLabel label1;
         private JButton clear;
         private JTextField field1;
         public static void main(String[] args)
              final JFrame f = new JFrame("");
              /*Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
              screenSize.width -=42;
              screenSize.height -= 42;*/
              f.setSize(1024,768);
              f.setLocation(20,20);
              f.setVisible(true);
         final JDesktopPane desktop = new JDesktopPane();
              desktop.setPreferredSize(new Dimension(1024, 768));
              desktop.setBackground(new Color(148,102,75));
              desktop.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
              f.setContentPane(desktop);
              final JInternalFrame fr = new JInternalFrame("infix", false, true, true, true);
              fr.setSize(203, 126);
              fr.setLocation(50, 50);
              fr.setVisible(true);
              fr.setOpaque(false);
              fr.setBackground(new Color(100,0,255,140));
         JPanel panel = new JPanel();
         panel.setLayout(new BorderLayout(0,0));
              panel.setSize(203,126);
              panel.setBackground(new Color(0,0,255,140));
              panel.setOpaque(false);
              JTextField field1 = new JTextField("",60);
              field1.setPreferredSize(new Dimension(200, 21));
              panel.add(field1,BorderLayout.NORTH);
              JButton evaluate = new JButton("Evaluate");
              evaluate.setPreferredSize(new Dimension(115,25));
              panel.add(evaluate,BorderLayout.CENTER);
              JButton clear = new JButton("Clear");
              clear.setPreferredSize(new Dimension(115,25));
              panel.add(clear,BorderLayout.EAST);
         JLabel label = new JLabel("");
              label.setPreferredSize(new Dimension(34,100));
              panel.add(label,BorderLayout.SOUTH);
              fr.add(panel);     
              desktop.add(fr);
              JInternalFrame fr2 = new JInternalFrame("test", true, true, true,false);
              fr2.setSize(230, 300);
              fr2.setLocation(50, 50);
              fr2.setVisible(true);
              fr2.setOpaque(false);
              fr2.setBackground(new Color(0,0,255,140));
         JPanel panel2 = new JPanel();
         panel2.setLayout(new BorderLayout(0, 0));
              fr2.add(panel2);
              desktop.add(fr2);
              //f.getContentPane().add(desktop);
              f.add(desktop);
         }

    guess what I have fixed it myself, this was the problem label.setPreferredSize(new Dimension(34,100)); wrong size, but I change it to 34, 50 and its work

  • How do I put two centered text in a PAGE_START in BorderLayout ?

    Hi everybody.
    I am using a BorderLayout and in PAGE_START section I want to put a title(centered, with two rows). I don't know how to do that. When I put my text there, is on the left side.
    Thanks.
    Edited by: blackblack13 on Jul 18, 2009 1:08 AM

    Aaa yes, you're right. The thing with two JLabels is very good, I didn't think about that. But with HTML I don't know how to use it. Where can I find smth about that?
    Thanks a lot !

  • I gt problem in createImage method, Please Help Me!

    This part of code is from Ticker.Class:
    public void createParams()
         {//tickerTape.x = 900;
              //tickerTape.y = 40;
              int width = getSize().width;
              //System.out.println("getSize().width "+getSize().width);
              int height = getSize().height;
              lastS.width = width;
              lastS.height = height;
              System.out.println("width"+width);
              //System.out.println("width: " + width + " height: " + height);
              tickerTape.createParamsgr();
              Font font = tickerTape.getDefaultFont();
              this.setFont(font);
              FontMetrics metrics = getFontMetrics(font);
              metrics = getFontMetrics(font);
              int k = getFontMetrics(font).getHeight();
              //tickerTape.cParams();
              //tickerTape.createParams1(lastS);
              //setSize(tickerTape.cParamsHeight(),tickerTape.cParamsWidth());
         //     messageY = tickerTape.cParamsY();
              messageX = width;
              messageY = (height - k >> 1) + metrics.getAscent();
                   image = createImage(getSize().width,getSize().height);
                   tickerTape.initImage(image);
                   //gr=image.getGraphics();
         public  void paint(Graphics g)
          update(g);
         public synchronized void update(Graphics g)
              //gr.clearRect(0, 0, d.getSize().width, d.getSize().height);
              //gr.setColor(bgCo);
              //gr.drawRect(0, 0, d.getSize().width - 1, d.getSize().height - 1);
              //gr.fillRect(0, 0, d.getSize().width, d.getSize().height);
              //g.drawImage(image, 0, 0, this);
              if (Ticker.LOADING_DATA) {
                   System.out.println("Refreshing data. Please wait....");
                   return;
              try {
                   if(image==null)
                   image = createImage(getSize().width, getSize().height);
                   tickerTape.initImage(image);
                   //if (tickerTape.cParamsHeight() != lastS.height|| tickerTape.cParamsWidth() != lastS.width)
                   if (getSize().height != lastS.height|| getSize().width != lastS.width)
                   createParams();
                   if (tickerTape.getDisplayItems().size() > 0) {
                        //System.out.print("lastS.width: " + lastS.width + " lastS.height: " + lastS.height + "\n");
                        tickerTape.setBackground(lastS,bgCo,messageX,messageY);
                        if (display_URL) {
                             int k = mouseX;
                              //System.out.println("k=" + k + " messageX=" + messageX);
                             if (k > messageX) {
                                  //System.out.println("(k > messageX) is true!!");
                                  //System.out.println("messageCount----> " + messageCount);
                                  messageCount = tickerTape.displayItemsCnt;
                                  k -= messageX;
                                  switch (this.mouseEvent) {
                                  case TickerTape.SCROLL_LEFT:
                                       break;
                                  case TickerTape.SCROLL_RIGHT:
                                       // for (int i1 = 0; i1 <= messageCount - 1; i1++)
                                       // i += ((Integer) msgsW.elementAt(i1)).intValue();
                                       // if (k >= i)
                                       // continue;
                                       // messageIndex = i1;
                                       // break;
                                       // break;
                                  if (this.mouseEvent == MOUSE_CLICK) {
                                       // showStatus((String)
                                       // msgsURL.elementAt(messageIndex));
                        //Font itemFont = null;
                        //FontMetrics fontMetrics = null;
                        //Color textColor = null;
                        //Vector msgs = tickerTape.getDisplayItems();
                                  switch (tickerTape.getScrollDirection()) {
                                  case TickerTape.SCROLL_LEFT:
                                       tickerTape.moveLeft(messageX,messageY);
                                       g.drawImage(image, 0, 0, this);
                                       break;
                                  case TickerTape.SCROLL_RIGHT:
                                       tickerTape.moveRight(messageX,messageY,ItemToDisplay);
                                       g.drawImage(image, 0, 0, this);
                                       break;
                                  case TickerTape.SCROLL_UP:
                                  case TickerTape.SCROLL_DOWN:
                                       tickerTape.moveDown(messageX,messageY);
                                       g.drawImage(image, 0, 0, this);
                                       //g.drawImage(image, 0, 0, this);
                                       break;
                   }     else {
                             image = createImage(getSize().width, getSize().height);
                             tickerTape.initImage(image);
                             //gr=image.getGraphics();
                             tickerTape.setBackground(lastS,bgCo,messageX,messageY);
                             g.drawImage(image, 0, 0, this);
              } catch (Exception e) {
                   e.printStackTrace();
         }This part of code from TickerTape.Class:
    public void createParamsgr(){
              if (gr != null)
                   gr.finalize();
              if (image != null)
                   image = null;
         public void initImage(Image image){
              gr = image.getGraphics();
         }This code already runable. But my question is Why when I decide to move the createImage method into the method of initImage in TickerTape.class, then it come out the error with nullpointer, why like that? is it im make any wrong thing? Or any solution for me to make it correct. Thanks and appreciate!

    hi, thanks for your reply.
    let me briefly explain to you,
    now, you try to look at the createParams() method and update(Graphics g) method int Ticker.class, inside there also got
    image = createImage(getSize().width, getSize().height);
    tickerTape.initImage(image);
    So, now I want to move the code:
    image = createImage(getSize().width, getSize().height);
    into the TickerTape.class but dont Why come out the error with:
    java.lang.NullPointerException
         at TickerTape.initImage(TickerTape.java:90)
         at Ticker.update(Ticker.java:503)
         at sun.awt.RepaintArea.updateComponent(RepaintArea.java:239)
         at sun.awt.RepaintArea.paint(RepaintArea.java:216)
         at sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:254)
         at java.awt.Component.dispatchEventImpl(Component.java:4031)
         at java.awt.Container.dispatchEventImpl(Container.java:2024)
         at java.awt.Component.dispatchEvent(Component.java:3803)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:463)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    but it doesnt work!
    Is it I put wrong thing or I forgot to put any important code?

  • Problem with Image.createImage()

    Hi all!
    I'm writing a simple midlet just to display an image on the screen and I'm having some problems with Image.createImage()
    Here is my code
    Image bg_img;
    ImageItem imageItem1;
    imageItem1 = new ImageItem("", null,ImageItem.LAYOUT_DEFAULT, "");
    try{
    bg_img = Image.createImage("/image.png");
    imageItem1.setImage(bg_img);
    catch(java.io.IOException e){
    e.printStackTrace();
    I'm getting an exception on bg_img = Image.createImage("/image.png");
    I can't understand what is it...:(
    I know for sure that the problem is not "file not found"
    Any one can help me???

    If you are catching IOException, then u may have problem with ur image path. "image not found on the specified path." if ur image is not in the current directiry then put it into current directory. otherwise, If u are using resouce folder and it is already included into the resouce path, then put ur image in that folder..try this..
    Still not get, then please give some detail about ur development toolkit. and ur apllication packaging scheem. are you using ANT?
    Pranav

  • Maximum size for JPanel in BorderLayout

    I'am using a BorderLayout in my JFrame. I want to place a JPanel in BorderLayout.CENTER. The problem: It should use the maximum possible space.
    For example, if I place a JButton in CENTER, the JButton will grow very big. I want the same behaviour for a JPanel.
    Using setPreferredSize doesn't seem to be a solution because I want the JPanel to resize dynamically, like a JButton does.
    Any ideas? :-)
    Thanks

    The borderlayout is the layout which resizes the components as and when the frame is resized. So i think you should not have a problem like resizing.
    One more thing when u are adding a panel with a borderlayout, do specify where the components are to be added on the panel. i.e. on north, center or south,etc...
    May be this simple example help u out, just copy paste the code and run it.
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class BorderMain extends JFrame {
    Container c;
    JPanel pnl;
    BorderLayout bl;
    public BorderMain()
         setPreferredSize(new Dimension(200,200));
         c = getContentPane();
         bl = new BorderLayout();
         pnl = new JPanel();
         pnl.setLayout(bl);
         pnl.setBackground(Color.GRAY);
         c.add(pnl);
         c.validate();
         setVisible(true);
         pack();
         public static void main(String[] args) {
              new BorderMain();
    now when u add anythin to the panel just say
    pnl.add(new JButton("OK"), BorderLayout.NORTH);
    pnl.add(new JButton("OK"), BorderLayout.CENTER);
    pnl.add(new JButton("OK"), BorderLayout.SOUTH);
    this is just an example.
    if u add anything only to north, then to the panel will occupy all the space given.
    Regards
    Poonam.
    and if ur adding another panel on a panel with the borderlayout then u need to set the same layoutfor the inner panel also.

  • Keyboard shortcuts in JTabbedPane don't work in BorderLayout

    I'm mystified by a problem that doesn't seem to make any sense. I have a JTabbedPane with mnemonics, that used to work well before. But since I've shuffled components around a bit and put the JTabbedPane in the BorderLayout.CENTER of a JPanel, the keyboard shortcuts no longer work.
    The appropriate letters are underlined, but the Alt+letter sequence no longer switched tabs. Other components (JButtons) with keyboard shortcuts in the same JPanel, but in the BorderLayout.SOUTH or elsewhere, work as expected.
    It sounds like a bug to me, but is there perhaps a workaround?
    Thanks,
    - Peter

    I keep replying to my own posts...
    I figured out that the tabs start working once a component in them (say, a JTextField) receives keyboard focus. It does sound a bit suspicious to me, but I can live with it.
    Unfortunately, setting the focus programmatically doesn't seem to work: requestFocus() or requestFocusInWindow() on the first JTestBox simply don't work.
    - Peter

  • Set the minimal size of a Component with BorderLayout

    Hi,
    I got a little problem using BorderLayout.
    The scenario is :
    A JPanel placed BorderLayout.WEST got a size a few pixel too small for a JTable contained in this panel to paint all names of the table header.
    If i set the preferredScrollableViewportSize larger then a specific amount the table disappear(shrinks to a tiny size)
    The panel uses GridBagLayout...
    How can i set the size of this "west"-component of the border layout a little larger?
    regards
    Olek

    My understanding of help is an other then only post messages likeWell, your understanding, in my opinion is wrong.
    You must post a self documenting program ...Not everybody who uses this forum speaks english as their main language. Even if english is your main language it is not always easy to communicate the problem effectively. By posting demo code we can see exactly what you are doing.
    Or why you don't read the API... Of course that is a valid answer. You should always read the API. Why should we waste time typing the Documentation from the API when we can point you directly to the API????????
    why you don't search the forum Again, why should be waste time answering questions that have already been answered???????
    You learn by searching the forum and finding multiple solutions, then you use the solution that is appropriate. There is rarely a single solution for all cases. The more knowledge you have the better decision you can make.
    Have a little pride and learn to do some problem solving on your own without us spoonfeeding every anser to you.
    It is not possible to post a short self documenting program ...Then you truly don't understand what the problem is. And if you don't understand what the problem is how to you expect to communicate that problem verbally so that we understand the problem. You question is not about logic its about sizing of components. How hard is it to create a component and add it to a panel to demonstrate the problem. You don't even need real data. For example you can create a JTable with a single line of code, JTable table = new JTable(5, 10).
    the core of the problem depends on the components added to the JSplitPane...Then demonstrate that with a SSCCE.

  • Resizing JButtons in a BorderLayout

    Hi, I've been working with a BorderLayout and whenever I try and set a JButton's size or preferredSize, it always ignores what I set it at and puts it's size as filling the entire BorderLayout.CENTER. Any ideas?

    {color:#507C9A}1. In future, post Swing questions in the Swing forum: http://forum.java.sun.com/forum.jspa?forumID=57
    2. The behaviour of a Borderlayout is to ignore a component's preferredSize and stretch it to fill the centre.
    Solution: nest.
    JPanel withBorderLayout = ...
    JButton btn = ...
    //withBorderLayout .add(btn, BorderLayout.CENTER);
    JPanel centrePanel = new JPanel(); //FlowLayout by default, you may want to change this
    centrePanel .add(btn);
    withBorderLayout .add(centrePanel , BorderLayout.CENTER);{color}

  • Error CreateImage in for loop array

    Hi,
    I would like to dynamically create images inside a for loop. It dependent on the array_size that the sevlets will send. Snapshots of code:
    for (int i = 0; i < ARRAY_SIZE; i++)
    img[i] = Image.createImage("\"/nike" + (i+1) + ".png\"");
    }Error:
    java.io.IOException
         at javax.microedition.lcdui.ImmutableImage.getImageFromStream(+15)
         at javax.microedition.lcdui.ImmutableImage.<init>(+20)
         at javax.microedition.lcdui.Image.createImage(+8)
         at SlidesCanvas.createImages(+138)
         at SlidesCanvas.<init>(+146)
         at ListSlides.commandAction(+113)
         at javax.microedition.lcdui.Display$DisplayAccessor.commandAction(+282)
         at javax.microedition.lcdui.Display$DisplayManagerImpl.commandAction(+10)
         at com.sun.midp.lcdui.DefaultEventHandler.commandEvent(+68)
         at com.sun.midp.lcdui.AutomatedEventHandler.commandEvent(+47)
         at com.sun.midp.lcdui.DefaultEventHandler$QueuedEventHandler.run(+250)
    Is this a known bug in CreateImage? Or am i doing it in a wrong way?

    Herlena
    I tried this, it works.
    for (int i = 0; i < ARRAY_SIZE; i++) {
        img[i] = img.createImage("nike" + (i+1) + ".png");
    Hope your problem is solved, Darryl

Maybe you are looking for

  • How can I do the CNiReal64Vector as a global variable?

    My problem is with the CNiReal64Vector. Ive tried to define this vector as a global variable in the header file: public: NI::CNiReal64Vector plotData(50); but the debuger flushed error : Syntax error ´constant´. Of course,  I used usually square brac

  • All of a Sudden, lots of corrupted files

    I've never had this issue with lightroom 5.  All of a sudden, I'm getting corrupted files, some of them disappear , and some seem to be corrupted AFTER I've already processed it.  Very odd.  I use a Nikon D7100 with Delkin Devices 64gb SD 633x.  I ju

  • Special ledger document number

    Hi, I want that special ledger document number is the same Financial document number, is this posible ?. Best Regards, Ivonne

  • Can we install Dev and QA in Single Server

    hi Now we r going to sizing the BW System. we getting data only fro HR,FI,CO and MM Can we installed the BW Dev and QA in one server Do we need have seperate serversfor each of them Total concurrent of users would be 25 Can anyone help me out Thanks

  • Premiere Pro CS5 Crashes on Startup on Mac

    Hi, I have installed Master Collection CS5 on a MacBook Pro (late 2009) Mac OSX 10.6..4 (4GB RAM) with all Apple updates applied as at 26.8.2010  , Photoshop & Illustrator work fine , Premiere Pro & Soundbooth CS5 repeatedly crash when starting up &