JLabel ImageIcon not opaque.

Hi I am having a little problem with my program that I am trying to develop.
I have created a JFrame and instead of having the background the usual grey I have used an image.
I then wanted to create some nice big buttons with nice smooth curved edges but was having trouble using the JButton so decicded to use a JLabel and attach a MouseListener to it. This seems to be working fine at the mo.
The only problem is that instead of my nice gradient filled background being displayed I get a big white border around the JLabel. The rest of the background is perfectly displayed having only a problem around the JLabel. I have tried not using a background image and it shows the JLabel correctly and the button looks nice and smooth.
I think it might be something to do with the rendering sequence maybe but I am at a loss. If any one has any ideas on how to fix it or a better way of doing it I would be most grateful.
Many thanks for your help in advance.
Matt
PS now heres my code:
public class GUI extends JFrame implements MouseListener {
     ImageIcon icon;
     JPanel buttonPanel = new JPanel();
     public GUI(){
          super("Property Works - Estate Agent Management System");
          icon = new ImageIcon("images/bg.jpg");
          JPanel panel = new JPanel(){
               protected void paintComponent(Graphics g){
                    //g.drawImage(icon.getImage(), 0, 0, null);
                    Dimension d = getSize();
                    //g.drawImage(icon.getImage(), 0, 0, d.width, d.height, null);                    
                    super.paintComponent(g);                    
          panel.setOpaque(false);
          addButton();
          panel.add(buttonPanel);
          getContentPane().add(panel);
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          setExtendedState(JFrame.MAXIMIZED_BOTH);
          setVisible(true);
     public void addButton(){
          ImageIcon icon1 = new ImageIcon("images/buttons/addProperty.gif");
          JLabel addProperty = new JLabel(icon1);
          addProperty.setOpaque(false);
          addProperty.setToolTipText("Add a new property");
          addProperty.addMouseListener(this);
          JLabel tester = new JLabel("Tester");
          tester.setOpaque(false);
          buttonPanel.add(addProperty);
          buttonPanel.add(tester);     
     public void mousePressed(MouseEvent arg0) {
          // TODO Auto-generated method stub
          System.out.println("Button Clicked");
}

Swing related questions should be posted in the Swing forum.
Use the "code" tags when you post code so the formatting is retained.
The code you posted doesn't compile so we can't see the incorrect behaviour.
Using code I already have I do not see any white border around the image. I tested using a "Duke" image which is found in many of the Swing tutorial examples. Maybe your image is the problem.

Similar Messages

  • Update of jlabel does not happen when i wait for thread to finish (join())

    gurus please help.
    I have a main application which in actionevent calls a thread, that thread calls parent method to update ths status in jlabel, but when i use thread.join() to wait for process to complete, the jlabel does not get updated, please tell me how can i update the jlabel, i have to wait for thread to finish and during run i need to update the jlabel.
    thanks

    hi camickr and gurus:
    here is the code:
    notice after pressing the Process button, the label is being updated but its not working. I called the processnow() method directly and also by thread, but in thread I have to wait until it finishes using join() but still does not work, please help. Thanks
    package label;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.text.*;
    import javax.swing.border.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    public class thePanel extends JDialog {
      private DefaultTableModel tableModel = null;
      private JTable theTable = new JTable();
      private JScrollPane scrollPane = new JScrollPane();
    JPanel tPanel = new JPanel();
      private Border mainBorder;
      private BorderLayout borderLayout1 = new BorderLayout();
      private BorderLayout borderLayout2 = new BorderLayout();
      private BorderLayout borderLayout3 = new BorderLayout();
      private BorderLayout borderLayout4 = new BorderLayout();
      private JPanel statusPanel = new JPanel();
      private JPanel buttonPanel = new JPanel();
      private JPanel lowerPanel = new JPanel();
      private JLabel statusBar = new JLabel();
      private JButton processButton = new JButton("Process");
      public JButton closeButton = new JButton("Close");
      boolean image = true;
      theProcess processThread;
      Vector tableData = new Vector();
      ImageIcon Image = new ImageIcon("image.gif");
      ImageIcon oImage= new ImageIcon("oimage.gif");
      boolean errorOcurred=false;
      String statusMessage;
      public thePanel() {
        try {
         jbInit();
        } catch(Exception e) {
          e.printStackTrace();
      private void jbInit() throws Exception {
        tPanel.setPreferredSize(new Dimension(800,424));
        mainBorder = new TitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED)," ");
        statusPanel.setBorder(BorderFactory.createEtchedBorder());
        tPanel.setBorder(mainBorder);
        tPanel.setLayout(borderLayout1);
        scrollPane.getViewport().add(theTable, null);
        tPanel.add(scrollPane,  BorderLayout.CENTER);
        // status
        statusPanel.setLayout(borderLayout2);
        statusPanel.setBorder(BorderFactory.createEmptyBorder());
        statusBar.setAlignmentX((float) 0.5);
        statusBar.setBorder(BorderFactory.createLoweredBevelBorder());
        statusBar.setMaximumSize(new Dimension(600, 21));
        statusBar.setMinimumSize(new Dimension(600, 21));
        statusBar.setPreferredSize(new Dimension(600, 21));
        statusPanel.add(statusBar, BorderLayout.SOUTH);
        // buttons
        processButton.setPreferredSize(new Dimension(70,25));
        processButton.addActionListener(new java.awt.event.ActionListener() {
          public void actionPerformed(ActionEvent e) {
            process_actionPerformed(e);
        closeButton.setPreferredSize(new Dimension(70,25));
        buttonPanel.setLayout(borderLayout3);
        buttonPanel.setBorder(BorderFactory.createRaisedBevelBorder());
        buttonPanel.add(processButton,BorderLayout.WEST);
        buttonPanel.add(new JPanel());
        buttonPanel.add(closeButton,BorderLayout.EAST);
        // lower panel
        lowerPanel.setLayout(borderLayout4);
        lowerPanel.setBorder(BorderFactory.createEmptyBorder());
        lowerPanel.add(statusPanel, BorderLayout.WEST);
        lowerPanel.add(buttonPanel, BorderLayout.EAST);
        tPanel.add(lowerPanel, BorderLayout.SOUTH);
        theTable.setAutoCreateColumnsFromModel(true);
        theTable.setColumnSelectionAllowed(false);
        theTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        theTable.getTableHeader().setReorderingAllowed(false);
    getContentPane().add(tPanel);pack();
        getinfo();
    show();
      private void prepairTable(){
        tableModel = new DefaultTableModel(){
                          public boolean isCellEditable(int row, int col)
                            { return false; }};
        tableModel.addColumn("text 1");
        tableModel.addColumn("text 2");
        tableModel.addColumn("text 3");
        tableModel.addColumn("text 4");
        tableModel.addColumn("text 5");
        theTable.setModel(tableModel);
      } // end method (prepairTable)
      public void refreshTable() {
        prepairTable();
      public void getinfo() {
        try {
            refreshTable();
            tableModel.addRow(new Object[]{"3465465555","0123456789",new Date(1135022905196L),"0100000","errror message","sssssss"});
            tableModel.addRow(new Object[]{"8949344562","0324354549",new Date(1134511763683L),"0166600","errror mes666e","ddddddd"});
    setStatusMessage("ready to process, select record and click Process button to process record");
          errorOcurred = false;
        } catch (Exception ex) {
          errorOcurred = true;
          ex.printStackTrace();
        } // End try
      private void process_actionPerformed(ActionEvent e) {
        try {
          if(theTable.getSelectedRows().length > 0) {
    //        processThread = null;
    //        processThread = new theProcess(this);
    //        processThread.start();
    processnow();
            System.out.println("........finished now.........");
          } else {
        } catch (Exception ex) {
          ex.printStackTrace();
      public void processnow() {
        try {
          int[] selectedRows = null;
          int totalSelected = 0;
          setStatusMessage("processing " + totalSelected + " selected records...");Thread.sleep(1500);
          selectedRows = theTable.getSelectedRows();
          totalSelected = selectedRows.length;
          for(int i = 0; i < totalSelected ; i++){
            setStatusMessage("processing " + (i+1) + " of " + totalSelected + " selected records...");
            System.out.println(".......................row: "+selectedRows);
    Thread.sleep(2500);
    System.out.println("........fins...........");
    errorOcurred = false;
    } catch (Exception ex) {
    errorOcurred = true;
    ex.printStackTrace();
    } // End try
    public void setStatusMessage(String message) {
    statusMessage=message;
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    if(image)
    statusBar.setIcon(Image);
    else
    statusBar.setIcon(oImage);
    statusBar.setText(statusMessage);
    statusBar.update(statusBar.getGraphics());
    public static void main(String[] args){
    new thePanel();
    } // class
    package label;
    import java.lang.Runnable;
    public class theProcess implements Runnable {
    private thePanel parent;
    public theProcess(thePanel xparent){
    parent = xparent;
    } // end constructor
    public void start() {
    try {
    Thread thisThread = new Thread(this);
    thisThread.start();
    thisThread.join();
    } catch(Exception ex) {
    ex.printStackTrace();
    } // end method (start)
    public void run(){
    try {
    parent.processnow();
    } catch (Exception ex){
    ex.printStackTrace();
    } // end try
    } // end method (run)
    } // end class

  • Painting on a layer but the paint is not opaque..it is pale and transparent.  How can I get paint to be more intense and opaque to cover part of the picture?  I have a MAC and updated Photoshop CC.

    Why is any paint color I choose with paint brush not opaque while painting on a layer?  I want to cover or paint part of a picture on the first layer.  Using MAC and latest Photoshop CC

    Reset the Paint Tool as shown in the screenshot:
    If you are painting on a Layer, check the Opacity and Blend mode in the Layers Panel.  Blend Mode: Normal  Opacity and Fill: 100%
    Gene

  • The upper part of the page is not opaque, and the desktop shows through. Thus, the menu bar is hard to read. How to remedy this?

    The area behind the menu bar and the line above it, all the way across to the minimize, maximize and close icons is not opaque and the desktop and desktop icons show through. There is nothing I can find in Firefox Help to change this. Also, it would be nice if the menu bar could be made larger and more visible -- and if I could delete "Yahoo!" from the menu bar, leaving just the important items (File, Edit, View, History, Bookmarks, Tools, and Help). Any suggestions?

    See:
    *[[/questions/804050]]
    Right click in a free space on your desktop.<br />
    Left click on Personalization.<br />
    There are four options in Windows 7 at the bottom of the screen, choose "Window Color and Appearance".<br />
    Select a border color<br />
    Uncheck: "Enable transparency"<br />

  • Which is better for drawing JPGs on JLabel: ImageIcon or directly?

    I'm currently using this everywhere.
    BufferedImage bi;
    Jlabel jLabel;
    ImageIcon img = new ImageIcon( bi );
    jLabel.setIcon(imgIcon);but now I've discovered I can write images directly to the component from paintComponent( Graphics g )
    (from a subclass of JLabel)
    public void paintComponent( Graphics g ) {
      super.paintComponent( g );
      Graphics2D g2 = (Graphics2D)g;
      BufferedImage bi=getBufImg();
      g2.drawImage(bi, 0, 0, this.getWidth(), this.getHeight(), null );Is this more efficient or better form? Should I update my code everywhere?
    Also, the latter method seems to work the first time I call it, but I can't seem to change the image on an event like mouseEnter using code like this:
    public void mouseEntered(MouseEvent e) {
      Graphics g = this.getGraphics();
      Graphics2D g2 = (Graphics2D)g;
      BufferedImage bi=getBufImg();
      g2.drawImage(bi, 0, 0, this.getWidth(), this.getHeight(), null );
    }what's wrong?

    Is this more efficient or better form?
    No.
    Should I update my code everywhere?
    It depends on what you want to do. If you want to show an image then ImageIcon is an easy way. Override paintComponent when you want to do something other than simply display the image, eg, write text on top of the image or alter the image with things like rotation and scaling.
    Also, the latter method seems to work the first time I call it, but I can't seem to change the image on an event like mouseEnter using code like this
    Don't put painting code inside event code. Painting/drawing code belongs in an appropriate painting method. Use member variables in the enclosing class for state, manipulate these from your event code and set up your painting method to be able to accurately render this state at any time.
    stephensk8s is correct about the mouseEntered method. It works for components. So using a simple JLabel with ImageIcon is a carefree way to achieve rollover affects.
    Creating this kind of thing for custom graphics and images takes a little more effort. It all depends on what you are trying to do.
    Is there a good place to go to get a better understanding of this, or just ask on this forum?
    Ask when you need help.
    Resources that may be helpful to get started:
    Lesson: Writing Event Listeners
    Lesson: Performing Custom Painting
    How to Use Icons
    Lesson: Working with Images
    Core Java Technologies Tech Tips.

  • My Top Bar is Not Opaque.

    My top bar is not opaque. Why? It's just like Tiger. How can I make it opaque?

    http://discussions.apple.com/thread.jspa?threadID=1197590&start=0&tstart=0

  • How to check if JComponent is JLabel or not??

    I would need just a little check if a certain JComponent variable is a JLabel or not.
    I know JLabel is a subclass of JComponent but don't have any ideas.
    How to do that?
    Is there some method like:
    JComponent component;
    component.isLabel();Thanks for you help!!!!

    Provide a sampleok!
         Paint scaleGradient(Paint paint,View view){
              if (view.scale!=100){
                   if (GradientPaint.class.isInstance(paint) ){
                        GradientPaint gp = (GradientPaint)paint;
                        Point2D p1 = gp.getPoint1();
                        Point2D p2 = gp.getPoint2();
                        double scale = ((double)view.scale)/100;
                        p1 = new Point2D.Double(p1.getX()*scale,p1.getY()*scale);
                        p2 = new Point2D.Double(p2.getX()*scale,p2.getY()*scale);
                        paint = new GradientPaint(p1, gp.getColor1(), p2, gp.getColor2(), gp.isCyclic());     
                   else if (Radial.isRadial(paint))
                        paint = Radial.scale(paint, view.scale);
              return paint;
         }This snippet is from some paint code. Painting a shape, possibly with a gradient fill. If the view scale is not 100%, then the gradient needs scaling. But the Paint might be just a Color, or a GradientPaint, or a RadialGradientPaint. So isInstance( ) is used to find which.

  • JLabel / ImageIcon fitting issue

    I am importing a banner into my gui program on a JLabel,
    banner = new JLabel(new ImageIcon(getClass().getResource(
                             "logo.png")));
                   banner.setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1,
                             Color.BLACK));The problem is the issue with the inconsistency of the image being centered. I open the program five times and the banner fits differently almost everytime. Sometimes its shifted 5 pixels left or 3 pixels right and such.
    1. Could it be an issue with JLabel -> ImageIcon importing?
    2. frame.pack(); shifts it?
    Thanks in advance.

    I used netbeans to create the form.
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addComponent(jLabel1)I put the label at 0,0 on the frame.

  • ImageIcon not displaying anything

    Hi all, i have the following code which is supposed to display an image but basically isnt, does anyone have any idea why?
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.Image.*;
    import java.awt.Graphics.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.Vector;
    import java.util.StringTokenizer;
    import java.util.*;
    import java.lang.*;
    public class connectFour extends JPanel implements ActionListener
    private JButton aDrop, bDrop, cDrop, dDrop, eDrop, fDrop, gDrop, exitButton, changePlayers;
    private String whosTurn;
    private int playerOneScore, playerTwoScore, aHeight, bHeight, cHeight, dHeight, eHeight, fHeight, gHeight, moveCounter;
    private JLabel turnLabel, picture, playerOneNameLabel, playerTwoNameLabel, moveCounterLabel, moveLabel, whosTurnLabel, vsLabel;
    public String playerOneName, playerTwoName;
    public static String CHANGE = "change";
    public static String EXIT = "exit";
    public static String A = "a";
    public static String B = "b";
    public static String C = "c";
    public static String D = "d";
    public static String E = "e";
    public static String F = "f";
    public static String G = "g";
         public connectFour()
         //Gridbag Initial Settings
            GridBagConstraints c = new GridBagConstraints();
            c.anchor = GridBagConstraints.LINE_START;
            c.insets = new Insets(1,5,1,1); 
            //Create Panes
                JPanel mainPane = new JPanel();
            mainPane.setLayout(new GridBagLayout());
           JPanel gamePane = new JPanel();
              gamePane.setBorder(BorderFactory.createTitledBorder("Game Board"));
            gamePane.setLayout(new GridBagLayout());
           JPanel scorePane = new JPanel();
              scorePane.setBorder(BorderFactory.createTitledBorder("Score"));
            scorePane.setLayout(new GridBagLayout());
           JPanel buttonPane = new JPanel();
            buttonPane.setLayout(new GridBagLayout());
            JPanel rightPane = new JPanel();
            rightPane.setLayout(new GridBagLayout());
            JPanel leftPane = new JPanel();
            leftPane.setLayout(new GridBagLayout());
    // ----------------------------------------------here is the ImageIcon stuff ---------       
            ImageIcon board = new ImageIcon("images//gameboard.jpg");
            picture = new JLabel(board);
            c.gridx=1;
            c.gridy=2;
            c.weightx=7.0;
            gamePane.add(picture, c);
            aDrop = new JButton("A");
            c.gridx = 1;
            c.gridy = 1;
            gamePane.add(aDrop, c);
            bDrop = new JButton("B");
            c.gridx = 2;
            c.gridy = 1;
            gamePane.add(bDrop, c);
            cDrop = new JButton("C");
            c.gridx = 3;
            c.gridy = 1;
            gamePane.add(cDrop, c);
            dDrop = new JButton("D");
            c.gridx = 4;
            c.gridy = 1;
            gamePane.add(dDrop, c);
            eDrop = new JButton("E");
            c.gridx = 5;
            c.gridy = 1;
            gamePane.add(eDrop, c);
            fDrop = new JButton("F");
            c.gridx = 6;
            c.gridy = 1;
            gamePane.add(fDrop, c);
            gDrop = new JButton("G");
            c.gridx = 7;
            c.gridy = 1;
            gamePane.add(gDrop, c);
            // Laying out all the panels
            c.gridx=0;
            c.gridy=0;
            leftPane.add(gamePane, c);
            // there are more Panes and things in them but they are not relivant to this
            c.gridx=0;
            c.gridy=0;
            add(mainPane);
    public void actionPerformed(ActionEvent e) {
         String cmd = e.getActionCommand();
             if (EXIT.equals(cmd)) {
             System.exit(0);
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
            private static void createAndShowGUI() {
            //Make sure we have nice window decorations.
            JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("header");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            final connectFour newContentPane = new connectFour();
            newContentPane.setOpaque(true); //content panes must be opaque
            frame.setContentPane(newContentPane);
            //Make sure the focus goes to the right component
            //whenever the frame is initially given the focus.
            frame.addWindowListener(new WindowAdapter() {
                public void windowActivated(WindowEvent e) {
            //Display the window.
            frame.pack();
            frame.setSize(650,400);
            frame.setLocation(400,300);
            Image img = Toolkit.getDefaultToolkit().getImage("images\\icon.jpg");
            frame.setIconImage(img);
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
    }

    never mind, I fixed it :-)

  • Resized animated gif ImageIcon not working properly with JButton etc.

    The problem is that when I resize an ImageIcon representing an animated gif and place it on a Jbutton, JToggelButton or JLabel, in some cases the image does not show or does not animate. More precicely, depending on the specific image file, the image shows always, most of the time or sometimes. Images which are susceptible to not showing often do not animate when showing. Moving over or clicking with the mouse on the AbstractButton instance while the frame is supposed to updated causes the image to disappear (even when viewing the non-animating image that sometimes appears). No errors are thrown.
    Here some example code: (compiled with Java 6.0 compliance)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Test
         public static void main(String[] args)
              new Test();
         static final int  IMAGES        = 3;
         JButton[]           buttons       = new JButton[IMAGES];
         JButton             toggleButton  = new JButton("Toggle scaling");
         boolean            doScale       = true;
         public Test()
              JFrame f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JPanel p = new JPanel(new GridLayout(1, IMAGES));
              for (int i = 0; i < IMAGES; i++)
                   p.add(this.buttons[i] = new JButton());
              f.add(p, BorderLayout.CENTER);
              f.add(this.toggleButton, BorderLayout.SOUTH);
              this.toggleButton.addActionListener(new ActionListener() {
                   @Override
                   public void actionPerformed(ActionEvent e)
                        Test.this.refresh();
              f.setSize(600, 300);
              f.setVisible(true);
              this.refresh();
         public void refresh()
              this.doScale = !this.doScale;
              for (int i = 0; i < IMAGES; i++)
                   ImageIcon image = new ImageIcon(i + ".gif");
                   if (this.doScale)
                        image = new ImageIcon(image.getImage().getScaledInstance(180, 180, Image.SCALE_AREA_AVERAGING));
                   image.setImageObserver(this.buttons);
                   this.buttons[i].setIcon(image);
                   this.buttons[i].setSelectedIcon(image);
                   this.buttons[i].setDisabledIcon(image);
                   this.buttons[i].setDisabledSelectedIcon(image);
                   this.buttons[i].setRolloverIcon(image);
                   this.buttons[i].setRolloverSelectedIcon(image);
                   this.buttons[i].setPressedIcon(image);
    Download the gif images here:
    http://djmadz.com/zombie/0.gif
    http://djmadz.com/zombie/1.gif
    http://djmadz.com/zombie/2.gif
    When you press the "Toggle scaling"button it switches between unresized (properly working) and resized instances of three of my gif images. Notice that the left image almost never appears, the middle image always, and the right image most of the time. The right image seems to (almost) never animate. When you click on the left image (when visble) it disappears only when the backend is updating the animation (between those two frames with a long delay)
    Why are the original ImageIcon and the resized ImageIcon behaving differently? Are they differently organized internally?
    Is there any chance my way of resizing might be wrong?

    It does work, however I refuse to use SCALE_REPLICATE for my application because resizing images is butt ugly, whether scaling up or down. Could there be a clue in the rescaling implementations, which I can override?
    Maybe is there a way that I can check if an image is a multi-frame animation and set the scaling algorithm accordingly?
    Message was edited by:
    Zom-B

  • JLabel components not being displayed on the content Panel in Applet

    Hi everyone!!
    Plz give a solution to the following problem:
    I have an applet in which i have JPanel component and on that component i am adding a lot of JLabel components but the problem is that the JLabel components are not displayed on the applet unless i minimize or maximize the applet.
    kindly give solution to the problem.
    Thanks

    Howdy,
    code would be helpful. Here is a very simple JApplet that displays labels okay here in appletviewer. You talk of applets and JLabels. I assume you are using JApplets.
    import javax.swing.*;
    import java.applet.*;
    import java.awt.*;
    public class AppletPie extends JApplet {
         public void init() {
              Container cp = getContentPane();
              cp.setLayout(new FlowLayout());
              cp.add(new JLabel("Show"));
              cp.add(new JLabel("up"));
              cp.add(new JLabel("you"));
              cp.add(new JLabel("dumb"));
              cp.add(new JLabel("labels"));
    }Perhaps something in this code will help you to solve your problem.
    regards
    sjl

  • JLabel do not Appear On JPanel

    Help! PPl I am upto my eyes in this problem and I cannot solve it.
    I have a JFrame with BorderLayout on which I have 2 JPanels.The JPanel on the SOUTH of borderLayout is called secPanel and the one at the CENTER is called newPanel.
    On newPanel I am basically trying to make a lot of squares appear some should be whit and some black which is based on a random calculation. I have put in a lot of time on this and it worked on the first go and now it does not seem to work after I changed some code which I cannot recall what I did wrong. Now all the calculcations work out fine and everything only the squares which are really JLabels with a single space character in them are not displayed . The main file proj.java and the file that contains class aSquare are give below can someone please have a look and tell me how can I do it RIGHT! PLEASE
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class proj
         public static void main(String args[])
              JFrame aFrame= new JFrame("This is a Test");
              aFrame.addWindowListener(new WindowAdapter()
              {public void windowClosing(WindowEvent e)
              {System.exit(0);
              aFrame.setSize(700,700);
              Container c = aFrame.getContentPane();
              //c.setBackground(Color.blue);
              JPanel secPanel = new JPanel();
              secPanel.setLayout(new GridLayout(1,3));
              secPanel.setBackground(Color.gray);
              secPanel.setOpaque(false);
              secPanel.setBorder(BorderFactory.createEtchedBorder());
              JButton first, second, third;
              first= new JButton("Initialise New Maze");
              second = new JButton("Random New Genes");
              third = new JButton("Run Halt Genes");
              secPanel.add(first);
              secPanel.add(second);
              secPanel.add(third);
              JPanel newPanel = new JPanel();
              newPanel.setLayout(null);
              newPanel.setOpaque(true);
              newPanel.setBorder(BorderFactory.createEtchedBorder());
              newPanel.setVisible(true);
              aSquare squares[][] = new aSquare[40][40];
              int xPos=5;
              int yPos=5;
              for(int i=0; i<40; i++)
                   yPos= yPos+10;
                   xPos=5;
                   for(int j=0; j<40;j++)
                        xPos= xPos+10;
                        squares[i][j] = new aSquare(i,j);
                        if (nZrandom()%nZrandom()== 0 && nZrandom()%nZrandom() == 0)
                             squares[i][j].changeColor(Color.black);
                             System.out.println("MAde Black"+i+" "+j);
                        squares[i][j].setBounds(xPos, yPos,10,10);
                        System.out.println(xPos+" "+yPos);
                        newPanel.add(squares[i][j]);
                   }//end for j
              }//end for i
              newPanel.setOpaque(false);
              c.add(newPanel,BorderLayout.CENTER);
              c.add(secPanel,BorderLayout.SOUTH);
              aFrame.setVisible(true);
              aFrame.show();
         }//end main
         public static int nZrandom()
              int randno =(int)(Math.random()*10);
              while (true)
                   if (randno != 0)
                        return randno;
                   }else
                        randno = (int)(Math.random()*10);
                   }//end if
              }//end while
         }//end nZrandom
    }//end class proj
    CLASS aSquare
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    class aSquare extends JLabel implements MouseListener
         private int x, y;
         private boolean wall, beenThere;
         public aSquare(int a,int b)
              super(" ");
              this.setOpaque(true);
              this.setBackground(Color.white);
              this.setToolTipText(String.valueOf(a)+","+String.valueOf(b));
              this.setVisible(true);
              this.addMouseListener(new MouseAdapter()
                   public void mousePressed(MouseEvent e)
                        if (((JLabel)e.getSource()).getBackground().equals(Color.black))
                             ((JLabel)e.getSource()).setBackground(Color.white);
                        System.out.println("You are on the Label");
                        }else
                             ((JLabel)e.getSource()).setBackground(Color.white);
                             System.out.println("You are on the Label");
                        }//end if
              int x=a;
              int y=b;
              wall= false;
              beenThere= false;
         }//end constructor;
         public void changeColor(Color change)
              this.setBackground(change);
              if (change.equals(Color.cyan))
                   this.setBeenThere(true);
              if(change.equals(Color.black))
                   this.setWall(true);
         }//end changeColor
         public void mousePressed(MouseEvent me)
         public void mouseClicked(MouseEvent me)
         public void mouseReleased(MouseEvent me){}
         public void mouseEntered(MouseEvent me){}
         public void mouseExited(MouseEvent me){}
         public int getX()
         return this.x;
         public int getY()
         return this.y;
         public boolean getBeenThere()
         return this.beenThere;
         public void setBeenThere(boolean beenThere)
         this.beenThere = beenThere;
         public boolean getWall()
         return this.wall;
         public void setWall(boolean wall)
         this.wall = wall;
    }//end class aSquare

    There seems to be some problem in getting the label to display at the proper location on the JPanel cos I just wrote short code in which I pasted a JLabel and one instance of my class aSquare here renamed to Alab .
    the label get displayed at the proper location but the instance of class Alab does not . I went through the code line by line but I cannot understand it at all.. U have been very kind and patient.. can u gimme a hand with this one...
    thanks again..
    here is the small code
    //code
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    class LabelTry
         public static void main(String args[])
              JFrame aFrame= new JFrame("This is a Test");
              aFrame.addWindowListener(new WindowAdapter()
              {public void windowClosing(WindowEvent e)
              {System.exit(0);
              aFrame.setSize(500,500);
              Container c = aFrame.getContentPane();
              JPanel secPanel = new JPanel();
              secPanel.setLayout(null);
              secPanel.setBackground(Color.gray);
              secPanel.setOpaque(true);
              secPanel.setBorder(BorderFactory.createEtchedBorder());
              JLabel aLabel = new JLabel(" ");
              aLabel.setBounds(200,200,10,10);
              aLabel.setBackground(Color.black);
              aLabel.setOpaque(true);
              aLabel.setVisible(true);
              Alab bLabel = new Alab(1,2);
              bLabel.setBounds(200,200,10,10);
              bLabel.setBackground(Color.black);
              bLabel.setOpaque(true);
              bLabel.setVisible(true);
              secPanel.add(aLabel);
              secPanel.add(bLabel);
              c.add(secPanel, BorderLayout.CENTER);
              aFrame.setVisible(true);
         }//end main
    }//end class LabelTry
    CLASS ALAB //WHICH IS NOTHING BUT class aSquare
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    class Alab extends JLabel implements MouseListener
         private int x, y;
         private boolean wall, beenThere;
         public Alab(int a,int b)
              super(" ");
              this.setOpaque(true);
              this.setBackground(Color.white);
              this.setToolTipText(String.valueOf(a)+","+String.valueOf(b));
              this.setVisible(true);
              this.addMouseListener(new MouseAdapter()
                   public void mousePressed(MouseEvent e)
                        if (((JLabel)e.getSource()).getBackground().equals(Color.black))
                             ((JLabel)e.getSource()).setBackground(Color.white);
                        System.out.println("You are on the Label");
                        }else
                             ((JLabel)e.getSource()).setBackground(Color.white);
                             System.out.println("You are on the Label");
                        }//end if
              int x=a;
              int y=b;
              wall= false;
              beenThere= false;
         }//end constructor;
         public void changeColor(Color change)
              this.setBackground(change);
              if (change.equals(Color.cyan))
                   this.setBeenThere(true);
              if(change.equals(Color.black))
                   this.setWall(true);
         }//end changeColor
         public void mousePressed(MouseEvent me)
         public void mouseClicked(MouseEvent me)
         public void mouseReleased(MouseEvent me){}
         public void mouseEntered(MouseEvent me){}
         public void mouseExited(MouseEvent me){}
         public int getX()
         return this.x;
         public int getY()
         return this.y;
         public boolean getBeenThere()
         return this.beenThere;
         public void setBeenThere(boolean beenThere)
         this.beenThere = beenThere;
         public boolean getWall()
         return this.wall;
         public void setWall(boolean wall)
         this.wall = wall;
    }//end class aSquare

  • ImageIcon not loading from Jar file

    Hi,
    I'm developing an application that uses ImageIcons in JButtons.
    The images are stored in the following relative dir:
    images/<filename>.jpg
    They load fine when I run the application from class files in the appropriate directory.
    However when I jar everything, my ImageIcons don't load.
    I know that my jar file is in the classpath, because other items in the jar file load successfully.
    I've tried everything the related threads recommend, but still nothing.
    When I try to launch from the jar file, the ClassLoader.getResource("filepath"); returns null.
    Whereas when I launch the class files, it returns the correct URL for the image.
    What am I missing? Is this jar file security-related? Do I need to sign the jar file with all-permissions?
    Any suggestions would be gratefully appreciated.
    I'm using java 1.4.2_01-b06
    Much thanks,
    -Jeroen

    Here is a little load program that you can use.
    import java.io.*;
    import java.util.*;
    import java.util.zip.*;
    * <p>Resources extracts all the resources from a jar file into binary large
    * objects. These objects can be used to create images or read as streams.
    * This class is implemented as a singleton model.</p>
    * <p>An attempt is made to find the path to the jar file in
    * if this file is not found no resources are
    * loaded.
    * @author Michael Couck
    * @version 1.00, 16/01/2004
    public final class Resources extends Constants {
          * The only instance of this class
         private static Resources resources;
          * Hashtables for the sizes of the entries in the jar
         private static Hashtable sizes= new Hashtable();
          * Hashtable for each entry in the jar as a blob
         private static Hashtable contents= new Hashtable();
          * Flag to test if the resources were loaded correctly
         private static boolean resourcesLoaded= false;
          * Initilises the <code>static</code> instance of the
          * <code>Resources</code> instance.
         public static void initiliseResources() {
              if (resources == null)
                   resources= new Resources();
          * Instanciates a <code>Resources</code> object.
         private Resources() {
              init();
          * Returns a resource as a <code>byte</code> array, which can then be used
          * as a <code>ByteArrayInputStream</code> to instanciate among other things
          * images and property files.
          * @param name a resource name. This is the path to the recource from the
          *         root of the jar file.
         public static byte[] getResourceAsByteArray(String name) {
              if (resources == null)
                   resources= new Resources();
              return (byte[]) Resources.contents.get(name);
          * Returns true if the resources were correctly loaded
         public static boolean resourcesLoaded() {
              return resourcesLoaded;
          * Reads the jar file and inserts the contents
          * into the Hashtables.
         public void init() {
              try {
                   //Sizes into the table     
                                                                    File jar= new File("[path to]/yourjar.jar");
                   if (jar != null && jar.exists()) {
                        //Found the path to this jar file
                        ZipFile zipFile= new ZipFile(jar);
                        Enumeration enum= zipFile.entries();
                        while (enum.hasMoreElements()) {
                             ZipEntry zipEntry= (ZipEntry) enum.nextElement();
                             sizes.put(
                                  zipEntry.getName(),
                                  new Integer((int) zipEntry.getSize()));
                        zipFile.close();
                        //Contents into the table
                        FileInputStream fis= new FileInputStream(jar);
                        BufferedInputStream bis= new BufferedInputStream(fis);
                        ZipInputStream zis= new ZipInputStream(bis);
                        ZipEntry zipEntry= null;
                        while ((zipEntry= zis.getNextEntry()) != null) {
                             if (zipEntry.isDirectory()) {
                                  continue;
                             int size= (int) zipEntry.getSize();
                             // -1 means unknown size.
                             if (size == -1) {
                                  size=
                                       ((Integer) sizes.get(zipEntry.getName()))
                                            .intValue();
                             byte[] blob= new byte[(int) size];
                             int readBuffer= 0;
                             int buffer= 0;
                             while (((int) size - readBuffer) > 0) {
                                  buffer=
                                       zis.read(blob, readBuffer, (int) size - readBuffer);
                                  if (buffer == -1) {
                                       break;
                                  readBuffer += buffer;
                             contents.put(zipEntry.getName(), blob);
                        resourcesLoaded= true;
              } catch (NullPointerException e) {
                   Constants.logger.severe(e.getMessage());
                   StackTraceElement[] stackTrace= e.getStackTrace();
                   for (int i= 0; i < stackTrace.length; i++) {
                        Constants.logger.severe(stackTrace.toString());
                   resourcesLoaded= false;
              } catch (FileNotFoundException e) {
                   Constants.logger.severe(e.getMessage());
                   StackTraceElement[] stackTrace= e.getStackTrace();
                   for (int i= 0; i < stackTrace.length; i++) {
                        Constants.logger.severe(stackTrace[i].toString());
                   resourcesLoaded= false;
              } catch (IOException e) {
                   Constants.logger.severe(e.getMessage());
                   StackTraceElement[] stackTrace= e.getStackTrace();
                   for (int i= 0; i < stackTrace.length; i++) {
                        Constants.logger.severe(stackTrace[i].toString());
                   resourcesLoaded= false;
    } //End Resources
    You can get the icons with "new ImageIcon(new ByteArrayResources.getResourceAsByteArray(String name));
    See ya
    Michael

  • Help Menu Search Bar Transparency Not Opaque With Increase Contrast Option

    Hi,
    I am running OS X 10.10 and I've turned on the Reduce Transparency and the Increase Contrast options.
    I've noticed, however, that with the Increase Contrast On the background of the search bar in the Help menu is transparent again and with black text (making it even harder to read then normal). If I have only the Reduce Transparency on then it is opaque as expected. It's with both Reduce Transparency and Increase Contrast on that causes this behavior.
    Is this a bug that anyone else has experienced or is it just me? Any ideas how to fix this annoyance (other than turning off Increase Contrast)?
    Thanks

    I'm having the same problem here. Not really sure why it's not working, but checking the "synchronize with google" box seems to do nothing.

  • Background Problem (not opaque?)

    Hello,
    I apologize for being a newbie - but after reading the manual still have this issue. I am trying to make an animated matte to place over a movie (with just two identifying logos in the corner). Even though my canvas is checkered - it doesn't render or export as opaque - but black instead. From my reading this is contratry to what should be...
    Thanks in advance...

    Thank you, but unfortunately it did not work. When I select a background color (any) and set opacity to zero - still shows as black. I know how to create a matte in Photoshop, but I really want one that will animate between logos. I can't get a transparent background in Keynote either - in which case I'd export my files as QTime files and lay them over as a matte.
    I must admit I am doing these things and importing them to iMovie (with Slick plug-ins for the mattes, etc.) Would things be that much easier in FCE? I have been intimidated with it to date. Thanks for any and all suggestions.

Maybe you are looking for

  • Airport Express and IPTV Set Top Box

    I want to connect an IPTV Set Top Box to my wireless router but my provider's STB doesn't have Wireless networking. So I though to connect it to my wireless network with an Airport Express. I made a scheme of how it would be connected: Is it possible

  • Regarding Select data from *BSEG

    Hi Experts, I am studying the logic of an ABAP in which data has been fetched by a select statement like this SELECT * FROM *BSEG When i double clicked on *BSEG, system says *BSEG does not exist. Also, there is no table as *BSEG in ABAP dictionary. P

  • Addition In Calculator Application

    Hi everyone, I've got a bit of a problem. I'm busy working on a calculator that will be used in DOS. Eventually it will include the arithmetic operations as well as 5 scientific operations and convert to octal and hexadecimal. I�ve included my code b

  • Itunes sees iPad as an iPhone under the App tab...

    I'm having trouble getting iTunes to recognize the iPad as IPAD and iTunes think it's an iPhone, so essentically, it wouldn't install any iPad specific apps on my iPad. Anyone having this same problem and how to solve it? I restore it factory once an

  • Populating Array

    Hi, I'm having trouble populating a 1D array using a Replace Array Subset function. The two arrays coming from the top are two separate ones.  This program is supposed to compare two adjacent elements in one array and flows through a case structure.