Problem in setting background of jLabel when mouse is pressed on JLabel

I am working on a WindowsExplorer like application.
I have a panel with null layout.
On this panel there are several labels with icon on top and text below imageIcon.My requirement is ;
When mouse is pressed on a JLabel , I want to set the background of text on label to show that this is the selected label.what should i do ?

Use html tags:
setText"<html><fontcolor=blue>a111<br>b22222</html>");
public class MyLabel extends JLabel
     ImageIcon i1 = new ImageIcon("g1.gif");
     String    txt;
public MyLabel(String s)
     super("",JLabel.CENTER);
     txt = s;
     setText("<html><font color=blue>"+txt+"</html>");
     setIcon(i1);
     setOpaque(true);
     setBackground(Color.pink);
     setBorder(new MatteBorder(1,1,1,1,Color.black));
     addMouseListener(new MouseAdapter()     
     {     public void mousePressed(MouseEvent m)
                    setText("<html><font color=blue>"+txt+"</html>");     
}Noah
     

Similar Messages

  • Problem in Setting Background Color for JButton

    Hi,
    I am using Background color for JButton (color is selected from the customized JColorChooser created by us) where it contains the option of transparency. If we choose light color, then the background is set to JButton, but when we mouse-over the JButton, other components inside the container (JPanel) is getting displayed inside the button.
    Can anyone help to sort out this problem.
    Thanks in advance.

    Hi,
    Here is the code.
    DialogWrapper is JDialog and ColorEditorPane is JPanel.
    DialogWrapper     dlg         = new DialogWrapper();
    ColorEditorPane colorPanel = new ColorEditorPane();
    colorPanel.setValue( _data.getTransparentColor());
    dlg.showWrappedDialog( colorPanel, "color_help", "color_dialog" );
    if( dlg.isOK())
    Color chosenColor = (Color) colorPanel.getValue().getContent();
    _data.setTransparentColor( chosenColor );
    _transparentColorDisplay.setBackground( chosenColor );
    _transparentColorDisplay.setOpaque( true );
    this.repaint();
    this.doLayout();
    this.validate();
    }I've several components like JCheckBox, JRadioButton, JTextField in "this".

  • Problem while setting background color for jsplit pane

    Hi ALL,
    i am using jsplit frame inside jframe.
    i placed jtree inside left jsplit frame.
    I am not able to set background clolr to jsplit frame.
    when i hide(jtree.setvisible(false)) jtree is shows default background color.it is not showing backgroun color which i set.

    In the below code,i am adding jtree inside jscrollpane and i am adding jscrollpane inside jsplitpane.
    whenever i am setting jtree.setvisible(false),it must show background color which is i am setting for jscrollpane .but its showing default background color.
    Please help me.
    * Demo.java
    * Created on August 19, 2008, 1:44 PM
    public class Demo extends javax.swing.JFrame {
    /** Creates new form Demo */
    public Demo() {
    initComponents();
    jTree1.setVisible(false);
    jScrollPane1.setBackground(new java.awt.Color(136, 194, 252));
    jSplitPane1.setBackground(new java.awt.Color(136, 194, 252));    }
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
            jPanel1 = new javax.swing.JPanel();
            jSplitPane1 = new javax.swing.JSplitPane();
            jScrollPane1 = new javax.swing.JScrollPane();
            jTree1 = new javax.swing.JTree();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jScrollPane1.setViewportView(jTree1);
            jSplitPane1.setLeftComponent(jScrollPane1);
            org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jSplitPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 440, Short.MAX_VALUE)
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, jSplitPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 362, Short.MAX_VALUE)
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            pack();
        }// </editor-fold>
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Demo().setVisible(true);
        // Variables declaration - do not modify
        private javax.swing.JPanel jPanel1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JSplitPane jSplitPane1;
        private javax.swing.JTree jTree1;
        // End of variables declaration

  • Problem in setting background Image to TabedPane.

    Hi Pals,
    I created a JFrame which consist of some components. The structure of the added components are given below.
    1) I added a JPanel (MainPanel) with background image in a JFrame.
    2) I added a JTabbedPane with 7 tabs in the previous JPanel (MainPanel).
    3) Each tabs in the JTabbedPane having JPanel with Background Image.
    This is my Frame Structure. but i haven't problem to run in JDK1.6,1.5. It is working perfect. But when am run in lower version like 1.3 or 1.4. The design is looking bad. The JTabbedPane overlap the (MainPanel). The background image of the (MainPanel) was hided. I set setOpaque(false) for the JTabbedPane. But it also not working. How can i solve this problem.
    By,
    Mohan

    Your problems appear to stem from your choice of layout manager(s). To get better help sooner, post a [_Short, Self Contained, Compilable and Executable, Example Program (SSCCE)_|http://mindprod.com/jgloss/sscce.html] that clearly demonstrates your problem.
    To post code, use the code tags -- [code]Your Code[/code] will display asYour CodeOr use the code button above the editing area and paste your code between the {code}{code} tags it generates.
    db

  • Problem to set background color for configTable cell

    Hi All,
    I've a configTable displays some status fields, and I need to set yellow color when the status is in processing and green when finished and red when cancelled. I've searched the forum and decided to use iterator with method RENDER_CELL_START. Here are the steps that I've done.
    Step 1: wrote a new class ZCL_ACTSTAT_ITERATOR implements interface IF_HTMLB_TABLEVIEW_ITERATOR.
        this class has a private attribute ORDERS containing the search result internal table data, in the CONSTRUCTOR method I pass the search result to the attribute using the statement ME->ORDERS = ORDERS. Then in the method IF_HTMLB_TABLEVIEW_ITERATOR~RENDER_CELL_START I check the p_column_key for the status fields and then get the status value and set p_style accordingly using the following statement:
    CASE p_column_key.
        WHEN 'PREPAY_STATUS' OR 'DELVPLN_STATUS' OR 'DESIGN_STATUS'.
          READ TABLE me->orders INTO ls_order INDEX p_row_index.
          IF sy-subrc NE 0.
            EXIT.
          ENDIF.
          ASSIGN COMPONENT p_column_key OF STRUCTURE ls_order TO <col>.
          IF sy-subrc = 0.
            wf_text = <col>.
          ENDIF.
          IF wf_text = '00' OR wf_text = 'Initial'.
    *        concatenate '<font color=""red"">'
    *         WF_TEXT '</font>' into html_str.
    *        create object html_bee.
    *        html_bee->add( html = html_str ).
    *        p_replacement_bee = html_bee.        "not work either
            p_style = 'celldesign:STANDARD'.
          ELSEIF wf_text = '10' OR wf_text = 'InProcessing'.
            p_style = 'celldesign:GOODVALUE_MEDIUM'.
          ELSEIF wf_text = '20' OR wf_text = 'Finished'.
            p_style = 'celldesign:GOODVALUE_LIGHT'.
    *        p_style = 'background-color:#92D050'.
          ENDIF.
      ENDCASE.
    Step 2: In the component controller ZL_ZACT_MYO_ORDERS_IMPL, create a public attribute GV_ITERATOR type ref to the class created in step 1 (ZCL_ACTSTAT_ITERATOR), then in the controller's DO_PREPARE_OUTPUT method, get the combined context data and convert them into internal table LT_ORDERS, then create the iterator GV_ITERATOR passing LT_ORDERS, after this step, the result data can be transfered into iterator class and then be used in the RENDER_CELL_START method.
    The DO_PREPARE_OUTPUT method is like bellow:
    lr_pro ?= me->typed_context->order->collection_wrapper->get_first( ).
        WHILE lr_pro is BOUND.
          lr_pro->get_properties( IMPORTING es_attributes = ls_order ).
          if ls_order is not initial.
            append ls_order to lt_order.
          endif.
          lr_pro ?= me->typed_context->order->collection_wrapper->GET_next( ).
        ENDWHILE.
        CREATE OBJECT lc_iterator
          EXPORTING
            orders = lt_order.
        me->GV_iterator = lc_iterator.
    Step 3: in the .htm page, point iterator to controller's iterator
    <chtmlb:configTable  id                    = "Table1"
                        table                 = "//ORDER/Table"
                        iterator              = "<%= controller->GV_ITERATOR %>"
                         />
    Step 4: in the GET method of status attributes in context node ORDER, do the translation to change the status code into status description
    METHOD GET_PREPAY_STATUS
        DATA: OLD_VALUE TYPE ZACT_STATU,
              LS_STATUS TYPE ZACT_STATUS_S.
        OLD_VALUE = VALUE.
        READ TABLE GT_STATUS INTO LS_STATUS WITH KEY STATUS = OLD_VALUE.  
        "Get status description from field domain definition
        IF SY-SUBRC = 0.
          VALUE = LS_STATUS-NAME.           "Show status description
        ENDIF.
    ENDMETHOD.
    I thought I could see the status fields change their styles for different status code. But it still refuse to work, although I can debug to see that p_style really set as I expect, so I think there must have something wrong after RENDER_CELL_START, but what is it?
    Could anyone please help me sort it out or point out what's missing there or guide me the correct steps? Any post is greatly appreciated.
    Thank you!
    Jeff
    Edited by: liu jinghui on Feb 9, 2012 6:37 PM

    Hi, Jeff.
    Just don't want to cross post the same answer all over the forum. So I gave some inputs on the topic in this message: http://forums.sdn.sap.com/thread.jspa?messageID=11127647&#11127647
    Hope this will help you.

  • Problem in setting background colour for jButton.

    Hi,
    I have a jButton in which I want to set the color of the body of the button to gray. But by setting the background color, the color of only the border surrounding the button is changed to red. How can I set the color of the the body of the button to gray?

    Maxideon wrote:
    Geeze. I never though it would be so hard to upload an image. It probably has to do with your location relative to where I uploaded (are you really in India?).Yes.
    Maybe those free hosting sights that show up in my google search are only US based.photobucket was the first result in my search, but I was surprised it isn't blocked ;-)
    I went ahead and created an account with photobucket. I'm assuming all I have to do is make the album public and provide a direct link (hopefully). Otherwise I just simply give up
    [Direct Link|http://i633.photobucket.com/albums/uu51/Maxideon/Button.png]
    [Share Link?|http://s633.photobucket.com/albums/uu51/Maxideon/?action=view&current=Button.png]
    Yup, I see it now. Tends to support what I said about system L&Fs (and you agreed)... I think if I was designing it, I would want to disallow even the red border :P
    Just a nitpick, but the whole purpose of the system L&Fs being to provide a user experience consistent with different OS'es, should one even be trying to change a button background? A splash of color can always be done with an Icon.I'm going to have to agree with you on this one.If the non-system look is absolutely necessary in a Vista L&F, a paintComponent override should be a solution. Or, in case multiple buttons are to be customized, a custom UI delegate inheriting from javax.swing.plaf.basic.BasicButtonUI.
    db

  • How to get rid of widget when mouse hovers on desktop

    I am having a problem with widget appearing on desktop when mouse hovers on bottom of dock. Down left it has a cross / manage widgets. There are no ticked widgets at all when I go into manage widgets. Please help, it is driving me nuts!

    Pls ignore above post I have now found the answer.

  • Chess UI Code Posted... Problems setting the background of JLabel.

    import javax.swing.*;
    import java.awt.*;
    import javax.swing.border.*;
    class chess
         JLabel l[];
         JPanel p;
         public chess()
              l = new JLabel[65];
              p= new JPanel();
              p.setLayout(new GridLayout(8,8));
              p.setBorder(new MatteBorder(2,2,2,2,Color.black));
              for(int i = 1; i<=64; i++)
                   l[i] = new JLabel(""+i);
                   p.add(l);
              JFrame f = new JFrame ("Hello");
              f.getContentPane().add(p);
              f.setSize(500,500);
              f.setVisible(true);
         public static void main(String args[])
              new chess();
    hello, i have created an array of JLabel and i wannt to set the background of JLabel white n black.. But when i write this statement it does not work..though it shud.
              if (i%2==0)
                   l.setBackground(Color.black);
              else
                   l[i].setBackground(Color.white);
    where i am going wrong n wht is the way to do this...

    can u tell wht shud i use in the if else block coz... the output is not wht i was expecting....u nd 2 chng clr wn lb @ % 8

  • Set background color when condition applied

    hi,
    Can anybody tell me how to set background color when condition applied.
    My initial plan was to highlight a specify row(Change color) when the third column of this JTable consists of OK word.
    int rowCount = table.getRowCount();
    for(int i=0 ;i <rowCount ; i++)
    String word = table.getValueAt(i,3).toString();
    if(word.equals("Word")) {
    table.setSelectionBackground(Color.red);
    break;
    else {
    table.setBackground(getBackground());
    Thanks.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    public class TableChanges
        public TableChanges()
            String[] headers = { "column 1", "column 2", "column 3", "column 4" };
            int rows = 18;
            int cols = 4;
            String[][] data = new String[rows][cols];
            for(int row = 0; row < rows; row++)
                for(int col = 0; col < cols; col++)
                    data[row][col] = "item " + (row * cols + col + 1);
            JTable table = new JTable(data, headers);
            // add custom cell renderer to each column
            TableColumnModel columnModel = table.getColumnModel();
            for(int j = 0; j < columnModel.getColumnCount(); j++)
                TableColumn col = columnModel.getColumn(j);
                col.setCellRenderer(new CellRenderer());
            // add table model listener to listen for cell edits
            // so we can detect our special selection edit value
            // which is "word"
            TableModel tableModel = table.getModel();
            tableModel.addTableModelListener(new ModelListener(table));
            JScrollPane scrollPane = new JScrollPane(table);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(scrollPane);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
            Dimension d = scrollPane.getViewport().getSize();
            table.setRowHeight(d.height/rows);
        public static void main(String[] args)
            new TableChanges();
    class ModelListener implements TableModelListener
        JTable table;
        public ModelListener(JTable table)
            this.table = table;
        public void tableChanged(TableModelEvent e)
            int firstRow = e.getFirstRow();
            int lastRow  = e.getLastRow();
            int colIndex = e.getColumn();
            if(e.getType() == TableModelEvent.UPDATE &&
                  firstRow != TableModelEvent.HEADER_ROW &&
                  colIndex != TableModelEvent.ALL_COLUMNS &&
                  colIndex == 2)                            // column 3 only
                String value = (String)table.getValueAt(firstRow, colIndex);
                // check for our special selection criteria
                if(value.equals("word"))
                    for(int j = 0; j < table.getColumnCount(); j++)
                        CellRenderer renderer =
                            (CellRenderer)table.getCellRenderer(firstRow, j);
                        renderer.setSpecialSelection(firstRow, j);
    class CellRenderer extends DefaultTableCellRenderer
        int specRow, specCol;
        public CellRenderer()
            specRow = -1;
            specCol = -1;
        public Component getTableCellRendererComponent(JTable table,
                                                       Object value,
                                                       boolean isSelected,
                                                       boolean hasFocus,
                                                       int row, int col)
            setHorizontalAlignment(JLabel.CENTER);
            Color color = Color.black;
            if(hasFocus)
                color = Color.blue;
            else if(isSelected)
                color = Color.green.darker();
            else if(row == specRow && col == specCol)
                color = color.red;
            setForeground(color);
            setText((String)value);
            return this;
        public void setSpecialSelection(int row, int col)
            specRow = row;
            specCol = col;
    }

  • WHEN-MOUSE-DOUBLECLICK with PRE-BLOCK: what the problem ?

    I created a form master-detail with Forms 6i:
    first block using table DEPT
    second block using table EMP
    In block EMP I created a trigger PRE-BLOCK with:
    message( 'Stoping' );
    message( ' ', no_acknowledge );
    raise form_trigger_failure;
    In form level I created a trigger WHEN-MOUSE-DOUBLECLICK with.
    null;
    Yes only a NULL.
    The problem is very simple, the cursor stay in second block after the raise in PRE-BLOCK when it must stay in first block. Note that the hint displaied is the first block.
    If I remove the WHEN-MOUSE-DOUBLECLICK the problem solve.
    What Do I do to solve this problem ?

    What's the type of provider's mail server? (e.g. POP3,IMAP, or enterprise Mail for Exchange Protocol)
    have you tested by removing and re setting the account?
    Please identify your iOS version.

  • When mousing over text, the cursor flickers constantly (with each letter passed) from arrow to i-beam and back.  The problem occurs in both MS Word and Pages.  Any idea of how to resolve this annoying problem is appreciated.  System: 10.10.1

    When mousing over text, the cursor flickers constantly (with every letter passed) from arrow to i-beam and back.  The problem occurs in both MS Word 2011 and Pages.  Any idea of how to solve this annoying problem will be much appreciated.  System 10.10.1 on a MacPro (Late 2013)

    The mouse is controlled by the OS so don't guess any app other than a mouse driver or OS X itself would be able to cause this sort of flicker issue.
    Have you seen the following and is it what you are seeing? Maybe you could make a movie (Quicktime is great for this this to make a screen recording) - but not sure how to attach a movie to these discussions as mine is grayed out and can't be selected (to the right of the insert image). Here is the what I found for a search of "mouse cursor flickers os x yosemite"
         https://www.youtube.com/watch?v=ZNQ0D84DdF4
    What kind of mouse are you using? Is the mouse driver up to date if it's a third party mouse?

  • On my Mac desktop I must have changed a setting so that now when I move the mouse the open windows fly off to the sides and I can't see them. They come back when I move the mouse, but it is so annoying. How can I make the windows not disappear like that?

    On my Mac desktop I must have changed a setting so that now when I move the mouse the open windows fly off to the sides and I can't see them. They come back when I move the mouse, but it is so annoying. How can I make the windows not disappear like that?

    Click on the Hot Corners..  button and look at the four definitions.  In the picture below, if you moved the cursor to the right top of the screen, it would slide all the applications off the screen as you describe and show the desktop.  Set it to "-" to deactivate.

  • What do I do when I create a pdf and it says fatal error, there is a problem with the background task

    What do I do when I create a pdf and it says fatal error, there is a problem with the background task

    see Adobe Community: File Crashing on Output - printing/PDF/other

  • Setting up Abode Digital Editions, when I try to Authorize with my Abode id information I get the message "Activation Server Problem - check connection to the internet" when I clearly am connected to the internet ?

    Hi can anyone help me please this is driving me crazy ! I download and install Abode Digital Editions and when I try to Authorize with my Abode ID information I get the message " Activation Server Problem - check connection to the internet when I clearly am connected to the internet ?

    <moved from Downloading, Installing, Setting Up to Adobe Digital Editions>

  • Screensaver background frozen onscreen when awaking monitor

    Hi, I have noticed this issue recently and it has occurred a couple of times. Basically I have the monitor set to turn off after 15 minutes. This issue is occurring on my Mac Pro.
    My Mac is always on, just the monitor turns off. I have also set one of Snow Leopard screensaver to start after 5 minutes of no use. Recently I noticed that when my monitor is off and I move the mouse to turn it on, a static background from the screensaver appears on screen, no desktop, no dock or anything.
    After about 20 seconds, the screen disappears and my desktop is back in view and I can use my Mac. This doesn't occur all the time. I have repaired permissions and also verified the disk which appeared to be ok.
    I have recently updated to Safari 5 but that's the only change that I've made to the computer. I was getting low on free space on my 650GB Drive (30GB) so I deleted stuff and now it's at 80 gbs. Anyone else have this issue? what could be causing this?
    Any help is greatly appreciated.

    I've been having the same problem on my iMac for a while, including far before Safari 5. The screen saver will "freeze" leaving a static image on the screen. I have the time displayed, so I can tell when it happens because the time doesn't update. For example it just happened that the time said 5:23 and it's 5:30. Moving the mouse and pressing a key on the keyboard doesn't work. However I have found that if I connect with screen sharing from another Mac it wakes it up immediately.

Maybe you are looking for