Adding scrollbars to a panel containing a buffered image

Frame Class:
package HeatMap;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridBagLayout;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
class HeatMapFrame extends JFrame
     BufferedImage img;
     HeatMapFrame(BufferedImage img)
          super("Gene Expression Profile Heatmap");
          this.img = img;
          HeatMapPane mapPanel = new HeatMapPane(img);
          JScrollPane scrollPane = new JScrollPane(mapPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,   
                                          ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS );   
          scrollPane.setPreferredSize(new Dimension(640,480));
          add(scrollPane,BorderLayout.CENTER);
          setSize(640,480);
          setLocation(getWidth()/4,getHeight()/4);
          setDefaultCloseOperation(EXIT_ON_CLOSE);
          setVisible(true);
Panel Class:
package HeatMap;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
public class HeatMapPane extends JPanel
     BufferedImage img;
     HeatMapPane(BufferedImage img)
          this.img = img;
          //setSize(640,480);
     protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        // Draw image centered.
        //int x = (getWidth() - img.getWidth())/2;
        //int y = (getHeight() - img.getHeight())/2;
        g.drawImage(img, 0, 0, this);
}I`m drawing the BufferedImage to a JPanel and addig the JPanel to a JScrollPane. The problem is that the scrollbars are visible but not active. Scrolling is not working. Can somebody tell me why? Thanks for any advice.

Since your HeatMapPane does not declare a preferred size, I'm guessing(1) it is assigned a size of 0x0.
1) I would do more than guess, if you had posted an SSCCE. For an SSCCE to do with images, you might hot-link to some of the images available at my [media page|http://pscode.org/media/#image], or generate an image within the source.

Similar Messages

  • Problem with scrolling a panel containing an image

    I am having a problem adding scrolling capabilities to a tabbed panel containing pages containing an image. In my program, I have a class called ImagePanel that extends JPanel and contains an image read from a file. In another class, I create a tabbed panel and add to it ImagePanels.
    The problem I'm facing is that the pages added to my tabbed panel contain scroll bars, but these scroll bars are not scrollable (i.e. I cannot use the bars the scroll and see the missing parts of the image).
    Any help on this manner is highly appreciated.
    The code is shown below:
    JTabbedPane m_pathwayTabbedPane = new JTabbedPane();
    ImageIcon overviewImageIcon = IconLoader.readImageIcon(pathway.gif);
    ImagePanel overviewPanel = new ImagePanel(overviewImageIcon.getImage());
    JScrollPane graphcrollPane = new JScrollPane(overviewPanel,
    ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
    ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
    m_pathwayTabbedPane.addTab(StringManager.OVERVIEW, graphcrollPane);

    import java.awt.*;
    import java.io.*;
    import java.net.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class ScrollingImages
        public static void main(String[] args)
            String[] fileNames = {
                "images/bclynx.jpg", "images/mtngoat.jpg", "images/redfox.jpg"
            JPanel panel = new JPanel(new GridBagLayout());
            panel.setBackground(Color.black);
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(5,5,5,5);
            gbc.gridwidth = gbc.REMAINDER;
            for(int j = 0; j < fileNames.length; j++)
                panel.add(new ImageComponent(fileNames[j]), gbc);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JScrollPane(panel));
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    class ImageComponent extends JPanel
        Image image;
        public ImageComponent(String fileName)
            loadImage(fileName);
            setBackground(Color.black);
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            int w = getWidth();
            int h = getHeight();
            int imageWidth = image.getWidth(this);
            int imageHeight = image.getHeight(this);
            int x = (w - imageWidth)/2;
            int y = (h - imageHeight)/2;
            g.drawImage(image, x, y, this);
         * For the JScrollPane which will inquire about our size
         * which it needs to properly set its scrollbars.
        public Dimension getPreferredSize()
            return new Dimension(image.getWidth(this), image.getHeight(this));
        private void loadImage(String fileName)
            try
                URL url = getClass().getResource(fileName);
                image = ImageIO.read(url);
            catch(MalformedURLException mue)
                System.out.println(mue.getMessage());
            catch(IOException ioe)
                System.out.println(ioe.getMessage());
    }

  • Adding a scrollbar to a panel

    this seems like it should be a no brainer.  I am dynamically adding elements to a panel, and sometimes there is too much stuff and the size of the window gets enormous.  I would like a fixed windoe size, and if the elements in the panel spill over the edge, give me a scrollbar to see those items that arent visible.
    this is not the first time I have set out to solve this problem...is there really no way to have a scrolling panel?  the javascript tools guide speaks of a scrollbar element, but it is not documented very well and does not appear to do much of anything.
    Mike Cardeiro

    Continued here:
    http://forum.java.sun.com/thread.jspa?threadID=5146140
    OP, don't you think one thread's enough?

  • Adding a window to a container: Error

    Hello there,
    Im facing a problem with my program.My program is about a Car Rental System and I am using GUI for the interface. From the main(CarRental) program,when user click one of the menu, there is another interface will appear for user to enter details.The problem is,my main (CarRental)program is running,click the first menu,then another interface open,but wen user enter details n click buttons , it is not even working. Below is my program:
    //This is main menu program
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    import javax.swing.JFrame;
    public class CarRental extends JFrame implements ActionListener{
         JFrame f;
         JLabel l1,l2,l3,choice;
         JPanel p1,p2,p3,p4,p5,p6,p7,p8,p9;
         JButton btnA,btnB,btnC,btnD,btnE,btnF;
         Connection conn;
         Statement stmt;
         ResultSet rs;
         public CarRental(){
              p1=new JPanel();p2=new JPanel();p3=new JPanel();
              p4=new JPanel();p5=new JPanel();p6=new JPanel();
              p7=new JPanel();p8=new JPanel();p9=new JPanel();
              f=new JFrame("New Rental Record");
              l1=new JLabel("........::: Car Rental System :::.........");
              l2=new JLabel("*******************************************************");
              choice=new JLabel("Please select your option:");
              btnA=new JButton("[1] New Rental Record");
              btnB=new JButton("[2] Update Rental Record");
              btnC=new JButton("[3] Search Rental Record");
              btnD=new JButton("[4] Delete Rental Record");
              btnE=new JButton("[5] Display Rental record");
              btnF=new JButton("[6] Exit");
              l3=new JLabel("*******************************************************");
              f.setLayout(new GridLayout(10,1));
              f.pack();
              f.setVisible(true);
              f.setSize(350,500);
              f.setBackground(Color.white);
              p1.add(l1);f.add(p1);
              p2.add(l2);f.add(p2);
              p3.add(choice);f.add(p3);
              p4.add(btnA);f.add(p4);
              p5.add(btnB);f.add(p5);
              p6.add(btnC);f.add(p6);
              p7.add(btnD);f.add(p7);
              p8.add(btnE);f.add(p8);
              p9.add(btnF);f.add(p9);
              btnA.addActionListener(this);
              btnB.addActionListener(this);
              btnC.addActionListener(this);
              btnD.addActionListener(this);
              btnE.addActionListener(this);
              btnF.addActionListener(this);
         f.addWindowListener(new WindowAdapter(){
                   public void windowClosing(WindowEvent e)
                        {System.exit(0);}});
              public void actionPerformed(ActionEvent e){
                        if(e.getSource()== btnA)
                        {     NewRecord nr=new NewRecord();}
                         else if(e.getSource()== btnB)
                        {     updateRecord ur=new updateRecord();}
                        else if(e.getSource()== btnC)
                        {     searchRecord sr=new searchRecord(); }
                        else if(e.getSource()== btnD)
                        {     deleteRecord dr=new deleteRecord(); }
                        else if(e.getSource()== btnE){
                             try{
                                  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                             catch(ClassNotFoundException e3) {
                                  JOptionPane.showMessageDialog(null,"ERROR:"+e3.getMessage());
                             try{
                                  conn=DriverManager.getConnection("Jdbc:Odbc:Car Rental", "", "");
                                  stmt=conn.createStatement();
                                  rs=stmt.executeQuery("Select * from Customer where CustID");
    String s=("CustID:   CustName:    CustAdd:          CustPhone:       No.of days rent:     Rate per rental: \n");
    while(rs.next())
    s=s+rs.getString(1)+"             "+rs.getString(2)+"              "+rs.getString(3)+"              "+rs.getString(4)+"                    "+rs.getString(5)+"                     "+rs.getString(6)+"\n";
                                       JOptionPane.showMessageDialog(null,s);}
    catch(SQLException e4){e4.printStackTrace();}}//end of F
    //to exit the program                    
    else if(e.getSource()== btnF){
    JOptionPane.showMessageDialog(null,"Thank you");System.exit(0);}
    else
    JOptionPane.showMessageDialog(null,"Invalid Option!");System.exit(0);
                   }//end of if statement
    public static void main(String args[]){
              CarRental cr= new CarRental();}//end of main
    }//end of main menu
    //New Rental program when user selects it
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    public class NewRecord extends JFrame implements ActionListener{
         JFrame f;
         Container c;
         FlowLayout layout;
         JLabel l1,l2,custId,custName,custAdd,custPhone,dayRent,rateRent;
    JTextField tid,tname,tphone,tday,trate;
                                  JTextArea tadd;
                                  JButton save,clear,exit;
                                  Connection conn;
                                  Statement stmt;
                                  ResultSet rs;
                                  JPanel p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11;
                             public NewRecord(){
                                //super("New Record");
                                  layout = new FlowLayout();
                                  c=getContentPane();
                                  c.setLayout(layout);
                                  p1=new JPanel();p2=new JPanel();p3=new JPanel();
                                  p4=new JPanel();p5=new JPanel();p6=new JPanel();
                                  p7=new JPanel();p8=new JPanel();p9=new JPanel();
                                  p10=new JPanel();p11=new JPanel();
                                  f=new JFrame();     
                                  l1=new JLabel("........::: New Rental Record :::.........");
                                  l2=new JLabel("*******************************************************");
                                  custId =new JLabel("Customer ID:");
                                  custName=new JLabel("Customer name:");
                                  custAdd=new JLabel("Customer address:");
                                  custPhone=new JLabel("Customer phone:");
                                  dayRent=new JLabel("Days of rental:");
                                  rateRent=new JLabel("Rate per rental:");
                                  tid= new JTextField(10);
                                  tname=new JTextField(10);
                                  tphone=new JTextField(10);
                                  tadd=new JTextArea(4,30);
                                  tday=new JTextField(5);
                                  trate=new JTextField(10);
                                  save=new JButton("SAVE");
                                  clear=new JButton("CLEAR");
                                  exit=new JButton("EXIT");
                                  f.setLayout(new GridLayout(11,1));
                                  f.setBackground(Color.white);
                                  f.setVisible(true);
                                  f.setSize(600,600);
                                  p1.add(l1);f.add(p1);
                                  p2.add(l2);f.add(p2);
                                  p3.add(custId);p3.add(tid);f.add(p3);     
                                  p4.add(custName);p4.add(tname);f.add(p4);
                                  p5.add(custAdd);p5.add(tadd);f.add(p5);
                                  p6.add(custPhone);p6.add(tphone);f.add(p6);                         
                                  p7.add(dayRent);p7.add(tday);f.add(p7);
                                  p8.add(rateRent);p8.add(trate);f.add(p8);
                                  p9.add(save);f.add(p9);
                                  p10.add(clear);f.add(p10);
                                  p11.add(exit);f.add(p11);
                             /*     f.add(l1);
                                  f.add(l2);
                                  f.add(custId);
                                  f.add(tid);
                                  f.add(custName);
                                  f.add(tname);
                                  f.add(custAdd);
                                  f.add(tadd);
                                  f.add(custPhone);
                                  f.add(tphone);
                                  f.add(dayRent);
                                  f.add(tday);
                                  f.add(rateRent);
                                  f.add(trate);
                                  f.add(save);
                                  f.add(clear);
                                  f.add(exit);*/
                                  c.add(f);
                                  save.addActionListener(this);
                                  clear.addActionListener(this);
                                  exit.addActionListener(this);
                                  f.addWindowListener(new WindowAdapter(){
                                  public void windowClosing(WindowEvent e)
                                       {System.exit(0);}});
                             public void actionPerformed(ActionEvent e){
                                  if(e.getSource()== exit)
                                       {System.exit(0);}
                                  if(e.getSource()== clear){
                                       tid.setText("");
                                       tname.setText("");
                                       tadd.setText("");
                                       tphone.setText("");
                                       tday.setText("");
                                       trate.setText("");}
                                  if(e.getSource()== save){
                                       try{
                                            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                                       catch(ClassNotFoundException e1) {
                                            JOptionPane.showMessageDialog(null,"ERROR:"+e1.getMessage());
                                       try{
                                            conn=DriverManager.getConnection("Jdbc:Odbc:Car Rental", "", "");
                                            stmt=conn.createStatement();
                                            rs=stmt.executeQuery("Select * from Customer");
                                            while(rs.next()){
                                            tid.setText(rs.getString(1));
                                            tname.setText(rs.getString(2));
                                            tadd.setText(rs.getString(3));
                                            tphone.setText(rs.getString(4));
                                            tday.setText(rs.getString(5));
                                            trate.setText(rs.getString(6));}
                                            String s=("CustID:   CustName:    CustAdd:          CustPhone:       No.of days rent:     Rate per rental: \n");
                                            while(rs.next())
                                            s=s+rs.getString(1)+"             "+rs.getString(2)+"              "+rs.getString(3)+"              "+rs.getString(4)+"                    "+rs.getString(5)+"                     "+rs.getString(6)+"\n";
                                                 JOptionPane.showMessageDialog(null,s);
                                       catch(SQLException e2){
                                                 e2.printStackTrace();
                             public static void main(String args[]){
                                       NewRecord nr=new NewRecord();
                                  //     nr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                                       }//end of newRecord class
                                  }//ends of New rental program
    I tried to use extending to JPanel or JApplet but still the same. Any help??

    Hi,
    In the NewRecord java file, use change the
    f = new JFrame();               
    c = f.getContentPane();, after that all panel add into the container
    p1.add(l1);c.add(p1);                    
    p2.add(l2);c.add(p2);
    p3.add(custId);p3.add(tid);c.add(p3);     
    p4.add(custName);p4.add(tname);c.add(p4);
    p5.add(custAdd);p5.add(tadd);c.add(p5);
    p6.add(custPhone);p6.add(tphone);c.add(p6);          
    p7.add(dayRent);p7.add(tday);c.add(p7);
    p8.add(rateRent);p8.add(trate);c.add(p8);
    p9.add(save);c.add(p9);
    p10.add(clear);c.add(p10);
    p11.add(exit);c.add(p11);and finally remove this line below
    //c.add(f);Try to avoid add frame into the container, or else you will receive adding a window to a container error.
    Rgrds,
    Sen
    Message was edited by:
    arjensen

  • Adding an additional accorion panel

    I am using the following style sheet code for this page: http://www.vintagetextile.com/brides.htm
    .Accordion { width: 600px;
    margin-right: auto;
    margin-left: auto;}
    .Accordion35 { width: 350px;
    margin-right: auto;
    margin-left: auto;}
    I have added the .Accordion35 rule because I wished to add a 3rd accordion panel below the first two, which use .jpgs that are 600 pixels wide.
    The 3rd accordion panel uses .jpgs that are 350 pixels wide X 550 pixels high.
    However, DW 5.5 ignores the .Accordion35 rule and creates a 3rd accordion panel that is 600 pixels wide, so that the .jpgs in the 3rd panel have 250 pixels of white space to their right in the accordion panel.
    Here is the relevant html code:
    <div id="Accordion2" class="Accordion" tabindex="0">
      <div class="AccordionPanel">
         <div class="AccordionPanelTab">The wedding portrait</div>
      <div class="AccordionPanelContent"><img src="images/Wedding/emily3.jpg" alt="wedding portrait" width="600" height="480"></div></div>
       <div class="AccordionPanel">
         <div class="AccordionPanelTab">Holding hands</div>
      <div class="AccordionPanelContent"><img src="images/Wedding/emily2.jpg" alt="holding hands" width="600" height="480"></div></div>
       <div class="AccordionPanel">
         <div class="AccordionPanelTab">Cutting the cake</div>
    <div class="AccordionPanelContent"><img src="images/Wedding/emily.jpg" alt="cutting the cake" width="600" height="480"></div></div></div>
    <div id="Accordion3" class="Accordion35" tabindex="0">
      <div class="AccordionPanel">
        <div class="AccordionPanelTab">Heirloom Gown</div>
        <div class="AccordionPanelContent"><img src="images/Wedding/amandagreb2.jpg" width="350" height="550" alt="heirloom gown"> </div></div>
      <div class="AccordionPanel">
        <div class="AccordionPanelTab">Label 2</div>
        <div class="AccordionPanelContent">Content 2</div>
      </div>
    </div>
    <p> </p>
    <div id="bronze-bottom"></div>
            <div id="cat-bottom">
              <a href="early.htm">Early</a>  :
               <a href="victorian.htm">Victorian</a>  : 
              <a href="edwardian.htm">Edwardian</a>  :
             <a href="1920s_to_1930s.htm">1920s to 1930s</a>
            :  <a href="1940s_to_designer.htm">1940s to Designer</a>  : 
               <a href="shawlstext.htm">Shawls/Textiles</a>  :          
             <a href="gallery.htm">Gallery</a>  :
            <a href="treasure_hunt.htm">Treasure Hunt</a>  :
              <a href="articles.htm" class="herelink">Articles</a>  : 
              <a href="order.htm">To Order</a>  :       
       <a href="mailto:[email protected]">Email</a>  :  <a href="index.html">Home</a></div>        
    <script type="text/javascript">
    <!--
    var Accordion1 = new Spry.Widget.Accordion("Accordion1");
    var Accordion2 = new Spry.Widget.Accordion("Accordion2");
    var Accordion3 = new Spry.Widget.Accordion("Accordion3");
    //-->
    </script>
    </body></html>
    I suspect that the problem may have something to do with the fact that "spryaccordion.css" (referenced in every .htm page that has an accordion panel) contains this code:
    .Accordion { border-left: solid 1px gray; border-right: solid 1px black; border-bottom: solid 1px gray; overflow: hidden; width: 600px;
    I tried inserting into the "spryaccordion.css" file a rule for .Accordon35 but that did not help.

    Why don't you just add the following to your css:
    #Accordion1, #Accordion2 {
    width: 600px;
    #Accordion3 {
    width: 350px;
    Then delete the width from the following:
    .Accordion {
    border-left: solid 1px gray;
    border-right: solid 1px black;
    border-bottom: solid 1px gray;
    overflow: hidden;
    .AccordionPanelContent {
        overflow: auto;
        margin: 0px;
        padding: 0px;

  • How to find out if a panel contains a specific component

    I am in a situation where i need to know whether a panel contains a specific component or not, like is there a specific method for that.
    To clarify, example :
    Suppose i have a panel
    JPanel p1;
    p1 = new JPanel();
    JLabel label = new JLabel("LABEL");
    p1.add(label);In this code i already know that p1 contains label, however at runtime, i would like to know if p1 contains label or not (assuming i removed the label at some point)

    verminator wrote:
    I thought that should have done the trick, and maybe it will, but did i do something wrong here :
    JPanel p1 = new JPanel();
    JLabel l1 = new JLabel("LABEL");
    p1.add(l1);
    if(isDescendingFrom(l1,p1))          //error here
    System.out.println("true");
    else
    System.out.println("false");
    }do you have to import some other package other than javax.swing.SwingUtilities for this method, because i'm getting an error "cannot find symbol" referring to the isDescendingFrom() methodSwingUtilities isn't a package, it's a class. isDescendingFrom() is a static method in that class.
    To call isDescendingFrom(), it should look like this:
    SwingUtilities.isDescendingFrom(c1, c2);

  • Adding Text to a Buffered Image

    Hey
    I am trying to add text to a bufferedimage image and have tried a couple of ways.
    I cannot seem to get it to work propely though. Everytime i try, the text appears but the image appears inside the lettering of the text and not under it like i want it to.
    Could someone please explain the best way of place text on TOP of an image as i am really stuck now :(
    Thanks in advanced for any help

    Basically paint your buffered image into a new BufferedImage and then paint in the new text on top.
    Here's a demo.
    import java.awt.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    public class BufferedImageTest
        public static void main(String[] args)
            ImageGenerator ig = new ImageGenerator();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(ig.getOriginalImagePanel(), "North");
            f.getContentPane().add(ig.getTextPanel(), "South");
            f.setSize(400,640);
            f.setLocation(200,50);
            f.setVisible(true);
            f.getContentPane().add(ig.getNewImagePanel());
            f.validate();
            f.repaint();
    class ImageGenerator
        JPanel originalPanel = new JPanel()
            public void paintComponent(Graphics g)
                super.paintComponent(g);
                Graphics2D g2 = (Graphics2D)g;
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                    RenderingHints.VALUE_ANTIALIAS_ON);
                int w = getWidth();
                int h = getHeight();
                g2.setPaint(Color.blue);
                g2.fill(new Rectangle2D.Double(w/16, h/16, w*7/8, h*7/8));
                g2.setPaint(Color.yellow);
                g2.fill(new Rectangle2D.Double(w/8, h/8, w*3/4, h*3/4));
                g2.setPaint(Color.red);
                g2.fill(new Ellipse2D.Double(w/6, h/6, w*2/3, h*2/3));
                g2.setPaint(Color.green);
                g2.draw(new Line2D.Double(w/16, h/16, w*15/16, h*15/16));
        JPanel textPanel = new JPanel()
            Font font = new Font("lucida sans regular", Font.PLAIN, 32);
            String text = "A New Label";
            public void paintComponent(Graphics g)
                super.paintComponent(g);
                Graphics2D g2 = (Graphics2D)g;
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                    RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setFont(font);
                FontRenderContext frc = g2.getFontRenderContext();
                LineMetrics lm = font.getLineMetrics(text, frc);
                float textWidth = (float)font.getStringBounds(text, frc).getWidth();
                int w = getWidth();
                int h = getHeight();
                float x = (w - textWidth)/2;
                float y = (h + lm.getHeight())/2 - lm.getDescent();
                g2.drawString(text, x, y);
        public ImageGenerator()
            originalPanel.setBackground(Color.white);
            originalPanel.setPreferredSize(new Dimension(300,200));
            textPanel.setOpaque(false);
            textPanel.setPreferredSize(new Dimension(300,200));
        private BufferedImage createNewImage()
            BufferedImage image = new BufferedImage(originalPanel.getWidth(),
                                                    originalPanel.getHeight(),
                                                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = image.createGraphics();
            originalPanel.paint(g2);
            textPanel.paint(g2);
            g2.dispose();
            return image;
        public JPanel getOriginalImagePanel()
            return originalPanel;
        public JPanel getTextPanel()
            return textPanel;
        public JPanel getNewImagePanel()
            JPanel panel = new JPanel()
                BufferedImage image = createNewImage();
                public void paintComponent(Graphics g)
                    super.paintComponent(g);
                    Graphics2D g2 = (Graphics2D)g;
                    g2.drawImage(image, null, 0, 0);
            return panel;
    }

  • Display the panel container when user select the specific tab in a tab set

    Hi SAP Experts,
    I've faced some problems and i would like to seek some help from the experts.
    Basically, my requirement is to display the component "panel container" which contains some data whenever a user select e.g. Tab "A" of my component Tab set. Similarly, it hides again when the user select Tab "B" and another panel container appear for it.
    I am not sure if this is achievable in Xcelsius. Experts, please advise me.
    Your help will be greatly appreciated!
    Thanks a lot!
    Feel free to clear any doubts with me
    Best regards,
    htoh

    actually, you can not do that, since you dont have a reference of the current selected tab

  • Unable to find the  'Panel Container 2' object

    Hi,
    I am unable to find the  'Panel Container 2' object under the containers folder of components. I am using xcelsius enterprise 2008.
    I have a scenario where in which i need to use it, Is there any way I can get it into the canvas.
    Thanks in advance,
    Shreesh.

    Hi,
    Which Theme are you using now? Not all of the themes have "Panel Container 2" object. Theme "Aqua" and Theme "Nova" have "Panel Container 2", please try them.
    Thanks,
    Grace

  • Adding scrollbars in jtextarea

    can any one tell me the method of adding scrollbars in jtextarea such that they are enabled when required means initially disabled but when the text goes long they are enabled.
    farhan

    Add ur JTextArea in a JScrollPane by doing this :
    JScrollPane jsp = new JScrollPane(JScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    //then add ur Jtext hereMaz -

  • HI Please Help me with Zoom of a buffered image

    Hi All,
    Please help,
    I want to zoom the buffered image using Affine Transforms, the code shown below can rotate the buffered image now how to zoom the same buffered image using Affine Transforms.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import javax.swing.*;
    public class RotationBounds extends JPanel implements ActionListener
        BufferedImage image;
        AffineTransform at = new AffineTransform();
        Rectangle2D.Double bounds = new Rectangle2D.Double();
        double theta = 0;
        double thetaInc = Math.PI / 2;
        public void actionPerformed(ActionEvent e)
            theta += thetaInc;
            setTransform();
            repaint();
        private void setTransform()
            int iw = image.getWidth();
            int ih = image.getHeight();
            double cos = Math.abs(Math.cos(theta));
            double sin = Math.abs(Math.sin(theta));
            double width = iw * cos + ih * sin;
            double height = ih * cos + iw * sin;
            double x = (getWidth() - iw) / 2;
            double y = (getHeight() - ih) / 2;
            at.setToTranslation(x, y);
            at.rotate(theta, iw / 2.0, ih / 2.0);
            x = (getWidth() - width) / 2;
            y = (getHeight() - height) / 2;
            // Set bounding rectangle that will frame the image rotated
            // with this transform. Use this width and height to make a
            // new BuffferedImage that will hold this rotated image.
            // AffineTransformOp doesn't have this size information in
            // the translation/rotation transform it receives.
            bounds.setFrame(x - 1, y - 1, width + 1, height + 1);
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            setBackground(Color.gray);
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
            if (image == null)
                initImage();
            g2.drawRenderedImage(image, at);
            // g2.setPaint(Color.blue);
            g2.draw(bounds);
            g2.setPaint(Color.green.darker());
            g2.fill(new Ellipse2D.Double(getWidth() / 2 - 2,
                getHeight() / 2 - 2, 4, 4));
        private void initImage()
            int w = 360, h = 300;
            image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = image.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(new Color(220, 240, 240));
            g2.fillRect(0, 0, w, h);
            g2.setPaint(Color.red);
            g2.drawString("Text for test", 50, 50);
            g2.drawRect(0, 0, w - 1, h - 1);
            g2.dispose();
            g2.setTransform(at);
    //        setTransform();
        private JPanel getLast()
            JButton rotateButton = new JButton("Rotate");
            rotateButton.addActionListener(this);
             JButton zoomButton = new JButton("Zoom");
            JPanel panel = new JPanel();
            panel.add(rotateButton);
            panel.add(zoomButton);
            return panel;
        public static void main(String[] args)
            RotationBounds test = new RotationBounds();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(test);
            f.getContentPane().add(test.getLast(), "North");
            f.setSize(400, 400);
            f.setLocation(0, 0);
            f.setVisible(true);
    }Message was edited by:
    New_to_Java

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import java.util.Hashtable;
    import javax.swing.*;
    import javax.swing.event.*;
    public class RotationZoom extends JPanel {
        AffineTransform at = new AffineTransform();
        Point2D.Double imageLoc = new Point2D.Double(100.0, 50.0);
        Rectangle2D.Double bounds = new Rectangle2D.Double();
        BufferedImage image;
        double theta = 0;
        double scale = 1.0;
        final int PAD = 20;
        public RotationZoom() {
            initImage();
        public void addNotify() {
            super.addNotify();
            setTransform();
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            g2.drawRenderedImage(image, at);
            g2.setPaint(Color.red);
            g2.draw(bounds);
        public Dimension getPreferredSize() {
            return new Dimension((int)(imageLoc.x + Math.ceil(bounds.width))  + PAD,
                                 (int)(imageLoc.y + Math.ceil(bounds.height)) + PAD);
        private void update() {
            setTransform();
            revalidate();
            repaint();
        private void setTransform() {
            int iw = image.getWidth();
            int ih = image.getHeight();
            double cos = Math.abs(Math.cos(theta));
            double sin = Math.abs(Math.sin(theta));
            double width  = iw*cos + ih*sin;
            double height = ih*cos + iw*sin;
            at.setToTranslation(imageLoc.x, imageLoc.y);
            at.rotate(theta, scale*iw/2.0, scale*ih/2.0);
            at.scale(scale, scale);
            double x = imageLoc.x - scale*(width - iw)/2.0;
            double y = imageLoc.y - scale*(height - ih)/2.0;
            bounds.setFrame(x, y, scale*width, scale*height);
        private void initImage() {
            int w = 240, h = 180;
            int type = BufferedImage.TYPE_INT_RGB;
            image = new BufferedImage(w,h,type);
            Graphics2D g2 = image.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setBackground(new Color(220,220,240));
            g2.clearRect(0,0,w,h);
            g2.setPaint(Color.red);
            g2.draw(new CubicCurve2D.Double(0, h, w*4/3.0, h/4.0,
                                            -w/3.0, h/4.0, w, h));
            g2.setPaint(Color.green.darker());
            g2.draw(new Rectangle2D.Double(w/3.0, h/3.0, w/3.0, h/3.0));
            g2.dispose();
        private JPanel getControls() {
            JSlider rotateSlider = new JSlider(-180, 180, 0);
            rotateSlider.setMajorTickSpacing(30);
            rotateSlider.setMinorTickSpacing(10);
            rotateSlider.setPaintTicks(true);
            rotateSlider.setPaintLabels(true);
            rotateSlider.addChangeListener(new ChangeListener() {
                public void stateChanged(ChangeEvent e) {
                    int value = ((JSlider)e.getSource()).getValue();
                    theta = Math.toRadians(value);
                    update();
            rotateSlider.setBorder(BorderFactory.createTitledBorder("theta"));
            int min = 50, max = 200, inc = 25;
            JSlider zoomSlider = new JSlider(min, max, 100);
            zoomSlider.setMajorTickSpacing(inc);
            zoomSlider.setMinorTickSpacing(5);
            zoomSlider.setPaintTicks(true);
            zoomSlider.setLabelTable(getLabelTable(min, max, inc));
            zoomSlider.setPaintLabels(true);
            zoomSlider.addChangeListener(new ChangeListener() {
                public void stateChanged(ChangeEvent e) {
                    int value = ((JSlider)e.getSource()).getValue();
                    scale = value/100.0;
                    update();
            zoomSlider.setBorder(BorderFactory.createTitledBorder("scale"));
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1.0;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            panel.add(rotateSlider, gbc);
            panel.add(zoomSlider, gbc);
            return panel;
        private Hashtable getLabelTable(int min, int max, int inc) {
            Hashtable<Integer,JComponent> table = new Hashtable<Integer,JComponent>();
            for(int j = min; j <= max; j += inc) {
                JLabel label = new JLabel(String.format("%.2f", j/100.0));
                table.put(new Integer(j), label);
            return table;
        public static void main(String[] args) {
            RotationZoom test = new RotationZoom();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JScrollPane(test));
            f.getContentPane().add(test.getControls(), "Last");
            f.setSize(500,500);
            f.setLocation(200,100);
            f.setVisible(true);
    }

  • Convert JPanel to buffered Image

    Hi,
    i have a JPanel,I override the paintComponent() method to do a lot of painting. the size of this panel is about 2500 X 2500 i want to convert it to a buffered image,
    but i dont get image of total panel, but only the image of what is displayed on screen, every thing else is black, i guess becuase this is not painted,
    so how do i get the total image, need help
    this is my code for creating image
    JFrame frame new JFrame();
    frame.getContentPane().add(myPanel);
    this.setSize(1000,700);
    show();
    int iWidth = myPanel.getPreferredSize().width;
    int iHeight =myPanel.getPreferredSize().height;
    BufferedImage image = new BufferedImage(iWidth, iHeight, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = image.createGraphics();
    myPanel.paint(g2);
    try
         ImageIO.write(image, "jpeg", new File("example.jpeg"));
    catch (Exception e) {
    e.printStackTrace();
    }Ashish

    i use this    chartPanel = new JPanel() {
          public void paint(Graphics g) {
            Image img = paintGraph(chartPanel.getWidth(), scroller.getViewport().getHeight());
            g.drawImage(img, 0, 0, Color.white, null);
      protected Image paintGraph(int width, int height) {
        if ((offscreen == null) || (width != offscreensize.width) || (height != offscreensize.height)) {
          offscreen = createImage(width, height);
          offscreensize = new Dimension(width, height);
          offgraphics = (Graphics2D)offscreen.getGraphics();
          try {
            offgraphics.setClip(0, 0, width, height);
            drawChart(offgraphics, width, height);
            offgraphics.setXORMode(offgraphics.getBackground());
            drawSelectables(offgraphics, width, height);
          } catch (ArrayIndexOutOfBoundsException e) { /* we have no data */ }
        return offscreen;
      }where scroller is my JScrollPane() and i get the complete panel to draw on.
    thomas

  • Stretch part of a buffered image

    For my dissertation at university I am writing a program to generate rectangular cartograms, for an example look at:
    here (Not my work)
    I have written the algorithm to generate the cartograms(rectangles are drawn using Java 2D rectangle) and as a further step, I have overlayed a transparent buffered image of the actual map. I want to link the image and the rectangles so that when a rectangle gets bigger, that part of the image gets stretched larger (and visa versa for a rectangle getting smaller). I can check whether rectangles are getting larger or smaller but I am not sure about how to code the stretching(distorting) of the buffered image. Any ideas (or suggestions how to do this differently) would be greatly appreciated.
    I am posting my drawing code in case this helps understand what I am trying to do. The algorithm for generating cartograms is not important and is contained in another class.
    public class DrawPanel extends JPanel
        private BufferedImage image;
         private ArrayList<Rect> newrectList;
        private ArrayList<Integer> newareaList;
        private ArrayList<ArrayList<ArrayList<Integer>>> newneighbourList;
        * Sets inherited arraylist as local variables
        * @param rectList an arraylist of Rect objects
         * @param areaList an arraylist of the desired area for each rectangle
         * @param neighbourList
         * @param transparency
         public DrawPanel(ArrayList<Rect> rectList, ArrayList<Integer> areaList,
                ArrayList<ArrayList<ArrayList<Integer>>> neighbourList,double transparency) throws IOException
            setSize(600,480);
              newrectList = rectList;
            newareaList = areaList;
            newneighbourList = neighbourList;
            float tempfloat=(float) transparency;
            image =   loadTranslucentImage(tempfloat);
        public static BufferedImage loadTranslucentImage(float transperancy) throws IOException
                // Load the image
                BufferedImage loaded = ImageIO.read(new File("Europe_map.jpg"));
                // Create the image using the
                BufferedImage aimg = new BufferedImage(loaded.getWidth(), loaded.getHeight(), BufferedImage.TRANSLUCENT);
                // Get the images graphics
                Graphics2D g = aimg.createGraphics();
                // Set the Graphics composite to Alpha
                g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, transperancy));
               // Draw the LOADED img into the prepared reciver image
                g.drawImage(loaded,null,0, 0);
              // let go of all system resources in this Graphics
               g.dispose();
               // Return the image
               return aimg;
        @Override
        * draws the rectangles
        * @param g A graphics object in order to draw rectangles to the screen
      //Code removed because I went over the character count
         * redraws the rectangles to the screen
        public void reDrawMap(boolean toHighlight, int highlight, boolean showPop, double transparency,
                boolean transparencyChanged) throws IOException
         Graphics g = this.getGraphics();
         g.clearRect(0,0,600,480);
         g.setColor(Color.blue);
         g.fillRect(0,0,600,480);
        int x=0;
         for(int i = 0; i < newrectList.size(); i++)
                Rect rect = newrectList.get(i);
                        int j = newareaList.get(i);
                        int area = j*j;
                       //not important                      
                g.fill3DRect(rect.x, rect.y, rect.width, rect.height,true);
                   g.setColor(Color.black);
                   g.drawString(rect.name,(rect.x)+5,(rect.y)+10);
                if(showPop == true)
                    double finalarea = area*0.005;
                    BigDecimal b = new BigDecimal(finalarea).setScale(2,BigDecimal.ROUND_HALF_UP);
                    finalarea=b.doubleValue();
                    String areastring = Double.toString(finalarea);
                    g.drawString(areastring,(rect.x)+5,(rect.y)+25);
        if(transparencyChanged ==true)
            float tempfloat=(float) transparency;
            image =   loadTranslucentImage(tempfloat);
           g.drawImage(image, 0, 0,getWidth(),getHeight(), null);
        else
            g.drawImage(image, 0, 0,getWidth(),getHeight(), null);
    }My idea is to have an arraylist of rectangles in this class to keep a local copy of the rectangles being drawn. It is then easy to test if the new rectangle being drawn has a greater or less area than previously. Once this is done, I need to execute some code to stretch a rectangle of that size and position in "image".
    Thanks,
    Matt

    I want to link the image and the rectangles so that when a rectangle gets bigger, that part of the image gets stretched larger (and visa versa for a rectangle getting smaller)Why don't you create a class that has at least these two fields
    BufferedImage country;
    Rectangle rect;Of course you can use any name for the fields you want.
    You have one universal image (in this case "Euro_map.jpg"). Country will be a subimage of this universal one
    //see BufferedImage#getSubimage api
    country = euroMap.getSubimage(x,y,w,h);then when you draw rect you draw the country on top of it scaled to fit the same bounds.
    g2d.setRenderingHint(
            java.awt.RenderingHints.KEY_INTERPOLATION,
            java.awt.RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2d.setComposite(
            AlphaComposite.getInstance(AlphaComposite.SRC_OVER, transperancy));
    g2d.drawImage(country,rect.x,rect.y,rect.width,rect.height,null);
    g2d.setComposite(AlphaComposite.SrcOver);Lastly, in your code you have this
    BufferedImage aimg = new BufferedImage(loaded.getWidth(), loaded.getHeight(), BufferedImage.TRANSLUCENT);The third parameter should be a BufferedImage type (TYPE_INT_ARGB for example). java.awt.Transparency.TRANSLUCENT has a value of 3, so you were creating a TYPE_INT_ARGB_PRE by chance. Luckily this type has an alpha channel. Were you aware you were doing that?

  • When I try to print my book I receive the following error message:  One or more of the images in your book are not presently available at full resolution. Please reconnect to these files by mounting the volume(s) containing the original images.

    When I try to print my book, I receive the following error message:  One or more of the images in your book are not presently available at full resolution. Please reconnect to these files by mounting the volume(s) containing the original images.  I don't understand what this means since all the photos are in the book.  Can someone please clarify?

    When you look at the images in the browser, do you see any arrow icons on your thumbnails? Like these:
    When you import your images from a folder on your system drive, you have two ways to import:
    Managed: Import and store the images in the library
    Or referenced: Leave the images in the folder outside the Aperture library.
    This is controlled by the "Store Files" settings in the Import panel:
    If you did not set "Store files" to "In the Aperture Library", the originals will stay in the folder outside.
    The error message you get, suggests that Aperture assumes the original files are in a folder outside the library.
    Select one of your images in the Browser and use the command "File > Show in Finder" - is this command available or dimmed out?

  • Stretch part of a buffered image Part 2

    I recently posted a question regarding resizing parts of a buffered image here . This question was answered brilliantly by Maxideon. I have implemented his suggestion and it works a treat, however because my application does not have rectangles for the sea areas of the map, those parts of the bufferedimage stay still and contains parts of countries that stay undistorted. My question is, is there a way to distort part of the image so that it drags the surrounding parts with it, making the distortion look a bit smoother?
    Thanks in advance.

    I have uploaded a video of the program at work to youtube here . As you can see, as the rectangles shrink/expand they drag the part of the map with them but they leave gaps, I was hoping to make this smoother in some way so the whole image becomes distorted. Thanks for your reply.
    Regards,
    Matthew

Maybe you are looking for

  • Unable to delete Address Book File

    I am unable to delete nor copy over an Address Book file that I have on an external HD connected via Airport Extreme. When I connect the HD directly to my Macbook Pro, I am able to delete the file - but not via Airport Extreme. When I attempt to dele

  • Help needed for Time Calc Java Script

    Hi, I am trying to create a timesheet in PDF and have hit a speed bump. Is there anyone there who could provide me with a script that calculated the difference between 2 times? (Field2 time)-(Feild 1 Time) = Duration.I am desperate and have tried eve

  • Dashboard Design Cache Server failed to start after upgrade to BOBJ 4.0 SP09 Patch 3

    Hi Friends, We have upgraded our BOBJ 4.0 server from SP04 Patch 8 to SP09 patch 3. After upgrade completed "Dashboard Design Cache Server" Failed to start. other servers are running fine. xccache_<hostname>.DashboardDesignCacheServer_trace.000003.gl

  • INDIA - Subcontract Process- Creation of Excise Invoice T-code J1IS

    Dear All, We are placing most of the purchase orders on subcontractor labour basis & raw material steel is being supplied by us to subcontractor. Transfer posting Movement type 311. After creation of material document Excise Invoice is created using

  • How do you open a .cwk document in pages?

    How do you open a .cwk (the old Apple word processing program) document in Pages?