JButton imageIcon problem

hello ,
i am facing a problem in changing the imageicon of jbutton in my application.
i want to change imageicon for few seconds and than again change it to original imageicon....
is it possible?????????????i have tried but after initializing button with one imageicon we are not able to change that icon again..
so what should i do...it is compulsory to change take two image for button.....
please help

Set up a Timer. You use the setIcon(...) method to change the icon. Then you start a Timer to fire in a few seconds and use the setIcon(...) method to change the image back to its original value.

Similar Messages

  • JButton.setBackground() Problem

    Hi All,
    When i apply the setBackground() Method to a JButton to set its Background, i face i Problem :
    Under Mac Os : The JButton DOSE NOT change its color,
    when i take my code to my other computer under Windows : OK, the JButton change...
    i am wondering ....
    1) Why under my Mac OS i face this problem...
    2) and Why i get two different results from a same code ??? Java is not Portable?? and independant of the OS?? or it is the swing that makes the problem???
    My code is so simple :
    MyJButton.setBackground(new Color(255,100,100));
    Thanks to any help...

    ellias2007 wrote:
    Sorry because it is the first time for me in this forum....
    thanks for any help...
    Sorry againMost of us don't like disjointed discussions or repeating effort for a problem that has already been solved elsewhere. Thanks for your reply. A link to one discussion: [http://www.java-forums.org/awt-swing/25986-jbutton-setbackground-problem.html]
    If you have cross-posts elsewhere, please post links in all of them to each other or to one central location.

  • A ImageIcon problem in Sun Java Studio Enterprise

    When I programmed with SJSE, I found a problem, let see a simple test:
        private void initComponents() {
            jButton1 = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setResizable(false);
            jButton1.setIcon(new javax.swing.ImageIcon("D:\\Sun\\JavaProjects\\test\\src\\test\\next.gif"));
            jButton1.setText("jButton1");
            getContentPane().add(jButton1, java.awt.BorderLayout.CENTER);
            pack();
        }This is for to show a picture in a button with File Path(which means you should choose a specific file on your disk).
    But,
    if I change the code into:
    private void initComponents() {
            jButton1 = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setResizable(false);
            jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/test/next.gif")));
            jButton1.setText("jButton1");
            getContentPane().add(jButton1, java.awt.BorderLayout.CENTER);
            pack();
        }The problem occurs. When I run this sample application, one exception throws:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at javax.swing.ImageIcon.<init>(ImageIcon.java:138)
    at test.NewJFrame.initComponents(NewJFrame.java:31)
    at test.NewJFrame.<init>(NewJFrame.java:17)
    at test.NewJFrame$2.run(NewJFrame.java:55)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:461)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:163)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:157)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:149)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:110)
    Could someone help me?
    Message was edited by:
    linyinlu

    No, this code was generated automatically by JSE.
    "New"->"JFrame"->Modify the property for this button->in "Icon" section-> choose the "ClassPath" and specific the icon. But it is not work.
    Today I have unstall the whole thing: JDK, JSE 8, deleted all dierctories and files and reinstalled them. But the problem is also not solved.
    Message was edited by:
    Scott
    Message was edited by:
    linyinlu

  • ImageIcon problem *Please HELP*

    Hello
    I am having problems adding an Image to this code I have tried everything I know but to no avail. Could u please give me some pointers as to what I am doing wrong.
    Thank you Michael
    The code:
    {color:#003300}package calculator;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class calculator extends JFrame {
    {color}
    {color:#003300}
    public calculator(){
    Container con = getContentPane();
    setSize(800, 600);
    con.setLayout(new GridLayout(5, 1));
    final JTextField value1, value2, sum;
    {color}
    {color:#003300}
    {color:#ff0000}ImageIcon img = new ImageIcon("images/calculator.jpg");
    JButton button = new JButton();
    button.setIcon(img);
    con.add(button);{color}
    value1 = new JTextField();
    value2 = new JTextField();
    sum = new JTextField();
    sum.setEditable(false);
    con.add(button);
    con.add(value1);
    con.add(value2);
    con.add(sum);
    JButton button1 = new JButton("Test 1");
    button1.setText("Equals");
    button1.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e)
    int val1 = Integer.parseInt(value1.getText());
    int val2 = Integer.parseInt(value2.getText());
    int val3 = val1 + val2;
    String val4 = Integer.toString(val3);
    sum.setText(val4);
    con.add(button1);
    pack();
    setVisible(true);
    }{color}

    Hello thank you for replying to my post I reposted the code in the correct way. I have tried running your code that you have provided but the image would still not show up on the screen. Is there any advice or problems that you can see with my code ? Any help is greatly appreciated.
    Thank you Michael
    /* Author Michael
    package calculator;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class calculator extends JFrame {
        private static final String CALC_IMAGE_STRING = "images/calculator.jpg";
        public calculator(){
        Container con = getContentPane();
        setSize(800, 600);
        con.setLayout(new GridLayout(5, 1));
        final JTextField value1, value2, sum;
        ImageIcon img = new ImageIcon(CALC_IMAGE_STRING);
        JButton button = new JButton(img);
        System.out.println("The File is located at " + CALC_IMAGE_STRING);
        System.out.println("image height: " + img.getIconHeight());
        con.add(button);
        value1 = new JTextField();
        value2 = new JTextField();
        sum = new JTextField();
        sum.setEditable(false);
        con.add(button);
        con.add(value1);
        con.add(value2);
        con.add(sum);
        JButton button1 = new JButton("Test 1");
        button1.setText("Equals");
        button1.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e)
            int val1 = Integer.parseInt(value1.getText());
            int val2 = Integer.parseInt(value2.getText());
            int val3 = val1 + val2;
            String val4 = Integer.toString(val3);
            sum.setText(val4);
        con.add(button1);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }

  • Remove imageicon problem!!Please help!!

    Hi!I m trying to do this:When the delete button is pressed , remove the jlabels appeared by one, from the last one to the first one!!How can i do this?I tried to do it with icon.set(null) but they all dissapear!Thank you!
    package icons;
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Icons extends Applet {
      JButton jButton1 = new JButton("a");
      JButton jButton2 = new JButton("b");
      JButton jButton3 = new JButton("c");
      JButton jButton4 = new JButton("d");
      JButton jButton5 = new JButton("e");
      JButton jButton6 = new JButton("f");
      JButton jButton7 = new JButton("g");
      JButton jButton8 = new JButton("compare");
      JButton jButton9 = new JButton("delete");
      FlowLayout flowLayout1 = new FlowLayout();
      JLabel jLabel1 = new JLabel();
      JLabel jLabel2 = new JLabel();
      JLabel jLabel3 = new JLabel();
      JLabel jLabel4 = new JLabel();
      JLabel jLabel5 = new JLabel();
      JLabel jLabel6 = new JLabel();
      JLabel jLabel7 = new JLabel();
    String s=new String();
      int i =1;
      ImageIcon myIcon1 = new ImageIcon("eikones/image1.gif");
      ImageIcon myIcon2 = new ImageIcon("eikones/image2.gif");
      ImageIcon myIcon3= new ImageIcon("eikones/image3.gif");
      ImageIcon myIcon4= new ImageIcon("eikones/image4.gif");
      ImageIcon myIcon5  = new ImageIcon("eikones/image5.gif");
      ImageIcon myIcon6 = new ImageIcon("eikones/image6.gif");
      ImageIcon myIcon7 = new ImageIcon("eikones/image7.gif");
      public void init() {
        jButton1.setPreferredSize(new Dimension(150, 25));
        jButton1.setIcon(myIcon1);
        jButton1.addActionListener(new Icons_jButton1_actionAdapter(this));
         jButton2.setPreferredSize(new Dimension(150, 25));
        jButton2.setIcon(myIcon2);
        jButton2.addActionListener(new Icons_jButton2_actionAdapter(this));
        jButton3.setPreferredSize(new Dimension(150, 25));
        jButton3.setIcon(myIcon3);
        jButton3.addActionListener(new Icons_jButton3_actionAdapter(this));
        jButton4.addActionListener(new Icons_jButton4_actionAdapter(this));
        jButton4.setPreferredSize(new Dimension(150, 25));
        jButton4.setIcon(myIcon4);
        jButton5.addActionListener(new Icons_jButton5_actionAdapter(this));
        jButton5.setPreferredSize(new Dimension(150, 25));
        jButton5.setIcon(myIcon5);
        jButton6.setPreferredSize(new Dimension(150, 25));
        jButton6.setIcon(myIcon6);
        jButton6.addActionListener(new Icons_jButton6_actionAdapter(this));
        jButton7.setPreferredSize(new Dimension(150, 25));
        jButton7.setIcon(myIcon7);
        jButton7.addActionListener(new Icons_jButton7_actionAdapter(this));
        jButton8.setPreferredSize(new Dimension(150, 25));
        jButton8.addActionListener(new Icons_jButton8_actionAdapter(this));
        jButton9.setPreferredSize(new Dimension(150, 25));
        jButton9.addActionListener(new Icons_jButton9_actionAdapter(this));
        jLabel1.getIcon();
        jLabel2.getIcon();
        jLabel3.getIcon();
        jLabel4.getIcon();
        jLabel5.getIcon();
        jLabel6.getIcon();
        jLabel7.getIcon();
        add(jButton1);
        add(jButton2);
        add(jButton3);
        add(jButton4);
        add(jButton5);
        add(jButton6);
        add(jButton7);
        add(jButton8);
        add(jButton9);
        add(jLabel1);
        add(jLabel2);
        add(jLabel3);
        add(jLabel4);
        add(jLabel5);
        add(jLabel6);
        add(jLabel7);
          public Icons()
                    this.setLayout(new FlowLayout(FlowLayout.LEFT));
      void jButton1_actionPerformed(ActionEvent e) {
       if (i==1)
          jLabel1.setIcon(myIcon1);
            else if (i==2)
         jLabel2.setIcon(myIcon1);
       else if (i==3)
          jLabel3.setIcon(myIcon1);
        else if (i==4)
            jLabel4.setIcon(myIcon1);
          else if (i==5)
            jLabel5.setIcon(myIcon1);
           else if (i==6)
            jLabel6.setIcon(myIcon1);
         else if (i==7)
         jLabel7.setIcon(myIcon1);
          s=s+jButton1.getText();
          i++;
      void jButton2_actionPerformed(ActionEvent e) {
        if (i==1)
          jLabel1.setIcon(myIcon2);
       else if (i==2)
         jLabel2.setIcon(myIcon2);
        else if (i==3)
         jLabel3.setIcon(myIcon2);
      else if (i==4)
            jLabel4.setIcon(myIcon2);
          else if (i==5)
             jLabel5.setIcon(myIcon2);
            else if (i==6)
             jLabel6.setIcon(myIcon2);
          else if (i==7)
          jLabel7.setIcon(myIcon2);
            s=s+jButton2.getText();
          i++;
      void jButton3_actionPerformed(ActionEvent e) {
        if (i==1)
         jLabel1.setIcon(myIcon3);
        else if (i==2)
          jLabel2.setIcon(myIcon3);
        else if (i==3)
          jLabel3.setIcon(myIcon3);
       else if (i==4)
        jLabel4.setIcon(myIcon3);
         else if (i==5)
            jLabel5.setIcon(myIcon3);
           else if (i==6)
            jLabel6.setIcon(myIcon3);
         else if (i==7)
          jLabel7.setIcon(myIcon3);
            s=s+jButton3.getText();
        i++;
      void jButton4_actionPerformed(ActionEvent e) {
       if (i==1)
        jLabel1.setIcon(myIcon4);
       else if (i==2)
         jLabel2.setIcon(myIcon4);
       else if (i==3)
          jLabel3.setIcon(myIcon4);
        else if (i==4)
            jLabel4.setIcon(myIcon4);
          else if (i==5)
            jLabel5.setIcon(myIcon4);
           else if (i==6)
            jLabel6.setIcon(myIcon4);
         else if (i==7)
          jLabel7.setIcon(myIcon4);
            s=s+jButton4.getText();
          i++;
      void jButton5_actionPerformed(ActionEvent e) {
        if (i==1)
          jLabel1.setIcon(myIcon5);
       else if (i==2)
         jLabel2.setIcon(myIcon5);
        else if (i==3)
         jLabel3.setIcon(myIcon5);
      else if (i==4)
            jLabel4.setIcon(myIcon5);
          else if (i==5)
             jLabel5.setIcon(myIcon5);
            else if (i==6)
             jLabel6.setIcon(myIcon5);
          else if (i==7)
          jLabel7.setIcon(myIcon5);
            s=s+jButton5.getText();
          i++;
      void jButton6_actionPerformed(ActionEvent e) {
        if (i==1)
         jLabel1.setIcon(myIcon6);
        else if (i==2)
          jLabel2.setIcon(myIcon6);
        else if (i==3)
          jLabel3.setIcon(myIcon6);
       else if (i==4)
        jLabel4.setIcon(myIcon6);
         else if (i==5)
            jLabel5.setIcon(myIcon6);
           else if (i==6)
            jLabel6.setIcon(myIcon6);
         else if (i==7)
          jLabel7.setIcon(myIcon6);
         s=s+jButton6.getText();
        i++;
      void jButton7_actionPerformed(ActionEvent e) {
       if (i==1)
        jLabel1.setIcon(myIcon7);
       else if (i==2)
         jLabel2.setIcon(myIcon7);
       else if (i==3)
          jLabel3.setIcon(myIcon7);
        else if (i==4)
            jLabel4.setIcon(myIcon7);
          else if (i==5)
            jLabel5.setIcon(myIcon7);
           else if (i==6)
            jLabel6.setIcon(myIcon7);
         else if (i==7)
          jLabel7.setIcon(myIcon7);
           s=s+jButton7.getText();
          i++;
      void jButton8_actionPerformed(ActionEvent e) {
      void jButton9_actionPerformed(ActionEvent e) {
          s="";
      jLabel4.setText(null);
    i=1;
    class Icons_jButton1_actionAdapter implements java.awt.event.ActionListener {
      Icons adaptee;
      Icons_jButton1_actionAdapter(Icons adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jButton1_actionPerformed(e);
    class Icons_jButton2_actionAdapter implements java.awt.event.ActionListener {
      Icons adaptee;
      Icons_jButton2_actionAdapter(Icons adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jButton2_actionPerformed(e);
    class Icons_jButton3_actionAdapter implements java.awt.event.ActionListener {
      Icons adaptee;
      Icons_jButton3_actionAdapter(Icons adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jButton3_actionPerformed(e);
    class Icons_jButton4_actionAdapter implements java.awt.event.ActionListener {
      Icons adaptee;
      Icons_jButton4_actionAdapter(Icons adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jButton4_actionPerformed(e);
    class Icons_jButton5_actionAdapter implements java.awt.event.ActionListener {
      Icons adaptee;
      Icons_jButton5_actionAdapter(Icons adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jButton5_actionPerformed(e);
    class Icons_jButton6_actionAdapter implements java.awt.event.ActionListener {
      Icons adaptee;
      Icons_jButton6_actionAdapter(Icons adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jButton6_actionPerformed(e);
    class Icons_jButton7_actionAdapter implements java.awt.event.ActionListener {
      Icons adaptee;
      Icons_jButton7_actionAdapter(Icons adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jButton7_actionPerformed(e);
    class Icons_jButton8_actionAdapter implements java.awt.event.ActionListener {
      Icons adaptee;
      Icons_jButton8_actionAdapter(Icons adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        Graphics g = getGraphics();
        if(s.equals("a"+"b"+"b"+"e"))
           g.drawString("ok",350,300);
              else
           g.drawString("wrong",150,300);
        adaptee.jButton8_actionPerformed(e);
    class Icons_jButton9_actionAdapter implements java.awt.event.ActionListener {
      Icons adaptee;
      Icons_jButton9_actionAdapter(Icons adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jButton9_actionPerformed(e);
    public void paint(Graphics g){
      g.setColor (back);
       g.fillRect (0,0,300,250);
       g.setColor (back1);
       g.fillRect (0,250,100,50);
      super.paint(g);
    }

    I don't really understand what you are trying to do but it is easier to write a single listener for all your buttons with code something like the following:
    ActionListener listener = new ActionListener()
        public void actionPerformed(ActionEvent e)
            JButton button = (JButton)e.getSource();
            String command = button.getActionCommand();
            if ("a".equals( command ))
                jLabel1.setIcon( null );
            else if ("b".equals( command ) )
                jLabel2.setIcon( null );
    };Another option would be to store you buttons and labels in an array. Then you would search the button array to find the index of the button clicked. Once you know this index then you can reset the label at the same index.

  • JButton dispatchEvent problem

    Hi,
    I've got JButtons in a JTable which means I have to capture the mouse events and forward them to the button.
    I do this with a mouse listener on the table, and the lines:
    buttonEvent = (MouseEvent)SwingUtilities.convertMouseEvent(table, e, button);
    button.dispatchEvent(buttonEvent);
    System.out.println(buttonEvent);
    table.repaint();where 'e' is the original mouse event. This produces, for example:
    java.awt.event.MouseEvent[MOUSE_CLICKED,(145,167),button=1,modifiers=Button1,clickCount=1]
    on
    javax.swing.JButton[,0,0,0x0,invalid,alignmentX=0.0,alignmentY=0.5 <snip> text=Delete,defaultCapable=true]but yet nothing happens to the button. Is this a coordinate problem, or am I missing something else, as I don't really know what I'm doing?
    Cheers,
    Rob

    MOUSE_CLICKED,(145,167),Well I'm guessing that you can't just convert the table coordinates and use them as the button coordinates because the button isn't that big.
    An alternative approach might be to use the doClick() method of the button.
    In case that doesn't work, here's something I've been playing with that may help:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.table.*;
    public class TableButton3 extends JFrame
         public TableButton3()
              String[] columnNames = {"Date", "String", "Integer", "Decimal", ""};
              Object[][] data =
                   {new Date(), "A", new Integer(1), new Double(5.1), "Delete1"},
                   {new Date(), "B", new Integer(2), new Double(6.2), "Delete2"},
                   {new Date(), "C", new Integer(3), new Double(7.3), "Delete3"},
                   {new Date(), "D", new Integer(4), new Double(8.4), "Delete4"}
              DefaultTableModel model = new DefaultTableModel(data, columnNames);
              JTable table = new JTable( model )
                   //  Returning the Class of each column will allow different
                   //  renderers to be used based on Class
                   public Class getColumnClass(int column)
                        return getValueAt(0, column).getClass();
              JScrollPane scrollPane = new JScrollPane( table );
              getContentPane().add( scrollPane );
              //  Create button column
              ButtonColumn buttonColumn = new ButtonColumn(table, 4);
         public static void main(String[] args)
              TableButton3 frame = new TableButton3();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
         class ButtonColumn extends AbstractCellEditor
              implements TableCellRenderer, TableCellEditor, ActionListener
              JTable table;
              JButton renderButton;
              JButton editButton;
              String text;
              public ButtonColumn(JTable table, int column)
                   super();
                   this.table = table;
                   renderButton = new JButton();
                   editButton = new JButton();
                   editButton.setFocusPainted( false );
                   editButton.addActionListener( this );
                   TableColumnModel columnModel = table.getColumnModel();
                   columnModel.getColumn(column).setCellRenderer( this );
                   columnModel.getColumn(column).setCellEditor( this );
              public Component getTableCellRendererComponent(
                   JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
                   if (hasFocus)
                        renderButton.setForeground(table.getForeground());
                         renderButton.setBackground(Color.WHITE);
                   else if (isSelected)
                        renderButton.setForeground(table.getSelectionForeground());
                         renderButton.setBackground(table.getSelectionBackground());
                   else
                        renderButton.setForeground(table.getForeground());
                        renderButton.setBackground(UIManager.getColor("Button.background"));
                   renderButton.setText( (value == null) ? "" : value.toString() );
                   return renderButton;
              public Component getTableCellEditorComponent(
                   JTable table, Object value, boolean isSelected, int row, int column)
                   text = (value == null) ? "" : value.toString();
                   editButton.setText( text );
                   return editButton;
              public Object getCellEditorValue()
                   return text;
              public void actionPerformed(ActionEvent e)
                   fireEditingStopped();
                   System.out.println( "Action: " + e.getActionCommand() );
    }

  • ImageIcon problem in a CellEditor

    Hello all,
    I'm really stacked with one anoying behavior. In my own CellEditor ImageCellEditor I wrote the following code.
    public Component getTableCellEditorComponent(
    JTable table,
    Object value,
    boolean isSelected,
    int row,
    int col) {
    if (value == null) {
    return editorComponent;
    ImageIcon imageIcon;
    if (value instanceof byte[]) {
    imageIcon = new ImageIcon((byte[])value);
    System.out.println("byte[]: " + imageIcon);
    else if (value instanceof String) {
    imageIcon = new ImageIcon(value.toString().getBytes());
    System.out.println("String: " + imageIcon);
    else {
    imageIcon = null;
    System.out.println("Null: " + imageIcon);
    ((JButton)editorComponent).setIcon(imageIcon);
    return editorComponent;
    The result of this code becomes strange, whererever message is thrown it prints "null", but the JButton editorComponent gets the image I want to show.
    Does anyone knows how it's possible? I supposed that if imageIcon is null and I set the icon of a JButton to this imageIcon, then it must be as if I had written ((JButton)editorComponent).setIcon(null);
    Please, help me to solve this "feature".

    Do you want to show your image in the table ? In this case, it is a CellRenderer you have to write...

  • ImageIcon problem

    Hi ,
    I creat a class extends Panel ( do I have to extend "JApplet"??). I try to use ClassLoader to get the source of the ImageIcon and put it as background of my JButton, but the ImageIcon doesn't display. I put multiple image file in the "images" folder , and this folder is under directory of my JAR file. Ans I also put this folder under the directory where the .class files is located.
    Here is my code:
    public class ButtonPanel extends Panel implements ActionListener {
    ButtonPanel() {
      setPanel();
    public void setPanel() {
    icon=new ImageIcon();
    icon=getMyIcon("images/theBtBacground.gif");
    MyButton = new JButton(icon);
    public ImageIcon getMyIcon(String source) {
        ImageIcon icon = null;
        URL iconURL = ClassLoader.getSystemResource(source);
        if (iconURL != null)
        icon = new ImageIcon(iconURL);
        return icon;
    }Also, I try another way to specify the image file
    public class ButtonPanel extends Panel implements ActionListener {
    ButtonPanel() {
      setPanel();
    public void setPanel() {
    URL iconURL=getURL("images/theBtBacground.gif");
    MyButton = new JButton(new ImageIcon(iconURL));
    public URL getURL(String filename) {
            URL codeBase =this.getCodeBase();
            URL url = null;
            try {
                url = new URL(codeBase, filename);
            } catch (java.net.MalformedURLException e) {
                System.err.println("Couldn't create image: badly specified URL");
                return null;
            return url;
    }but error message shows:
    "can not resovle symbol method getCodeBase()"
    I check the java. AWT.Panel library , the method getCodeBase() is there!
    Please help me. thanks.

    Here's how i accomplished a similar task. Holla back if it doesn't help !
             public ImageIcon createImageIcon(String path,String description)
                 java.net.URL imgURL = Client_2005_version1.class.getResource(path);
                 if (imgURL != null)
                     return new ImageIcon(imgURL, description);
                 else
                     System.err.println("Couldn't find file: " + path);
                     return null;
              class iconBoxClass extends JMenuItem
                   ImageIcon emoIcon = createImageIcon("cry_smile.gif",
                                                                  "emotion icon");
                   public iconBoxClass(ImageIcon eIcon)
                        eIcon = emoIcon;
              }

  • JButton display problem

    I would have thought the following would bring up two identical MainWindows, but in fact the buttons in the second one look slightly different.
    public class Main {
         public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                     setUpApp();
         private static void setUpApp() {
              MainWindow mainWindow = new MainWindow();
              MainWindow mainWindow2 = new MainWindow();
    }This is what the two windows look like after display: (How do URLs work?)
    I'm not really sure what code to paste other than this because I would think the code is identical for both.

    Slow day, and I actually created an SSCCE:
    import javax.swing.*;
    import java.awt.*;
    public class MainWindow {
       private JFrame topLevelContainer;
       public MainWindow() {
          topLevelContainer = new JFrame();
          topLevelContainer.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          topLevelContainer.setPreferredSize(new Dimension(400, 400));
          Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
          topLevelContainer.setTitle("ChatApp");
          topLevelContainer.setVisible(true);
          JPanel contentPane = new JPanel(new BorderLayout(2, 2));
          contentPane.setBorder(BorderFactory.createLineBorder(Color.BLUE));
          contentPane.setBackground(Color.BLUE);
          topLevelContainer.setContentPane(contentPane);
          JPanel sendingTo = new JPanel();
          sendingTo.setOpaque(false);
          sendingTo.setBorder(BorderFactory.createTitledBorder("Sending To"));
          contentPane.add(sendingTo, BorderLayout.PAGE_START);
          JPanel messageLog = new JPanel();
          messageLog.setOpaque(false);
          messageLog.setBorder(BorderFactory.createTitledBorder("Message Log"));
          contentPane.add(messageLog, BorderLayout.CENTER);
          JPanel sendPanel = new JPanel(new BorderLayout(2, 0));
          sendPanel.setBackground(Color.BLUE);
          JTextArea sendMessageArea = new JTextArea("Send Message Area", 5, 30);
          sendMessageArea.setOpaque(false);
          sendPanel.add(sendMessageArea, BorderLayout.CENTER);
          JButton _sendMessage = new JButton("Send Message");
          sendPanel.add(_sendMessage, BorderLayout.LINE_END);
          contentPane.add(sendPanel, BorderLayout.PAGE_END);
          try {
             UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
          } catch (ClassNotFoundException e) {
             e.printStackTrace();
          } catch (InstantiationException e) {
             e.printStackTrace();
          } catch (IllegalAccessException e) {
             e.printStackTrace();
          } catch (UnsupportedLookAndFeelException e) {
             e.printStackTrace();
          topLevelContainer.pack();
       private static void createAndShowUI() {
          new MainWindow();
          new MainWindow();
       public static void main(String[] args) {
          java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
                createAndShowUI();
    }And in it, I notice that you're setting your GUI visible before adding components and your setting the look and feel after you've created and added components, and this seems a bit backwards. The look and feel issue is what is causing the problem that you are noticing.

  • JButton Adding Problem

    Hi everyone,
    First, like to say I appreciate all your help. I have come here for help before and I always get my questions answered. Thanks.
    Here is my problem:
    I've created a JPanel and added this panel to a JFrame. The JPanel has a MouseListener and a MouseMotionListener. I am tryin to add JButtons to the JPanel at positions passed from the MouseMotionListener, but everytime I attempt this, the JButton pops to the top left corner of the screen. I don't know if I should use a layout manager on the JPanel and if I do, I don't know which one to use. I've tried using the SpringLayout, but was unsuccessful at deploying it.
    Appreciate any help.
    Thanks again.

    Null layout is not recommended, see my earlier post. Here is a simple SpringLayout that does the same thing.
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TestSpring extends JFrame
         Container cp;
         int mpx, mpy;
         int MINX= 80;
         int MINY=20;
         JLabel txt = new JLabel("use mouse to position buttons, drag to set size");
         SpringLayout slay = new SpringLayout();
         MouseInputAdapter mia = new MouseInputAdapter()
              public void mousePressed(MouseEvent evt){mousePress(evt);}
              public void mouseReleased(MouseEvent evt){mouseRelease(evt);}
         TestSpring()
              super("TestSpring");
              cp = getContentPane();
              addWindowListener(new WindowAdapter()
              {public void windowClosing(WindowEvent evt){System.exit(0);}});
              cp.addMouseListener(mia);
              cp.setLayout(slay);
              cp.add(txt);
              setBounds(0,0,700,400);
         void mousePress(MouseEvent evt)
              mpx = evt.getX();
              mpy = evt.getY();
         void mouseRelease(MouseEvent evt)
              int x,y,dx,dy;
              x = evt.getX();
              y=evt.getY();
              dx = x-mpx;
              dy = y-mpy;
              if(dx < 0){dx = -dx; mpx = x;}
              if(dy < 0){dy = -dy; mpy = y;}
              JButton jb = new JButton(mpx+","+mpy);
              cp.add(jb);
              setCPosition(jb,mpx,mpy);
              if(dx < MINX)dx = MINX;
              if(dy < MINY)dy = MINY;
              setCSize(jb, dx, dy);
              cp.validate();
         void setCPosition(Component c, int x, int y)
              slay.getConstraints(c).setX(Spring.constant(x));
              slay.getConstraints(c).setY(Spring.constant(y));
         void setCSize(Component c, int w, int h)
              slay.getConstraints(c).setWidth(Spring.constant(w));
              slay.getConstraints(c).setHeight(Spring.constant(h));
         // the main startup function
         public static void main(String[] args)
              new TestSpring().show();
    }

  • JButton clicked problem?

    I have a Jbutton and on button clicked, action is performed.
    Now if mouse is just clicked but moved only one pixel(means focus is still on the button) , action will not occur. It works only if the button is clicked and mouse does not move at all. I want action if the button is clicked and does not leave the button forground area until it is released.
    thnx

    Sounds like there is a problem in your code. Only can make wild guesses based on the lack of info. (If you post code, please spare us the pain of looking at all of it, just create a simple example).

  • JButton base problem

    Hi All,
    I have a primitive /as I known/ problem with the JButton.
    I create one, and set the text with this 'Show'. I set the font /eg. Arial/ and it's size to 9.
    If I set the required size of the button the text is not shown. /shown only .../
    When show the text correctly the width of button is very large for me.
    How can I make a button which hase a same width such as the text in it.?
    thx.

    Once you've set the font and text for a button, you can find out its preferred size using getPreferredSize.
    Typically buttons will add on padding between the text and the border. This is known as the "margin" and can be changed using setMargin.
    You can set the margin for all buttons using UIManager's Button.margin property.
    Hope this helps.

  • JButton NullPointerException problem

    Hi
    I was wondering if you guys can help me out on this one. I'm been prompted with a NullPointerException whenever I click on either of the 2 buttons.
    Thanks guys
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Alarm extends JPanel implements ActionListener{
        private JTextArea messageField;
        private JButton alarmOn, alarmOff;
        private JLabel alarmLED;
        public Alarm(){
            super.setPreferredSize(new Dimension(200,300));
            //configuring components;
            JButton alarmOn = new JButton("On");
            alarmOn.addActionListener(this);
            JButton alarmOff = new JButton("OFF");
            alarmOff.addActionListener(this);
            JLabel alarmLED = new JLabel("Alarm OFF");
            alarmLED.setOpaque(true);
            alarmLED.setBackground(Color.GREEN);
            messageField = new JTextArea(2,20);
            messageField.setEditable(false);
            messageField.setPreferredSize(new Dimension(200, 200));
            this.add(messageField, BorderLayout.PAGE_START);
            alarmOn.setPreferredSize(new Dimension(80, 20));
            this.add(alarmOn, BorderLayout.LINE_START);
            alarmOff.setPreferredSize(new Dimension(80, 20));
            this.add(alarmOff, BorderLayout.CENTER);
            alarmLED.setPreferredSize(new Dimension(65, 30));
            this.add(alarmLED, BorderLayout.LINE_END);
         public void actionPerformed(ActionEvent event){
            if(event.getSource()==this.alarmOn){
                this.alarmLED.setBackground(Color.RED);
                this.alarmLED.setText("Alarm ON");
            }else{
                this.alarmLED.setBackground(Color.GREEN);
                this.alarmLED.setText("Alarm OFF");
    }//end of class;

    I figured it out...I think i declared the button twice.
    Funny...it seems easier to spot it in this forums comparing it on BlueJ
    Will someone recommend me a better java client then BLueJ?
    Preferably user friendly kinds
    Thanks

  • ImageIcon problems

    Hi!
    I've problems with image icon. When I tried to scale or rotate it, "out of memory error" occours (mostly at larger pictures). Is there any solution to this problem?
    I know the "java -Xmx120m" solution, but this not solves the problem, just delays it.
    Any help would be usefull. THX!

    I tried for some month brefore using JAI to solve the problem of visualizing very big image using BufferedImage but I didn't find any solution.
    The only way i found were Tiling the original image in smallest image and read at each time only those visible.
    I think the solution with java advanced image is at the moment the best I found
    Stefano Madeddu

  • [bc4j] Urgent jbutton binding problem

    Hi,
    I have a working application with a few panels, and a few viewobjects, viewlinks, etc. I can use the navigator to navigate through the records, etc, everything works fine.
    But when I add a jbutton to the panel, with an action binding for the view object ('insert new record' or 'next'), then when starting up the application, the view object begins to spill, all records seem to be loaded and spilled to the spill-table.
    If I remove the model form the jbutton and re-run, everything works fine again. What could cause this? All other binded controls (navigationbar, several jtextfields, and even a jtree) work fine, but the jbutton causes spills.
    And not even when I click it, but during startup of the app!
    Any idea?
    Greetings,
    Ivo

    Bug#2772798 filed after reproducing using your testcase. Thanks.
    Shailesh got back to me with this analysis:
    No bindings should force a range size of -1 by default except for Lov Bindings on Combo and List Boxes where all the data is needed on the client side control.
    ButtonlActionBinding's create method is setting the rangesize of the iterator to -1 leading to all rows being fetched. The workaround is to set the range size on the iterator in setPanelBinding() method after jbInit() to a desired size.
    Here's a line I added to Ivo's setPanelBinding() method of his PanelFootballView1.java class...
    jbInit();
    panelBinding.findIterBinding("FootballViewIter1").getRowSetIterator().setRangeSize(1);

Maybe you are looking for

  • How do I find the serial number of a stolen Ipod touch?

    Unfortunately, we lost the serial number of our touch - now it was stolen. How can we find the serial number - I thought it would be registered under my iTunes-account... Any ideas? Thanks.

  • Need XML Structure as output

    Hi, I have an input structure in the below format. Sl.No*Name*Salary 101*Hari*45000 102*Ram*30000 103* * 25000 I want XML format in the below format. <RecordSet> <Record1> <Sl.No> 101 </Sl.No> <Name> Hari </Name> <Salary> 45000</Salary> </Record1> <R

  • How can I get this lousy browser to work?

    Where to start... First off there's never anyone on live chat. Second, none of my yahoo groups work with this browser and neither does my hotmail account. This browser was downloaded into my computer by a microsoft tech after I paid to have my comput

  • Difference in Premium vs. Standard?

    I was online with chat, and they weren't much help.  I am trying to understand what this feature is/means in Premium: Customize Business Catalyst sites to suit your customers That doesn't make any sense.  How is that different from a standard plan wh

  • Disabled buttons still generate events

    It seems that disabled buttons still generate events in business one. If a button is disabled (even a standard one) click events can still be seen in the SBO event logger. I would have expected a disabled button to be completely disabled and no event