How to get BufferedImage of a JPanel

Can anyone tell me : how to get BufferedImage of a JPanel

I've done something like this:
import java.awt.Graphics;
import java.awt.LayoutManager;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.io.FileInputStream;
import javax.swing.JPanel;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageDecoder;
* @author Martin Breton
public class JBackgroundImagePanel extends JPanel {
     private BufferedImage mImage = null;
     private InputStream mImageStream = null;
     public  String mImageFilename = null;
     public JBackgroundImagePanel( String ImageFilename ) {
          super();
          mImageFilename = ImageFilename;
          initialize();
     public JBackgroundImagePanel( BufferedImage ImageFilename ) {
          super();
          mImage = ImageFilename;
          initialize();
     public JBackgroundImagePanel( InputStream ImageStream ) {
          super();
          mImageStream= ImageStream;
          initialize();
     private  void initialize() {
          if(mImage == null)
               try {
                    ClassLoader Loader = this.getClass().getClassLoader();
                    if( mImageStream == null )
                         mImageStream = Loader.getResourceAsStream(mImageFilename);
                         if( mImageStream == null )
                             mImageStream = new FileInputStream( mImageFilename );     
                    JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder( mImageStream );
                    mImage = decoder.decodeAsBufferedImage();
                    mImageStream.close();
               catch(Exception e){
                    System.out.print("Image could not be loaded in JBackgroundImagePanel.");
          this.setSize(mImage.getWidth(),mImage.getHeight());
     public void paintComponent(Graphics g) {
          super.paintComponent(g);
          g.drawImage(mImage, 0, 0, null);
}Hope this helps.
proxi

Similar Messages

  • How to get BufferedImage to treat zero in the same way as MemoryImageSource

    Hi!
    I was wondering if there is a way for BufferedImage to treat the value zero, i.e. 0, the same way as MemoryImageSource. After some testing I have found out that if the integer array that is used by MemoryImageSource contains a zero pixel value, it is treated as no value and the given background color to drawImage is used. When using BufferedImage, with type TYPE_INT_RGB, the zero value is treated as black.
    The problem is that I need to replace my MemoryImageSource instance with a BufferedImage to handle dynamic update better and I do not want to redesign the whole pixel array. Is there a way to get BufferedImage to treat 0 value pixels the same way as MemoryImageSource, i.e. treat them as no value and use the background color.
    Would really appreciate some help!
    Best regards
    Lars

    Have you tried using an ARGB image type instead of RGB? Then you can set the alpha of pixels you want to be transparent to zero.

  • How to Get object that a JPanel belongs to.

    I created an object that has a JPanel. When that JPanel is clicked, how can I get the object to which its a GUI data member of?

    Hi,
    If you try JPanel.getParent() it will return the Container that it is in.
    If what you want is the creator you can derive from JPanel and add a constructor that has the creator as its only parm.
      JPanel panel = new JPanel(this);
    public class MyPanel extends JPanel {
      Object myCreator;
      public JPanel(Object creator) {
         super();
         myCreator = creator;
    }Now you can use myCreator to access that class that created it.
    Paul

  • HELP: How to get window (JFrame) from JPanel ???

    Hi there,
    anyone knows how I can get a ref. to the window (in the form of JFrame) from my JPanel that is in the actual window??
    I need that window when I display a modal dialog from the panel, as the dialog constructor takes the window as a param.
    I could always pass a window-ref. to the JPanel when I create it, but as I have a lot of panels, I'd rather be able to get it just when I need it from the JPanel!
    Thanks a lot for any help on this issue!
    Best regards,
    AC

    Thanks a lot!
    I'll use windowForComponent in swingUtils, I think getRootPane() would only return the panel that the component is in!
    Regards,
    AC

  • How to get the height of JPanel?

    Hi.
    I am new to GUI programming.
    I am trying to get the height of a JPanel which I put inside a JFrame but the getHeight() method returns me zero.
    My code are as follows:
    public class Form2
    public static void main(String[] args)
    JFrame f = new JFrame();
    JPanel p = new JPanel();
    f.setTitle("Testing...");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setSize(400, 300);
    f.setVisible(true);
    f.add(p);
    System.out.println(f.getHeight());
    System.out.println(p.getHeight());
    Can somebody enlighten me on how to obtain the height of the JPanel?
    Thanks in advance.

    Swing related questions should be posted in the Swing forum.
    I am trying to get the height of a JPanelComponents don't have a size until the JFrame is made visible and all the components are layed out by the LayoutManager. You can use a WindowListener to tell when a frame is shown.

  • How to get a string or byte array representation of an Image/BufferedImage?

    I have a java.awt.Image object that I want to transfer to a server application (.NET) through a http post request.
    To do that I would like to encode the Image to jpeg format and convert it to a string or byte array to be able to send it in a way that the receiver application (.NET) could handle. So, I've tried to do like this.
    private void send(Image image) {
        int width = image.getWidth(null);
        int height = image.getHeight(null);
        try {
            BufferedImage buffImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            ImageIcon imageIcon = new ImageIcon(image);
            ImageObserver observer = imageIcon.getImageObserver();
            buffImage.getGraphics().setColor(new Color(255, 255, 255));
            buffImage.getGraphics().fillRect(0, 0, width, height);
            buffImage.getGraphics().drawImage(imageIcon.getImage(), 0, 0, observer);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(stream);
            jpeg.encode(buffImage);
            URL url = new URL(/* my url... */);
            URLConnection connection = url.openConnection();
            String boundary = "--------" + Long.toHexString(System.currentTimeMillis());
            connection.setRequestProperty("method", "POST");
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            String output = "--" + boundary + "\r\n"
                          + "Content-Disposition: form-data; name=\"myImage\"; filename=\"myFilename.jpg\"\r\n"
                          + "Content-Type: image/jpeg\r\n"
                          + "Content-Transfer-Encoding: base64\r\n\r\n"
                          + new String(stream.toByteArray())
                          + "\r\n--" + boundary + "--\r\n";
            connection.setDoOutput(true);
            connection.getOutputStream().write(output.getBytes());
            connection.connect();
        } catch {
    }This code works, but the image I get when I save it from the receiver application is distorted. The width and height is correct, but the content and colors are really weird. I tried to set different image types (first line inside the try-block), and this gave me different distorsions, but no image type gave me the correct image.
    Maybe I should say that I can display the original Image object on screen correctly.
    I also realized that the Image object is an instance of BufferedImage, so I thought I could skip the first six lines inside the try-block, but that doesn't help. This way I don't have to set the image type in the constructor, but the result still is color distorted.
    Any ideas on how to get from an Image/BufferedImage to a string or byte array representation of the image in jpeg format?

    Here you go:
      private static void send(BufferedImage image) throws Exception
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpeg", byteArrayOutputStream);
        byte[] imageByteArray = byteArrayOutputStream.toByteArray();
        URL url = new URL("http://<host>:<port>");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(imageByteArray, 0, imageByteArray.length);
        outputStream.close();
        connection.connect();
        // alternative to connect is to get & close the input stream
        // connection.getInputStream().close();
      }

  • How  we get the component at front or back in a Jpanel

    How we get the component at front or back in a Jpanel. I want to manage the Z-axis position of the components in the Jpanel.

    [url http://java.sun.com/docs/books/tutorial/uiswing/components/layeredpane.html]How to Use Layered Panes

  • How can get a Graphics to draw line on screen?

    How can get a Graphics to draw line on screen?
    Now, I can get a Graphics to draw line based on component. For example JPanel, but I want to get a Graphics to draw line on screen.

    By drawing on the screen, I assume you mean drawing outside the bounds of a top-level window like
    JFrame or JDialog. You can't do that. At least, without going native and even then that's a dodgey thing
    for any platform to let you do. One thing you can do is simulate it with a robot's screen capture:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class X {
        public static void main(String[] args) throws Exception {
            Rectangle bounds = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
            BufferedImage image = new Robot().createScreenCapture(bounds);
            Graphics2D g2 = image.createGraphics();
            g2.setStroke(new BasicStroke(20));
            g2.setPaint(Color.RED);
            g2.drawLine(0, 0, bounds.width, bounds.height);
            g2.drawLine(bounds.width, 0, 0, bounds.height);
            g2.dispose();
            JLabel label = new JLabel(new ImageIcon(image));
            label.addMouseListener(new MouseAdapter(){
                public void mousePressed(MouseEvent evt) {
                    System.exit(0);
            JFrame f = new JFrame();
            f.setUndecorated(true);
            f.getContentPane().add(label);
            f.setBounds(bounds);
            f.setVisible(true);
    }

  • How to get the full path instead of just the file name, in �FileChooser� ?

    In the FileChooserDemo example :
    In the statement : log.append("Saving: " + file.getName() + "." + newline);
    �file.getName()� returns the �file name�.
    My question is : How to get the full path instead of just the file name,
    e.g. C:/xdirectory/ydirectory/abc.gif instead of just abc.gif
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    public class FileChooserDemo extends JFrame {
    static private final String newline = "\n";
    public FileChooserDemo() {
    super("FileChooserDemo");
    //Create the log first, because the action listeners
    //need to refer to it.
    final JTextArea log = new JTextArea(5,20);
    log.setMargin(new Insets(5,5,5,5));
    log.setEditable(false);
    JScrollPane logScrollPane = new JScrollPane(log);
    //Create a file chooser
    final JFileChooser fc = new JFileChooser();
    //Create the open button
    ImageIcon openIcon = new ImageIcon("images/open.gif");
    JButton openButton = new JButton("Open a File...", openIcon);
    openButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    int returnVal = fc.showOpenDialog(FileChooserDemo.this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
    File file = fc.getSelectedFile();
    //this is where a real application would open the file.
    log.append("Opening: " + file.getName() + "." + newline);
    } else {
    log.append("Open command cancelled by user." + newline);
    //Create the save button
    ImageIcon saveIcon = new ImageIcon("images/save.gif");
    JButton saveButton = new JButton("Save a File...", saveIcon);
    saveButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    int returnVal = fc.showSaveDialog(FileChooserDemo.this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
    File file = fc.getSelectedFile();
    //this is where a real application would save the file.
    log.append("Saving: " + file.getName() + "." + newline);
    } else {
    log.append("Save command cancelled by user." + newline);
    //For layout purposes, put the buttons in a separate panel
    JPanel buttonPanel = new JPanel();
    buttonPanel.add(openButton);
    buttonPanel.add(saveButton);
    //Explicitly set the focus sequence.
    openButton.setNextFocusableComponent(saveButton);
    saveButton.setNextFocusableComponent(openButton);
    //Add the buttons and the log to the frame
    Container contentPane = getContentPane();
    contentPane.add(buttonPanel, BorderLayout.NORTH);
    contentPane.add(logScrollPane, BorderLayout.CENTER);
    public static void main(String[] args) {
    JFrame frame = new FileChooserDemo();
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    frame.pack();
    frame.setVisible(true);

    simply use file.getPath()
    That should do it!Thank you !
    It takes care of the problem !!

  • How to get the path when i select a directory or a file in a JTree

    How to get the path when i select a directory or a file in a JTree

    import java.lang.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.HeadlessException;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Iterator;
    * @author Frederic FOURGEOT
    * @version 1.0
    public class JTreeFolder extends JPanel {
    protected DefaultMutableTreeNode racine;
    JTree tree;
    protected JScrollPane scrollpane;
    final static int MAX_LEVEL = 1; // niveau max de descente "direct" dans l'arborescence
    * Sous-classe FSNode
    * @author Frederic FOURGEOT
    * @version 1.0
    private class FSNode extends DefaultMutableTreeNode {
    File file; // contient le fichier li� au noeud
    * Constructeur non visible
    private FSNode() {
    super();
    * Constructeur par initialisation
    * @param userObject Object
    FSNode(Object userObject) {
    super(userObject);
    * Constructeur par initialisation
    * @param userObject Object
    * @param newFile File
    FSNode(Object userObject, File newFile) {
    super(userObject);
    file = newFile;
    * Definit le fichier lie au noeud
    * @param newFile File
    public void setFile(File newFile) {
    file = newFile;
    * Renvoi le fichier lie au noeud
    * @return File
    public File getFile() {
    return file;
    public JTree getJTree(){
         return tree ;
    * Constructeur
    * @throws HeadlessException
    public JTreeFolder() throws HeadlessException {
    File[] drive;
    tree = new JTree();
    // cr�ation du noeud sup�rieur
    racine = new DefaultMutableTreeNode("Poste de travail");
    // cr�ation d'un noeud pour chaque lecteur
    drive = File.listRoots();
    for (int i = 0 ; i < drive.length ; i++) {
    FSNode node = new FSNode(drive, drive[i]);
    addFolder(drive[i], node); // on descend dans l'arborescence du lecteur jusqu'� MAX_LEVEL
    racine.add(node);
    // Gestion d'evenement sur JTree (on �coute les evenements TreeExpansion)
    tree.addTreeExpansionListener(new TreeExpansionListener() {
    public void treeExpanded(TreeExpansionEvent e) {
    // lorsqu'un noeud est ouvert
    // on descend dans l'arborescence du noeud jusqu'� MAX_LEVEL
    TreePath path = e.getPath();
    FSNode node = (FSNode)path.getLastPathComponent();
    addFolder(node);
    ((DefaultTreeModel)tree.getModel()).reload(node); // on recharche uniquement le noeud
    public void treeCollapsed(TreeExpansionEvent e) {
    // lorsqu'un noeud est referm�
    //RIEN
    // alimentation du JTree
    DefaultTreeModel model = new DefaultTreeModel(racine);
    tree.setModel(model);
         setLayout(null);
    // ajout du JTree au formulaire
    tree.setBounds(0, 0, 240, 290);
    scrollpane = new JScrollPane(tree);
         add(scrollpane);
         scrollpane.setBounds(0, 0, 240, 290);
    * Recuperation des sous-elements d'un repertoire
    * @param driveOrDir
    * @param node
    public void addFolder(File driveOrDir, DefaultMutableTreeNode node) {
    setCursor(new Cursor(3)); // WAIT_CURSOR est DEPRECATED
    addFolder(driveOrDir, node, 0);
    setCursor(new Cursor(0)); // DEFAULT_CURSOR est DEPRECATED
    * Recuperation des sous-elements d'un repertoire
    * (avec niveau pour r�cursivit� et arr�t sur MAX_LEVEL)
    * @param driveOrDir File
    * @param node DefaultMutableTreeNode
    * @param level int
    private void addFolder(File driveOrDir, DefaultMutableTreeNode node, int level) {
    File[] fileList;
    fileList = driveOrDir.listFiles();
    if (fileList != null) {
    sortFiles(fileList); // on tri les elements
    // on ne cherche pas plus loin que le niveau maximal d�finit
    if (level > MAX_LEVEL - 1) {return;}
    // pour chaque �l�ment
    try {
    for (int i = 0; i < fileList.length; i++) {
    // en fonction du type d'�l�ment
    if (fileList[i].isDirectory()) {
    // si c'est un r�pertoire on cr�� un nouveau noeud
    FSNode dir = new FSNode(fileList[i].getName(), fileList[i]);
    node.add(dir);
    // on recherche les �l�ments (r�cursivit�)
    addFolder(fileList[i], dir, ++level);
    if (fileList[i].isFile()) {
    // si c'est un fichier on ajoute l'�l�ment au noeud
    node.add(new FSNode(fileList[i].getName(), fileList[i]));
    catch (NullPointerException e) {
    // rien
    * Recuperation des sous-elements d'un noeud
    * @param node
    public void addFolder(FSNode node) {
    setCursor(new Cursor(3)); // WAIT_CURSOR est DEPRECATED
    for (int i = 0 ; i < node.getChildCount() ; i++) {
    addFolder(((FSNode)node.getChildAt(i)).getFile(), (FSNode)node.getChildAt(i));
    setCursor(new Cursor(0)); // DEFAULT_CURSOR est DEPRECATED
    * Tri une liste de fichier
    * @param listFile
    public void sortFiles(File[] listFile) {
    triRapide(listFile, 0, listFile.length - 1);
    * QuickSort : Partition
    * @param listFile
    * @param deb
    * @param fin
    * @return
    private int partition(File[] listFile, int deb, int fin) {
    int compt = deb;
    File pivot = listFile[deb];
    int i = deb - 1;
    int j = fin + 1;
    while (true) {
    do {
    j--;
    } while (listFile[j].getName().compareToIgnoreCase(pivot.getName()) > 0);
    do {
    i++;
    } while (listFile[i].getName().compareToIgnoreCase(pivot.getName()) < 0);
    if (i < j) {
    echanger(listFile, i, j);
    } else {
    return j;
    * Tri rapide : quick sort
    * @param listFile
    * @param deb
    * @param fin
    private void triRapide(File[] listFile, int deb, int fin) {
    if (deb < fin) {
    int positionPivot = partition(listFile, deb, fin);
    triRapide(listFile, deb, positionPivot);
    triRapide(listFile, positionPivot + 1, fin);
    * QuickSort : echanger
    * @param listFile
    * @param posa
    * @param posb
    private void echanger(File[] listFile, int posa, int posb) {
    File tmpFile = listFile[posa];
    listFile[posa] = listFile[posb];
    listFile[posb] = tmpFile;

  • How to get coordinates of components. PLEASE HELP ME URGENT!

    Hi, I am trying to get the coordinates of my components that are tabbed pane buttons, buttons, text fields etc so I can place an image of a pointer under it that points to it and then under the image of the pointer I would put a label describing the button for example "press the tab to start". Then when I press tab1 the image of pointer image points to the next component and has a label under pointer.
    Now I have tried using componenet.getX() and getY() and then set the values of the the image panel to use then the label panel so they be placed under the component, these panels are not using layout manager but absolute positioning. If the window is resized then the labels and image of pointer should also adjust. I have tried putting the label and arrow into a glasspane and now layerdpane as some people here suggested which when I do then add it to contentpane the main panel with the components is not there but the layerd pane is.
    I am having huge difficulties with this and if someone can Please just tell me or even better give me an example code how to find out the coordinates of components so I can place my image of pointers and labels underneath them I will be very grateful of you. I am on a verge of giving up accomplish what I am doing and I am new to the swing framework. My progress to solve this has been very slow and frustrating. I just hope someone here can help.

    I tried the both of codes given. But the code given by both the person i have not understand. And what they there code is doing. This is the code form my side if this example help u.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    * Author Waheed-Ul-Haq ( BS(CS)-8 )
    public class Samulation2
         JPanel pane;
         JLabel label1;
         JTextField entProcesfld;
         JButton buttCreat;
         JButton buttReslt;
         JLabel usrProcesID[];
         JTextField usrArivTam[];
         int processes;
         public JComponent createComponents()
         pane = new JPanel();
         pane.setLayout (null);     
         label1 = new JLabel();     //Label for to tell user to enter no of Processes.
         label1.setText("Enter the no. of Processes");
         pane.add(label1);
         label1.setBounds(20, 25, 150, label1.getPreferredSize().height);
         entProcesfld = new JTextField();     //TextField to enter no of processes.
         entProcesfld.setToolTipText("Enter the no of Processes.");
         pane.add(entProcesfld);
         entProcesfld.setBounds(180, 25, 100, entProcesfld.getPreferredSize().height);
         buttCreat = new JButton();          //Button to create the TextFields.
         buttCreat.setText("Create TextFields");
         pane.add(buttCreat);               //Adding cutton to Jpane.
         buttCreat.setBounds(new Rectangle(new Point(30, 60), buttCreat.getPreferredSize()));
         buttCreat.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        buttCreatActionPerformed(e);
                   } } );          //ActionListenr to Create the TextFields.
         pane.setPreferredSize(new Dimension(600,600));
         return pane;
         }     //-------END of Component createComponents()--------//
         private void buttCreatActionPerformed(ActionEvent e)     //Action to Create the TextFields.
                   processes = Integer.parseInt (entProcesfld.getText ());
                   JLabel Labproces = new JLabel();     //Label of Processes.
                   Labproces.setText("Processes");
                   pane.add(Labproces);
                   Labproces.setBounds(new Rectangle(new Point(15, 105), Labproces.getPreferredSize()));
                   JLabel labArivTam = new JLabel();     //Label of Arival time.
                   labArivTam.setText("Arrial Time");
                   pane.add(labArivTam);
                   labArivTam.setBounds(new Rectangle(new Point(90, 105), labArivTam.getPreferredSize()));
                   //----Creating Dynamic JLabels------//
                   usrProcesID  = new JLabel[processes];     /* Makes an array */
                   int yXis = 125;          //Variable for Y-axix of JLabel.
                   for(int i=0; i<processes; i++)      /* i takes each value from 0 to processes-1 */
                    usrProcesID[i] = new JLabel("P" + i);      /* Makes a JLabel at an array place */
                    pane.add(usrProcesID);      /* Adds a JLabel (rather than an array) */
    usrProcesID[i].setBounds(new Rectangle(new Point(28, yXis), usrProcesID[i].getPreferredSize()));
    yXis = yXis + 25;     /* Increses the Y-axis to show JLabels. */
    }     //EndFor     
    //-------End Dynamic JLabels---------//               
                   //-----Creating Dynamic Arival Time TextFields-----//
                   usrArivTam = new JTextField[processes];          /* Makes an array */
                   yXis = 125;          //Variable for Y-axix of JTextField.
                   for(int i=0; i<processes; i++)      /* i takes each value from 0 to processes-1 */
    usrArivTam[i] = new JTextField();     /* Makes a JTextField at an array place */
    usrArivTam[i].setToolTipText("Enter Arival Time.");
    pane.add(usrArivTam[i]);      /* Adds a JTestField (rather than an array) */
    usrArivTam[i].setBounds(100, yXis, 35, usrArivTam[i].getPreferredSize().height);
    yXis = yXis + 25;     /* Increses the Y-axis to show JTextFields. */
    }     //EndFor     
    //-----End Dynamic Arival Time TextFields.-----//
    //----Calculating points for Label and textfields.
    Point poi = new Point();
    poi = usrArivTam[processes-1].getLocation ();     //Getting the location of the last text field of ArivalTime.
    //-----Label for Average Waiting time.--------\\
    JLabel averWaitLB = new JLabel();
    averWaitLB.setText("Average Waiting Time");
              pane.add(averWaitLB);
              averWaitLB.setBounds(new Rectangle(new Point(30, (int)poi.getY()+50), averWaitLB.getPreferredSize()));
    //-----TextField for Average Waiting Time.--------\\
    JTextField averWaitTF = new JTextField();
    averWaitTF.setText ("Hello");
    averWaitTF.setEditable(false);
    pane.add (averWaitTF);
    averWaitTF.setBounds(190, (int)poi.getY()+50, 35, averWaitTF.getPreferredSize().height);
    }     //------END of void buttResltActionPerformed(ActionEvent e)---------//
         private static void createAndShowGUI()
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("Priority Scheduling (Non-Preemptive)....");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Samulation2 application = new Samulation2();
    //Create and set up the content pane.
    JComponent components = application.createComponents ();
    components.setOpaque (true);
    int vertSB = ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
              int horzSB = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
              JScrollPane scrollPane = new JScrollPane(components, vertSB, horzSB);
    scrollPane.setPreferredSize (new Dimension(720,455));
    frame.getContentPane ().add (scrollPane,null);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    }     //------END Of void createAndShowGUI()--------//
         public static void main(String[] args)
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
         }     //---------End of main()----------------//
    }     //--------END of class Samulation2----------//
    If any body help me implementing the ScrollBars in this code. I am unable to use Scroll Bars with this code while using NULL layout. If any body tell me how to get the Size and set for the pane.

  • How to get format from textpane?

    iam changing the color and inserting image in jtextpane after i have to send a mail.
    how to get that formatted data and send to mail plz help in this case.
    change the code and send it. plz...............
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.JTabbedPane.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import javax.swing.text.rtf.*;
    import java.util.*;
    import javax.mail.*;
    import javax.mail.internet.*;
    import javax.activation.*;
    public class loginform extends JFrame {
         JTabbedPane jtp = new JTabbedPane();
         public loginform() {
              Container c = getContentPane();
              JTabbedPane jtp = new JTabbedPane();
              jtp.addTab("COMPOSEMAIL", new ComposeMailPanel());
              c.add(jtp);
              c.validate();
         }//method
         public static void main(String a[]) throws Exception {
              loginform s = new loginform();
              s.setSize(800, 800);
              s.setVisible(true);
         }//main
    }//mainclass
    class ComposeMailPanel extends JPanel implements ActionListener {
         JTextField BCC;
         int start;
         int end;
         JLabel JLabel1;
         JLabel JLabel2;
         JLabel JLabel3;
         JLabel JLabel4;
         JFrame mainFrame = new JFrame();
         JTextField from;
         JTextField subject;
         JButton Send;
         String mailsentaddress = "";
         JButton bInsertPic = new JButton("P");
         JButton bForegroundColor = new JButton("F");
         JFileChooser insertIconFile = new JFileChooser();
         JColorChooser backgroundChooser = new JColorChooser();
         JColorChooser foregroundChooser = new JColorChooser();
         Color foregroundColor;
         JTextPane mainTextPane = new JTextPane();
         SimpleAttributeSet sas = new SimpleAttributeSet();
         MutableAttributeSet sas1 = new SimpleAttributeSet();
         StyleContext sc = new StyleContext();
         MutableAttributeSet mas;
         DefaultStyledDocument dse = new DefaultStyledDocument(sc);
         JScrollPane mainScrollPane = new JScrollPane(mainTextPane, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
         RTFEditorKit rtfkit = new RTFEditorKit();
         Dimension Size1 = new Dimension();
         public ComposeMailPanel() {
              setLayout(null);
              mainTextPane.setBounds(150, 325, 572, 150);
              mainTextPane.setContentType("text/html");
              mainTextPane.setEditorKit(rtfkit);
              mainTextPane.setDocument(dse);
              mainScrollPane.setBounds(150, 325, 572, 155);
              bInsertPic.setBounds(150, 300, 20, 20);
              bForegroundColor.setBounds(171, 300, 20, 20);
              add(mainScrollPane);
              add(bInsertPic);
              add(bForegroundColor);
              mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              bInsertPic.addActionListener(this);
              bInsertPic.setToolTipText("Insert picture");
              bForegroundColor.addActionListener(this);
              bForegroundColor.setToolTipText("Text color");
              JLabel1 = new JLabel("FROM  :");
              add(JLabel1);
              JLabel1.setBounds(30, 205, 110, 20);
              JLabel2 = new JLabel("BCC :");
              add(JLabel2);
              JLabel2.setBounds(30, 235, 110, 20);
              JLabel3 = new JLabel("SUBJECT :");
              add(JLabel3);
              JLabel3.setBounds(30, 265, 110, 20);
              JLabel4 = new JLabel("MESSAGE :");
              add(JLabel4);
              JLabel4.setBounds(30, 325, 110, 20);
              from = new JTextField();
              add(from);
              from.setBounds(150, 210, 577, 20);
              BCC = new JTextField();
              add(BCC);
              BCC.setBounds(150, 240, 577, 20);
              subject = new JTextField();
              add(subject);
              subject.setBounds(150, 270, 577, 20);
              Send = new JButton("Send");
              add(Send);
              Send.setBounds(720, 495, 65, 20);
              Send.addActionListener(this);
         }// constructor
         public void setAttributeSet(AttributeSet attr) {
              int xStart, xFinish, k;
              xStart = mainTextPane.getSelectionStart();
              xFinish = mainTextPane.getSelectionEnd();
              k = xFinish - xStart;
              if (xStart != xFinish) {
                   dse.setCharacterAttributes(xStart, k, attr, true);
              } else if (xStart == xFinish) {
                   mas = rtfkit.getInputAttributes();
                   mas.addAttributes(attr);
              // The below command line sets the focus to the JTextPane
              mainTextPane.grabFocus();
         public void actionPerformed(ActionEvent ae1) {
              JComponent b = (JComponent) ae1.getSource();
              String str3 = null;
              if (b == bInsertPic) {
                   insertIconFile.setDialogType(JFileChooser.OPEN_DIALOG);
                   insertIconFile.setDialogTitle("Select a picture to insert into document");
                   if (insertIconFile.showDialog(mainFrame, "Insert") != JFileChooser.APPROVE_OPTION) {
                        return;
                   File g = insertIconFile.getSelectedFile();
                   ImageIcon image1 = new ImageIcon(g.toString());
                   mainTextPane.insertIcon(image1);
                   mainTextPane.grabFocus();
              } else if (b == bForegroundColor) {
                   foregroundColor = foregroundChooser.showDialog(mainFrame,"Color Chooser", Color.white);
                   if (foregroundColor != null) {
                        String s1 = mainTextPane.getSelectedText();
                        StyleConstants.setForeground(sas, foregroundColor);
                        setAttributeSet(sas);
              } else if (ae1.getSource() == Send) {
                   String From = "";
                   String To = "";
                   String Subject = "";
                   String Body = "";
                   String Attachment = "";
                   String Hostname = "";
                   From = from.getText();
                   To = BCC.getText();
                   Subject = subject.getText();
                   try {
                        int ki = mainTextPane.getDocument().getLength();
                        Body = mainTextPane.getStyledDocument().getText(0, ki);
                        Hostname = "192.9.200.2";
                        SmtpAttachmentExample example1 = new SmtpAttachmentExample();
                        example1.sendMessage1(Hostname, To, From, Subject, Body);
                        mailsentaddress = BCC.getText();
                   } catch (Exception we1) {
    class SmtpAttachmentExample {
         public void sendMessage1(String hostname, String to, String from,
                   String subject, String body) {
              try {
                   Properties props = System.getProperties();
                   props.put("mail.smtp.host", hostname);
                   Session mailsession = Session.getDefaultInstance(props, null);
                   Message message = new MimeMessage(mailsession);
                   message.setFrom(new InternetAddress(from));
                   message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
                   message.setSubject(subject);
                   message.setSentDate(new Date());
                   MimeBodyPart messageBodyPart = new MimeBodyPart();
                   messageBodyPart.setText(body);
                   Multipart multipart = new MimeMultipart();
                   multipart.addBodyPart(messageBodyPart);
                   message.setContent(multipart);
                   Transport.send(message);
              } catch (Exception ert) {
         }//withoutattachement
    }thanks in advance
    raja

    here it is...simple is'nt it???
    package jwsdp.test;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.util.Properties;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JColorChooser;
    import javax.swing.JComponent;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextField;
    import javax.swing.JTextPane;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.text.AttributeSet;
    import javax.swing.text.DefaultStyledDocument;
    import javax.swing.text.MutableAttributeSet;
    import javax.swing.text.SimpleAttributeSet;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyleContext;
    import javax.swing.text.rtf.RTFEditorKit;
    import javax.mail.*;
    import javax.mail.internet.*;
    import javax.activation.*;
    public class loginform extends JFrame {
         JTabbedPane jtp = new JTabbedPane();
         public loginform() {
              Container c = getContentPane();
              JTabbedPane jtp = new JTabbedPane();
              jtp.addTab("COMPOSEMAIL", new ComposeMailPanel());
              c.add(jtp);
              c.validate();
         }//method
         public static void main(String a[]) throws Exception {
              loginform s = new loginform();
              s.setSize(800, 800);
              s.setVisible(true);
         }//main
    }//mainclass
    class ComposeMailPanel extends JPanel implements ActionListener {
         JTextField BCC;
         int start;
         int end;
         JLabel JLabel1;
         JLabel JLabel2;
         JLabel JLabel3;
         JLabel JLabel4;
         JFrame mainFrame = new JFrame();
         JTextField from;
         JTextField subject;
         JButton Send;
         String mailsentaddress = "";
         JButton bInsertPic = new JButton("P");
         JButton bForegroundColor = new JButton("F");
         JFileChooser insertIconFile = new JFileChooser();
         JColorChooser backgroundChooser = new JColorChooser();
         JColorChooser foregroundChooser = new JColorChooser();
         Color foregroundColor;
         JTextPane mainTextPane = new JTextPane();
         SimpleAttributeSet sas = new SimpleAttributeSet();
         MutableAttributeSet sas1 = new SimpleAttributeSet();
         StyleContext sc = new StyleContext();
         MutableAttributeSet mas;
         DefaultStyledDocument dse = new DefaultStyledDocument(sc);
         JScrollPane mainScrollPane = new JScrollPane(mainTextPane, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
         RTFEditorKit rtfkit = new RTFEditorKit();
         Dimension Size1 = new Dimension();
         public ComposeMailPanel() {
              setLayout(null);
              mainTextPane.setBounds(150, 325, 572, 150);
              mainTextPane.setContentType("text/html");
              mainTextPane.setEditorKit(rtfkit);
              mainTextPane.setDocument(dse);
              mainScrollPane.setBounds(150, 325, 572, 155);
              bInsertPic.setBounds(150, 300, 20, 20);
              bForegroundColor.setBounds(171, 300, 20, 20);
              add(mainScrollPane);
              add(bInsertPic);
              add(bForegroundColor);
              mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              bInsertPic.addActionListener(this);
              bInsertPic.setToolTipText("Insert picture");
              bForegroundColor.addActionListener(this);
              bForegroundColor.setToolTipText("Text color");
              JLabel1 = new JLabel("FROM  :");
              add(JLabel1);
              JLabel1.setBounds(30, 205, 110, 20);
              JLabel2 = new JLabel("BCC :");
              add(JLabel2);
              JLabel2.setBounds(30, 235, 110, 20);
              JLabel3 = new JLabel("SUBJECT :");
              add(JLabel3);
              JLabel3.setBounds(30, 265, 110, 20);
              JLabel4 = new JLabel("MESSAGE :");
              add(JLabel4);
              JLabel4.setBounds(30, 325, 110, 20);
              from = new JTextField();
              add(from);
              from.setBounds(150, 210, 577, 20);
              BCC = new JTextField();
              add(BCC);
              BCC.setBounds(150, 240, 577, 20);
              subject = new JTextField();
              add(subject);
              subject.setBounds(150, 270, 577, 20);
              Send = new JButton("Send");
              add(Send);
              Send.setBounds(720, 495, 65, 20);
              Send.addActionListener(this);
         }// constructor
         public void setAttributeSet(AttributeSet attr) {
              int xStart, xFinish, k;
              xStart = mainTextPane.getSelectionStart();
              xFinish = mainTextPane.getSelectionEnd();
              k = xFinish - xStart;
              if (xStart != xFinish) {
                   dse.setCharacterAttributes(xStart, k, attr, true);
              } else if (xStart == xFinish) {
                   mas = rtfkit.getInputAttributes();
                   mas.addAttributes(attr);
              // The below command line sets the focus to the JTextPane
              mainTextPane.grabFocus();
         public void actionPerformed(ActionEvent ae1) {
              JComponent b = (JComponent) ae1.getSource();
              String str3 = null;
              if (b == bInsertPic) {
                   insertIconFile.setDialogType(JFileChooser.OPEN_DIALOG);
                   insertIconFile.setDialogTitle("Select a picture to insert into document");
                   if (insertIconFile.showDialog(mainFrame, "Insert") != JFileChooser.APPROVE_OPTION) {
                        return;
                   File g = insertIconFile.getSelectedFile();
                   ImageIcon image1 = new ImageIcon(g.toString());
                   mainTextPane.insertIcon(image1);
                   mainTextPane.grabFocus();
              } else if (b == bForegroundColor) {
                   foregroundColor = foregroundChooser.showDialog(mainFrame,"Color Chooser", Color.white);
                   if (foregroundColor != null) {
                        String s1 = mainTextPane.getSelectedText();
                        StyleConstants.setForeground(sas, foregroundColor);
                        setAttributeSet(sas);
              } else if (ae1.getSource() == Send) {
                   String From = "";
                   String To = "";
                   String Subject = "";
                   String Body = "";
                   String Attachment = "";
                   String Hostname = "";
                   From = from.getText();
                   To = BCC.getText();
                   Subject = subject.getText();
                   try {
                        int ki = mainTextPane.getDocument().getLength();
                        ByteArrayOutputStream l_out = new ByteArrayOutputStream();                  // added by Guilllaume
                        mainTextPane.getEditorKit().write(l_out,mainTextPane.getDocument(),0,ki);   // added by Guilllaume
                        Body = new String(l_out.toByteArray());                                     // added by Guilllaume
                    //     Body = mainTextPane.getStyledDocument().getText(0, ki); // supress by Guilllaume
                        Hostname = "192.9.200.2";
                        SmtpAttachmentExample example1 = new SmtpAttachmentExample();
                        example1.sendMessage1(Hostname, To, From, Subject, Body);
                        mailsentaddress = BCC.getText();
                   } catch (Exception we1) {
    class SmtpAttachmentExample {
         public void sendMessage1(String hostname, String to, String from,
                   String subject, String body) {
              try {
                   Properties props = System.getProperties();
                   props.put("mail.smtp.host", hostname);
                   Session mailsession = Session.getDefaultInstance(props, null);
                   Message message = new MimeMessage(mailsession);
                   message.setFrom(new InternetAddress(from));
                   message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
                   message.setSubject(subject);
                   message.setSentDate(new Date());
                   MimeBodyPart messageBodyPart = new MimeBodyPart();
                   messageBodyPart.setText(body);
                   Multipart multipart = new MimeMultipart();
                   multipart.addBodyPart(messageBodyPart);
                   message.setContent(multipart);
                   Transport.send(message);
              } catch (Exception ert) {
         }//withoutattachement
    }

  • Video Structure..How to get Frame i? help...

    standard video coding made by a Group of Picture(GOP), GOP it self made by few kind of frame/picture.
    Frame i, Frame p, Frame B, dan Frame D. Frame i is a frame that decode without any reference to another picture, this is the first frame in GOP.All i have is a theory, do anyone know how to get Frame i in JMF?

    Ok.
    I think you have a JFrame and
    a JPanel added to JFrame,
    And this JPanel contains JButton, Am I right?
    Then
    Container parent = button.getParent(); //this will be the JPanel
    Container grandParent = parent.getParent(); //this will be your JFrame
    BR

  • How to get the values from table SKB1 R/3  to SRM

    Hi Gurus,
    My requirement is to get all the values from the table SKB1 to SRM (i.e. in to an internal table) for doing some validation(G/L account XXXXXX requires an assignment to a CO objectXXXXXX.)
    Like wise I have many tables for doing validation in SRM
    Help me how to get this, suggest me any Function module with sample code.
    OR
    Any Standard FM which will give all the values of the fields in the table SKB1 when I pass the key fields G/L account & company code alone so that I can improve the performance.
    Suggest me.
    Regards
    Paul

    Hi,
    You can use the FM 's META_READ_TABLE Or RFC_READ_TABLE
    Which SRM / Backend system version are you using ?
    Are you taking care of the Importing paramater - DELIMITER in this case.. ??*
    See related links ->
    Re: Retrieving data from R/3 into SRM
    Re: Product Search TIME lag
    Else you can just call the remote enabled  FM "BAPI_GL_ACC_GETDETAIL"  from SRM.
    BR,
    Disha.
    Do reward points for useufl answers.

  • How to get the values from popup window to mainwindow

    HI all,
       I want to get the details from popup window.
          i have three input fields and one search button in my main window. when i click search button it should display popup window.whenever i click on selected row of the popup window table ,values should be visible in my main window input fields.(normal tables)
       now i am able to display popup window with values.How to get the values from popup window now.
       I can anybody explain me clearly.
    Thanks&Regards
    kranthi

    Hi Kranthi,
    Every webdynpro component has a global controller called the component controller which is visible to all other controllers within the component.So whenever you want to share some data in between 2 different views you can just make it a point to use the component controller's context for the same. For your requirement (within your popups view context) you will have have to copy the component controllers context to your view. You then will have to (programmatically) fill this context with your desired data in this popup view. You can then be able to read this context from whichever view you want. I hope that this would have made it clear for you. Am also giving you an [example|http://****************/Tutorials/WebDynproABAP/Modalbox/page1.htm] which you can go through which would give you a perfect understanding of all this. In this example the user has an input field in the main view. The user enters a customer number & presses on a pushbutton. The corresponding sales orders are then displayed in a popup window for the user. The user can then select any sales order & press on a button in the popup. These values would then get copied to the table in the main view.
    Regards,
    Uday

Maybe you are looking for