How to tint a JPanel that paints an Image

Hello all,
I have a basic understanding of Java Swing architecture and the Drawing capabilities of the Graphics and Graphics2D classes. However, i am utterly confused how to implement a basic tint over an image.
Overview:
I have a GCard (Graphical Card) class that extends JPanel. This class contains a BufferedImage so that when the GCard is added to a higher-level Container, it paints the BufferedImage. What I want to do is tint that card image to a user specified color (let's say RED) via the GCard.setTint(Color.RED) method and then allow them to control if the tint is on/off via the GCard.setTinted(true) method.
What I have:
Currently, I have the following in my GCard.paintComponent(Graphics g) method:
     @Override
     protected void paintComponent(Graphics g) {
          int xPosition = 0;
          int yPosition = 0;
          if(image != null) {
               g.drawImage(image, xPosition, yPosition, null);
               if(isTinted() && tint != null) {
                    g.setColor(tint);
                    for(int x = xPosition; x < (xPosition + image.getWidth()); x += 2)
                         for(int y = yPosition; y < (yPosition + image.getHeight()); y += 2)
                              g.drawLine(x, y, x, y);
     }All this does is implement a rudimentary tinting scheme by setting every other pixel in the panel to the tint color.
What I want:
What I'd like to see instead is a red haze over the entirety of the image. Much like the multiple item selection process that occurs when you select multiple things in a modern-day OS.
How can i do this?
From what I've read/thought out, I can either edit the actual image data to increase the level of the appropriate tint color, but I would prefer to be non-destructive to the image I'm holding in memory. I would prefer to imitate the 'layer' functionality of Adobe Photoshop where my image is the 'background' and I have a transparent panel that is tinted which can be switched on and off. Can I accomplish all of this in the paintComponent() method or will i need to add a JPanel (let's call it a tintPanel)to the GCard object and then add/remove that component from the GCard as necessary?
Thanks for the help!
-Pheez

Something likeprotected void paintComponent(Graphics g) {
   super.paintComponent(g);
   g.drawImage(....);
   g.setColor(new Color(r, g, b, a)); // where a <1.0
   g.fillRect(aRectThatOverlapsTheImage);
}db

Similar Messages

  • How to draw a JPanel in an offscreen image

    I am still working on painting a JPanel on an offline image
    I found the following rules :
    - JPanel.setBounds shall be called
    - the JPanel does not redraw an offline image, on should explicitly override paint()
    to paint the children components
    - the Children components do not pain, except if setBounds is called for each of them
    Still with these rules I do not master component placement on the screen. Something important is missing. Does somebody know what is the reason for using setBounds ?
    sample code :
    private static final int width=512;
    private static final int height=512;
    offScreenJPanel p;
    FlowLayout l=new FlowLayout();
    JButton b=new JButton("Click");
    JLabel t=new JLabel("Hello");
    p=new offScreenJPanel();
    p.setLayout(l);
    p.setPreferredSize(new Dimension(width,height));
    p.setMinimumSize(new Dimension(width,height));
    p.setMaximumSize(new Dimension(width,height));
    p.setBounds(0,0,width,height);
    b.setPreferredSize(new Dimension(40,20));
    t.setPreferredSize(new Dimension(60,20));
    p.add(t);
    p.add(b);
    image = new java.awt.image.BufferedImage(width, height,
    java.awt.image.BufferedImage.
    TYPE_INT_RGB);
    Graphics2D g= image.createGraphics();
    // later on
    p.paint(g);
    paint method of offScreenPanel :
    public class offScreenJPanel extends JPanel {
    public void paint(Graphics g) {
    super.paint(g);
    Component[] components = getComponents();
    for (int i = 0; i < components.length; i++) {
    JComponent comp=(JComponent) components;
    comp.setBounds(0,0,512,512);
    components[i].paint(g);

    Unfortunately using pack doesn't work, or I didn't use it the right way.
    I made a test case, eliminated anything not related to the problem (Java3D, applet ...). In the
    test case if you go to the line marked "// CHANGE HERE" and uncomment the jf.show(), you have
    an image generated in c:\tmp under the name image1.png with the window contents okay.
    If you replace show by pack you get a black image. It seems there still something.
    simplified sample code :[b]
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import com.sun.j3d.utils.applet.*;
    import com.sun.j3d.utils.image.*;
    import com.sun.j3d.utils.universe.*;
    import java.io.*;
    import java.awt.image.*;
    import javax.imageio.*;
    public class test {
    private static final int width=512;
    private static final int height=512;
    public test() {
    JPanel p;
    BorderLayout lay=new BorderLayout();
    java.awt.image.BufferedImage image;
    // add a JPanel with a label and a button
    p=new JPanel(lay);
    p.setPreferredSize(new Dimension(width,height));
    JLabel t=new JLabel("Hello");
    t.setPreferredSize(new Dimension(60,20));
    p.add(t,BorderLayout.NORTH);
    p.setDebugGraphicsOptions(DebugGraphics.LOG_OPTION );
    // show the panel for debug
    JFrame jf=new JFrame();
    jf.setSize(new Dimension(width,height));
    jf.getContentPane().add(p);
    [b]
    // CHANGE HERE->
    jf.pack();
    //jf.show();
    // create an off screen image
    image = new java.awt.image.BufferedImage(width, height,
    java.awt.image.BufferedImage.TYPE_INT_RGB);
    // paint JPanel on off screen image
    Graphics2D g= image.createGraphics();
    g.setClip(jf.getBounds());
    System.err.println("BEFORE PAINT");
    jf.paint(g);
    System.err.println("AFTER PAINT");
    // write the offscreen image on disk for debug purposes
    File outputFile = new File("c:\\tmp\\image1.png");
    try {
    ImageIO.write(image, "PNG", outputFile);
    } catch (Exception e) {
    System.err.println(e.getMessage());
    g.dispose();
    jf.dispose();
    public static void main(String[] args) {
    test t=new test();
    }

  • How to display HTML pages that have encrypted images?

    I’ve got a simple page like this:
    <html>
    <body>
    <img src="encrypted.jpg"></img>
    </body>
    </html>
    The encrypted.jpg is an encrypted file on the hard drive. When I load that page into a JTextPane, I want to use my key to decrypt the image on the fly before it is displayed. How can I do that?

    Go it.
    Just let HTMLEditorKit.getViewFactory return my own factory, which allows me to implement the view of a particular element.

  • How can I remove speckles that appear in images in Photoshop CC?

    When I open an image in photoshop cc I get speckles of pinks and purples all over the image.  When I turn on the View Gamut Warning, the speckles disappear.  Also when I save an image as a file like jpg they do not appear.  How can I get rid of the speckles that appear when I'm working on an image in photoshop? 

    Looks like you have a video card driver problem causing the color management shaders to return bad results.
    You can either set the GPU mode to Basic, or update the video card drivers from the GPU maker's website.

  • Zooming a Jpanel that contains Jbutton

    My question is how to zoom a jpanel that contains several jbutton... I am not sure what method to use.... when using a Graphics2D object there seem to be only methods as g.drawString(...)
    g.drawRectangle(..) etc... I am kind of familiar with
    AffineTransform, scaling matrix, etc but not how to zoom a jpanel with jcomponent...
    I hope some one out there understand what i am trying to do...please could you give me any idea
    thanx

    Hello.
    The solution could be the following:
    1. Create interface ZoomPane with the following methods:
    boolean isZoomMode
    float getZoomFactor
    2. ZoomPane interface must be implemented by some JComponent (JPanel will fit, assume it's called JZoomPanel)
    3. the paint method's body of the JZoomPanel should looks like:
    Graphics2D g2 = (Graphics2D)g;
    if(isZoomMode()){
    float zoomFactor = getZoomFactor();
    g2.scale(zoomFactor, zoomFactor);
    super.paint(g);
    4. Use updated RepaintManager.
    This solution solve all painting problem. The mouse event transformation problem can be solved as described above (by means of the glass pane).

  • Setting a jpanel as a background image

    i have managed to load the image into a jpanel but now need to know how to set the jpanel as a background image, to allow my jbuttons and textfields to be seen over the top

    that statement is unbeleivably true.
    right, heres my two classes, the first class is where i created the image
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.* ;
    import java.io.*;
    import javax.imageio.*;
    public class EmailBackgroundImage extends JComponent
    public void paint (Graphics g)
    File bkgdimage = new File ("background.jpg");
    Image imagebg = createImage ( 250,300 );
    try {
    imagebg = ImageIO.read(bkgdimage);
    catch (IOException e)
    g.drawImage(imagebg, 0, 0,null,null);
    this next class is where i'm trying to make the background
    youll notice remnants of my current attempt to create the background image.
    in its current state it does compile
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.* ;
    import java.sql.*;
    import java.util.*;
    import java.awt.color.*;
    public class emailFrontpage extends JFrame implements ActionListener
    JLabel FirstNameLabel = new JLabel("First Name");
    JLabel LastNameLabel = new JLabel("Last Name");
    JLabel EmailLabel = new JLabel("Email Address");
    JTextField FirstNameText = new JTextField( 10 );
    JTextField LastNameText = new JTextField( 10 );
    JTextField EmailAddressText = new JTextField( 20 );
    JPanel panel1 = new JPanel();
    JPanel panel2 = new JPanel();
    JPanel panel3 = new JPanel();
    JPanel panel4 = new JPanel();
    JPanel panel5 = new JPanel();
    JPanel image = new JPanel();
    JButton Enterbutton = new JButton("Enter Details");
    JButton Logon = new JButton("Log on");
    EmailBackgroundImage myimage;
    EmailEdit editEmp;
    emailFrontpage()
    getContentPane().setLayout( new BoxLayout( getContentPane(), BoxLayout.Y_AXIS ));
    myimage = new EmailBackgroundImage();
    image.add(myimage);
    myimage.setSize(250,300);
    image.setOpaque( false );
    FirstNameLabel.setForeground(Color.WHITE);
    LastNameLabel.setForeground(Color.WHITE);
    EmailLabel.setForeground(Color.WHITE);
    panel1.add(Logon);
    panel2.add(FirstNameLabel); panel2.add(FirstNameText);
    panel3.add(LastNameLabel); panel3.add(LastNameText);
    panel4.add(EmailLabel); panel4.add(EmailAddressText);
    panel5.add(Enterbutton);
    getContentPane().add(image);
    getContentPane().add(panel1);
    getContentPane().add(panel2);
    getContentPane().add(panel3);
    getContentPane().add(panel4);
    getContentPane().add(panel5);
    // .setBackground( Color.black )
    Enterbutton.addActionListener( this );
    Logon.addActionListener( this );
    Enterbutton.setActionCommand( "ENTERBUTTONPRESSED" );
    Logon.setActionCommand( "LOGONBUTTONPRESSED" );
    setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
    editEmp = new EmailEdit();
    public void actionPerformed( ActionEvent evt)
    if ( evt.getActionCommand().equals("LOGONBUTTONPRESSED") )
    emailLogonpage emaillogon = new emailLogonpage();
    emaillogon.setSize( 250, 300 );
    emaillogon.setVisible( true );
    emaillogon.setResizable(false);
    setVisible(false);
    else
    String newFN = FirstNameText.getText();
    String newLN = LastNameText.getText();
    String newEA = EmailAddressText.getText();
    editEmp.addNewEmail(newFN, newLN, newEA);
    setVisible(false);
    emailFrontpage emailfront = new emailFrontpage();
    emailfront.setSize( 250, 300 );
    emailfront.setVisible( true );
    emailfront.setResizable(false);
    public static void main ( String[] args )
    emailFrontpage emailfront = new emailFrontpage();
    emailfront.setSize( 250, 300 );
    emailfront.setVisible( true );
    emailfront.setResizable(false);
    }

  • IMac screen colour, how to show tints and shades that won't appear

    iMac screen colour, how do I show tints and shades that won't appear on screen
    I have a 2 month old imac, with a great screen. But for some reason I cant  se light shades of colour like 5% of a tint.
    yet on older macs, and a 2 year old imac, i can see them prefectly.
    Some designs have light panels with 5% colours, some a precent of a colour.
    Can anyone suggest a way to calibrate the screen, or set the screen to show all the colours n tints used as accuratley as possible.
    Advice much appreciated

    The fdisk output shows that it is a single GPT disk. Has any disk manipulation been done, like resizing or repartitioning.
    Your GPT looks correct. If you create a Hybrid MBR via gdisk and include partitions 2,3 and 4 and make 4 bootable, does Windows partition show up in Startup and as a separate volume in Finder?
    Please see https://discussions.apple.com/thread/5641066 for Hybrid MBR creation.

  • How to use an object's paint method

    I have created a class imagePanel which extends a jPanel to display an image. When I create a new imagePanel object I pass it an image argument which is used to paint my image on the jPanel, so far so good. I don't wish to have to continuously create new ImamePanels to display new images so I thought I could make a set_Image method that would set a new image in an exising imagePanel object. This is where I run into problems how to use the existing object paint method to replace the image. I tried this without success:
    public Image setMyImage (Image myImage)
    imageX = myImage; // imageX is the image that is painted by the imagePanel object's paint method
    paint(g);
    Something must be wrong on how I access the paint method. Thanks for any help.
    Jack

    Yahoooo, got it. This was the code I needed and thanks for your help:
    public void setImage (Image myImage)
    imageX = myImage;
    repaint(300);
    }

  • How to senter a JPanel on a parent container

    Hi,
    I have a fixed sized JPanel that I want to add to the center of a container. I would like my JPanel's center to be fixed to the center of the container.
    I have tried to use GridBagLayout with a GridbagConstraint like follows:
    GridBagLayout gridbag = new GridBagLayout();
    getContentPane().setLayout(gridbag);
    GridBagConstraints c = new GridBagConstraints();
    c.fill = c.CENTER;
    SubPanel subPanel = new SubPanel();
    gridbag.setConstraints(subPanel, c);
    getContentPane().add(subPanel);
    setSize(400, 500);
    setVisible(true);
    But this results in the upper left corner of my JPanel being put in the center of the container. Does anyone know how to get the center of my JPanel being placed in the center?
    Best regards
    // Johan

    how about flowlayout?
    this.setLayout( new Flowlayout( Flowlayout.CENTER ) );
    this.add( subPanel );
    This might put it at the center at the top though.
    Another way would be to use GridLayout and set the grids, when you add your panel it Should size the cells equal to your largest component which would be the JPanel, then just add blank JLabels to the other cells and add your subpanel to the center cell, that my work better.

  • How to make a JPanel selectable

    When extending a JPanel and overriding the paintComponent() method the custom JPanel can not be selected so that it gets for example KeyEvents.
    But if I make the new Class extend a JButton it gets of course selected and able to receive for example KeyEvents.
    My question is therefore; what does the JButton implement that a JPanel doesn&#8217;t so that a JButton gets selectable? Or in other words; how to make a JPanel selectable?
    Aleksander.

    Try this extended code. Only the first panel added can get the Focus.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class Test extends JFrame
      public Test()
        setLocation(400,300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JPanel panel1 = new JPanel(new BorderLayout());
        JPanel panel2 = new JPanel(new BorderLayout());
        ImagePanel imgPanel = new ImagePanel();
        panel1.setFocusable(true);
        panel2.setFocusable(true);
        panel1.setPreferredSize(new Dimension(0, 50));
        panel2.setPreferredSize(new Dimension(0, 50));
        panel1.setBorder(BorderFactory.createLineBorder(Color.RED,     4));
        panel2.setBorder(BorderFactory.createLineBorder(Color.CYAN,    4));
        imgPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK, 4));
        panel1.add(new JLabel("Panel 1"), BorderLayout.CENTER);
        panel2.add(new JLabel("Panel 2"), BorderLayout.CENTER);
        getContentPane().add(panel1, BorderLayout.NORTH);
        getContentPane().add(panel2, BorderLayout.SOUTH);
        getContentPane().add(imgPanel, BorderLayout.CENTER);   
        pack();
        panel1.addKeyListener(new KeyAdapter(){
            public void keyPressed(KeyEvent ke){
                System.out.println("Panel1");}});
        panel2.addKeyListener(new KeyAdapter(){
            public void keyPressed(KeyEvent ke){
                System.out.println("Panel2");}});
      public static void main(String[] args){new Test().setVisible(true);}
    class ImagePanel extends JPanel
      Image img;
      public ImagePanel()
        setFocusable(true);
        setPreferredSize(new Dimension(400,300));
        try{img = javax.imageio.ImageIO.read(new java.net.URL(getClass().getResource("Test.gif"), "Test.gif"));}
        catch(Exception e){/*handled in paintComponent()*/}
        addKeyListener(new KeyAdapter(){
          public void keyPressed(KeyEvent ke){
            System.out.println("ImagePanel");}});
      public void paintComponent(Graphics g)
        if(img != null)
          g.drawImage(img, 0,0,this.getWidth(),this.getHeight(),this);
        else
          g.drawString("This space for rent",50,50);
    }

  • How to place a JPanel at the center of another JPanel?

    Can anyone tell me how to place a JPanel inside another JPanel? The first JPanel consists of three JPanels each consisting of a label&textfield and are placed using BoxLayout. The second JPanel is a big blank screen. So, i would like to put the first JPanel at the center of second JPanel(horizontally & vertically). The problem is that i don't have any other component. So,if i try to use FlowLayout, i am able to put it at the center(horizontally, not vertically) only on the top edge. I tried to use BoxLayout. But, i couldn't(as i don't have any other elements). I tried to create some blank elements. But, they are messing up the elements of my JPanel. Any cluesssssssss??????????

    import java.awt.*;
    import javax.swing.*;
    public class CenteredLayout
        private JPanel getPanel()
            GridBagLayout gridbag = new GridBagLayout();
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(2,2,2,2);
            JPanel p = new JPanel(gridbag);
            addComponents(new JLabel("label 1"), new JTextField(8), p, gbc);
            addComponents(new JLabel("label 2"), new JTextField(8), p, gbc);
            addComponents(new JLabel("label 3"), new JTextField(8), p, gbc);
            JPanel panel = new JPanel(gridbag);
            panel.setBackground(Color.pink);
            gbc.anchor = GridBagConstraints.CENTER;
            gbc.insets = new Insets(0,0,0,0);
            panel.add(p, gbc);
            return panel;
        private void addComponents(Component c1, Component c2, Container c,
                                   GridBagConstraints gbc)
            gbc.anchor = GridBagConstraints.EAST;
            gbc.gridwidth = GridBagConstraints.RELATIVE;
            c.add(c1, gbc);
            gbc.anchor = GridBagConstraints.WEST;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            c.add(c2, gbc);
        public static void main(String[] args)
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new CenteredLayout().getPanel());
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • Calling a method on a jFrame from a jPanel that created by the jFrame

    Hi all
    I can not for the life of me work out how to do this.
    Calling a method on a jFrame from a jPanel that created by the jFrame.
    I have used this code to set a handle for one jPanel to another.
    i.e I can create new jpanel and pass in handles from one to another but not back to the jFrame.
    // this is sudo code
      private Panel_Top topPanel;
      private Menu_Panel menuPanel;
      private DataPanel dataPanel;
    //create new
        topPanel = new Panel_Top();
        menuPanel = new Menu_Panel();
        dataPanel = new DataPanel();
    // add handles from one to another
        menuPanel.setDataPanel(dataPanel);
        topPanel.setDataPanel(dataPanel);
        topPanel.setMenu_Panel(menuPanel);
        dataPanel.setMenu_Panel(menuPanel);
    // in each class I use this to set
      public void setDataPanel(DataPanel dataPanel) {
        this.dataPanel = dataPanel;
      }But I can not seam to get a handle back to the jFrame that created it.
    Please help
    as you can see I am trying but no luck so far
    Thanks

    class Life extends JPanel{
          pulic Life( JFrame owner )
                owner.doSomething(); // pass the JFrame to the constructor and feel free to use it
    }[code[                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How to create report from report painter??

    Hi,
    how to create report from report painter?? from transaction code GRR1

    Select the library that you want report to create.  GRR1
    You select what to list in coulumns and what to lisr in rows. You could select characteristics or key figures.
    You can use variable both in defininig row and coulmn or in general selection.
    You can also use sets as variable or as constant. These sets can be your master data groups or sets in GS02.
    You can use formulas.

  • How to add 3 jpanels into 1principal jpanel

    Hi, I have a situation with some panels:
    there are 3 jpanels, each one has 3 jbuttons inside; and there is 1 jpanel that contains a JLabel with an image.
    My question is:
    How can I put into the jpanel ppal the 3 jpanels with button; and then this jpanel container put into the main jframe class?
    Regards

    study and learn the Swing layout managers. you can find a decent tutorial on this on the Sun tutorial site.

  • How to make a ScrollPaneLayout that only scrolls vertically?

    I wish to put a number of JTextPanes in a JPanel that is then inside of a JScrollPane which in turn is inside of a JFrame of arbitrary size. Absent the JScrollPane, if you were to narrow the JFrame, the JTextPanes would wrap their text so that they still fit, at least until you run out of vertical space. So, I want to introduce the JScrollPane to create an endless amount of vertical space, but I still want the horizontal space constrained to the size of the JFrame.
    How can I do this? Setting the horizontalScrollPolicy to NEVER simply makes it so the horizontal scrollbar never appears even though the underlying content is still allowed to lay itself out wider than the viewport. Looking at the Javadocs for ScrollPaneLayout and JViewport doesn't turn up anything useful.

    I've tried extending JPanel as shown below and using that as my container for all the JTextPanes and the component that is then the child of the JScrollPane, and it seems to work. I just wish I had some sample implementation of the first 3 methods, particularly the first one.
    public class VerticalScrollPanel extends JPanel implements Scrollable {
    public Dimension getPreferredScrollableViewportSize() {
    return null;
    public int getScrollableUnitIncrement(Rectangle rectangle, int i, int i1) {
    return 1;
    public int getScrollableBlockIncrement(Rectangle rectangle, int i, int i1) {
    return 20;
    public boolean getScrollableTracksViewportWidth() {
    return true;
    public boolean getScrollableTracksViewportHeight() {
    return false;
    }

Maybe you are looking for

  • WWI Server configuration for EHS

    Dear Experts, First time i have sucessfully installed and started the EHS in my Server, but after installing MS Word in my server i have uninstalled teh EHS and installed again in my server but this time EHS service is not running it is giving the fo

  • Transferring music from one account to another on the same computer

    Set up a second itunes account on a different computer user. How do I transfer the music from the original account to the second account?

  • Change iCloud Email ID

    i have succesfully changed my Apple ID, as I left the company associated to this email ID (NEVER use work email for your Apple ID !).  How on earth do i now change the User Name ID previously set up with the old User Name/Email ID on my iCloud ID....

  • Stoping VI inbetween when program seeking data from serial port.

    I have an application in which I need to read data from two serial port one after other. One read will read 14 byte and other 08 bytes(Just info). Now in between if user need to stop the VI then how to stop it? Kudos are always welcome if you got sol

  • FCPX or Premier?  Ouch

    2 years ago, our non-profit organization started producing videos for broadcast on our local NBC affiliate.  Two professional mentors (both in our town, both do major national work, one is a multi-million dollar company) told us to use FCP7 (or they