Squished JButtons

I'm trying to make a JFrame that will cycle through several Images (VCR-like).
I've tried various methods, all with the same basic results. The image comes up fine, but the 4 buttons (first, previous, next, last) are all squished at the bottom (should be 36x36 icons - gifs really - but are displaying as about 25x10) and are unreadable. They are coming up in the correct order and work properly, it's just impossible for the operator to know what they do without the icon.
I've tried making a BorderLayout JPanel on the content pane, put the image in the CENTER and the 4 buttons in the SOUTH.
I've tried making a BoxLayout JPanel (Y-Axis) on the content pane with the image added first and the button panel (built on a BoxLayout (X-Axis)) second.
I've tried forcing the size of the buttons by setting the minimum size to the size of the GIF files.
I've run out of ideas.
Below is what I currently have, which builds the main panel with a BoxLayout in the Y-Axis then adds the image as a JLabel, builds another JPanel for the buttons (which is a BoxLayout in the X-Axis) which is added to the main panel.
public class ImageReview
             extends JFrame
   private int index = 0;
   private int numImages = 0;
   private ImageIcon[] images = null;
   private JLabel imageLabel = null;
   private JPanel mainPanel = null;
   private String FIRST_BUTTON = "firstArrowIcon.gif";
   private String PREV_BUTTON = "previousArrowIcon.gif";
   private String NEXT_BUTTON = "nextArrowIcon.gif";
   private String LAST_BUTTON = "lastArrowIcon.gif";
   public ImageReview (ImageIcon[] images)
      super ("Image Review");
      setSize (640, 550);
      Container contentPane = getContentPane();
      mainPanel = new JPanel ();
      mainPanel.setLayout (new BoxLayout (mainPanel, BoxLayout.Y_AXIS));
      numImages = images.length;
      this.images = new ImageIcon[numImages];
      for (int i=0 ; i<numImages ; i++)
         this.images[i] = images;
JPanel imagePanel = new JPanel ();
imageLabel = new JLabel (this.images[0]);
imagePanel.add (imageLabel);
mainPanel.add (imagePanel, BorderLayout.CENTER);
mainPanel.add (Box.createVerticalStrut (10));
index=0;
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout (new BoxLayout (buttonPanel, BoxLayout.X_AXIS));
buttonPanel.add (createButton (FIRST_BUTTON));
buttonPanel.add (createButton (PREV_BUTTON));
buttonPanel.add (createButton (NEXT_BUTTON));
buttonPanel.add (createButton (LAST_BUTTON));
mainPanel.add (buttonPanel);
mainPanel.add (Box.createVerticalStrut (20));
contentPane.add (mainPanel);
private JButton createButton (String buttonType)
JButton button = new JButton ();
ImageIcon imageIcon = new ImageIcon (buttonType);
Image image = imageIcon.getImage();
button.setIcon (imageIcon);
Dimension preferredSize = new Dimension (imageIcon.getIconWidth (),
imageIcon.getIconHeight());
button.setMinimumSize (preferredSize);
button.setAction (new imageReviewAction (buttonType));
String tooltip = "Press to go to ";
if (buttonType == FIRST_BUTTON)
tooltip += "First";
else if (buttonType == PREV_BUTTON)
tooltip += "Previous";
else if (buttonType == NEXT_BUTTON)
tooltip += "Next";
else if (buttonType == LAST_BUTTON)
tooltip += "Last";
tooltip += " Image in List";
button.setToolTipText (tooltip);
return button;
class imageReviewAction
extends AbstractAction
private Button button = null;
public imageReviewAction (Button button)
this.button = button;
public void actionPerformed (ActionEvent e)
if (button == FIRST_BUTTON)
index = 0;
else if (button == PREV_BUTTON)
if (index > 0)
index--;
else if (button == NEXT_BUTTON)
if (index < numImages - 1)
index++;
else if (button == LAST_BUTTON)
index = numImages - 1;
else
// No other buttons, can't do anything.
imageLabel.setIcon (images[index]);

Had to make a lot of changes to your app to get it squared away. It compiles and runs okay; you can have a look.
I think the central problem of the button size is in this line:
button.setAction (new imageReviewAction (buttonType));
Setting the action removes the icon. One way around it is to change your AbstractAction class to an ActionListener.
import java.awt.*;
import java.awt.event.*;
import java.net.URL;
import javax.swing.*;
public class ImageReviewRx extends JFrame
    private ImageIcon[] icons = null;
    private JLabel imageLabel = null;
    private JPanel mainPanel = null;
    ImageReviewAction action;
    public ImageReviewRx ()
        super ("Image Review");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize (640, 550);
        createIcons();
        action = new ImageReviewAction();
        mainPanel = new JPanel ();
        mainPanel.setLayout (new BorderLayout ());
        JPanel imagePanel = new JPanel ();
        imageLabel = new JLabel (icons[0]);
        imagePanel.add (imageLabel);
        mainPanel.add (imagePanel, BorderLayout.CENTER);
        JPanel buttonPanel = new JPanel();
        for(int j = 0; j < icons.length; j++)
            buttonPanel.add (createButton (j));
        mainPanel.add (buttonPanel, "South");
        Container contentPane = getContentPane();
        contentPane.add (mainPanel);
    private JButton createButton (int iconIndex)
        JButton button = new JButton ();
        int w = icons[iconIndex].getIconWidth();
        int h = icons[iconIndex].getIconHeight();
//        button.setPreferredSize(new Dimension(w,h));  // an option
        button.setIcon (icons[iconIndex]);
        button.addActionListener (action);
        String ac = "";
        switch(iconIndex)
            case 0:
                ac = "First";
                break;
            case 1:
                ac = "Previous";
                break;
            case 2:
                ac = "Next";
                break;
            case 3:
                ac = "Last";
        String tooltip = "Press to go to " + ac + " Image in List";
        button.setToolTipText (tooltip);
        button.setActionCommand(ac);
        return button;
    private void createIcons()
        String[] fileNames = {
            "firstArrowIcon.gif", "previousArrowIcon.gif",
            "nextArrowIcon.gif",  "lastArrowIcon.gif"
        icons = new ImageIcon[fileNames.length];
        for(int j = 0; j < icons.length; j++)
            URL url = getClass().getResource(fileNames[j]);
            icons[j] = new ImageIcon(url);
    class ImageReviewAction implements ActionListener
        int index = 0;
        public void actionPerformed (ActionEvent e)
            JButton button = (JButton)e.getSource();
            String ac = button.getActionCommand();
            if (ac.equals("First"))
                index = 0;
            if (ac.equals("Previous"))
                index--;
                if(index < 0)
                    index = icons.length - 1;
            if (ac.equals("Next"))
                index++;
                if(index > icons.length - 1)
                    index = 0;
            if (ac.equals("Last"))
                index = icons.length - 1;
            imageLabel.setIcon(icons[index]);
    public static void main(String[] args)
        ImageReviewRx rx = new ImageReviewRx();
        rx.setVisible(true);
}

Similar Messages

  • 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

  • Unable to  trace JButton event

    hello there,
    iam creating a JButton on which iam setting an imageicon .
    instead of the image path to the constructor of jbutton iam passing the
    byte array of that image.
    now the problem is when i click on that button, iam unable to trace in the actionperformed method that this particular button was clicked.
    any help in this regard is mostly appreciated.
    bye

    sorry. a small correction to the above sentence
    iam creating that image through the byte array which is passed to the constructor of the ImageIcon. now this imageicon object is passed to the constructor of the jbutton.

  • Getting the label of a JButton in a for loop

    hi,
    I doing a project for my course at the minute and im in need of a bit of help. I have set up 1-d array of buttons and i have layed them out using a for loop. I have also added an annoymous action listener to each button in the loop. It looks something lke this:
    b = new JButton[43];
    for (int i=1; i<43; i++)
    b[i] = new JButton(" ");
    b.addActionListener(
    new ActionListener()
    public void actionPerformed(ActionEvent e)
              System.out.println("..........");
    }); // addActionListener
    } // for
    I want the "System.out.println( ..." line, to print out the "i" number of the button that was pressed but i cannot figure out how to do it. I cannot put "System.out.println(" "+i);" as it wont recognise i as it is not inside the for loop. Does anyone have any suggestions?
    Thanks!!

    class ButtonExample extends JFrame implements ActionListener{The OP wanted to have anonymous listeners, not a subclassed JFrame
    listening to the buttons. I don't know if the following is the best design,
    since the poster has revealed so little, but here is how to pass the
    loop index to an anonymous class.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class ButtonExample {
        private JButton[] buttons = new JButton[24];
        public JPanel createGUI() {
            JPanel gui = new JPanel(new GridLayout(6,  4));
            for(int i=0; i<buttons.length; i++) {
                final int ii = i; //!! !
                buttons[i] = new JButton("button #" + i);
                buttons.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent evt) {
    System.out.println("number " + ii);
    gui.add(buttons[i]);
    return gui;
    public static void main(String[] args) {
    ButtonExample app = new ButtonExample();
    JPanel gui = app.createGUI();
    JFrame f = new JFrame("ButtonExample");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(gui);
    f.pack();
    f.setLocationRelativeTo(null);
    f.setVisible(true);

  • How to display a JPanel of JButtons on ImagePanel?

    Hi
    From the Swing Hacks examples, I can display a JButton on an ImagePanel no problem. But when I put this JButton in JPanel, then add the JPanel to the ImagePanel, the JPanel with the JButton is not displayed.
    Can someone please explain why this is?
    Here is the ImagePanel code:
    import java.awt.*;
    import javax.swing.*;
    public class ImagePanel extends JPanel {
        private Image img;
        public ImagePanel(String img) {
            this(new ImageIcon(img).getImage());
        public ImagePanel(Image img) {
            this.img = img;
            Dimension size = new Dimension(img.getWidth(null),img.getHeight(null));
            setPreferredSize(size);
            setMinimumSize(size);
            setMaximumSize(size);
            setSize(size);
            setLayout(null);
        public void paintComponent(Graphics g) {
            g.drawImage(img,0,0,null);
    }And here is the code to add a JButton to a JPanel, then add the JPanel to the ImagePanel:
    import javax.swing.*;
    import java.awt.event.*;
    public class ImageTest {
        public static void main(String[] args) {
           ImagePanel panel = new ImagePanel(new ImageIcon("images/background.png").getImage());
           JPanel buttonPanel = new JPanel()       
            JButton button = new JButton("Button");
            buttonPanel.add(button);
           JFrame frame = new JFrame("Hack #XX: Image Components");
            frame.getContentPane().add(button);    // WORKS!
            //frame.getContentPane().add(buttonPanel);   // NO BUTTON IS DISPLAYED???
           frame.pack();
            frame.setVisible(true);
    }Thanks

    setLayout(null);When you use a null layout then you are responsible for setting the size and location of any component added to the panel. The default location is (0,0) so thats ok, but the default size of the button panel is also (0,0) which is why nothing get painted.
    Don't use a null layout. Let the layout manager layout any component added to it.
    Also, I would override the getPreferredSize() method of your ImagePanel to return the size of the image, instead of setting the preferred size in the constructor.

  • How do i use jbutton for mutiple frames(2frames)???

    im an creating a movie database program and i have a problem with the jButtons on my second frame i dont know how to make them work when clicked on. i managed to make the jButtons work on my first frame but not on the second....
    here is that code so far----
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    * real2.java
    * Created on December 7, 2007, 9:00 AM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    * @author J
    public class real2 extends JPanel  implements ActionListener{
        private JButton addnew;
        private JButton help;
        private JButton exit;
        private JFrame frame1;
        private JButton save;
        private JButton cancel;
        private JButton save2;
        private JLabel moviename;
        private JTextField moviename2;
        private JLabel director;
        private JTextField director2;
        private JLabel year;
        private JTextField year2;
        private JLabel genre;
        private JTextField genre2;
        private JLabel plot;
        private JTextField plot2;
        private JLabel rating;
        private JTextField rating2;
        /** Creates a new instance of real2 */
        public real2() {
            super(new GridBagLayout());
            //Create the Buttons.
            addnew = new JButton("Add New");
            addnew.addActionListener(this);
            addnew.setMnemonic(KeyEvent.VK_E);
            addnew.setActionCommand("Add New");
            help = new JButton("Help");
            help.addActionListener(this);
            help.setActionCommand("Help");
            exit = new JButton("Exit");
            exit.addActionListener(this);
            exit.setActionCommand("Exit");
           String[] columnNames = {"First Name",
                                    "Last Name",
                                    "Sport",
                                    "# of Years",
                                    "Vegetarian"};
            Object[][] data = {
                {"Mary", "Campione",
                 "Snowboarding", new Integer(5), new Boolean(false)},
                {"Alison", "Huml",
                 "Rowing", new Integer(3), new Boolean(true)},
                {"Kathy", "Walrath",
                 "Knitting", new Integer(2), new Boolean(false)},
                {"Sharon", "Zakhour",
                 "Speed reading", new Integer(20), new Boolean(true)},
                {"Philip", "Milne",
                 "Pool", new Integer(10), new Boolean(false)}
            final JTable table = new JTable(data, columnNames);
            table.setPreferredScrollableViewportSize(new Dimension(600, 100));
            table.setFillsViewportHeight(true);
            //Create the scroll pane and add the table to it.
            JScrollPane scrollPane = new JScrollPane(table);
            //Add the scroll pane to this panel.
            add(scrollPane);
            GridBagConstraints c = new GridBagConstraints();
            c.weightx = 1;
            c.gridx = 0;
            c.gridy = 1;
            add(addnew, c);
            c.gridx = 0;
            c.gridy = 2;
            add(help, c);
            c.gridx = 0;
            c.gridy = 3;
            add(exit, c);
        public static void addComponentsToPane(Container pane){
            pane.setLayout(null);
            //creating the components for the new frame
            JButton save = new JButton("Save");
            JButton save2 = new JButton("Save and add another");
            JButton cancel = new JButton("Cancel");
            JLabel moviename= new JLabel("Movie Name");
            JTextField moviename2 = new JTextField(8);
            JLabel director = new JLabel("Director");
            JTextField director2 = new JTextField(8);
            JLabel genre = new JLabel("Genre");
            JTextField genre2 = new JTextField(8);
            JLabel year = new JLabel("year");
            JTextField year2 = new JTextField(8);
            JLabel plot = new JLabel("Plot");
            JTextField plot2 = new JTextField(8);
            JLabel rating = new JLabel("Rating(of 10)");
            JTextField rating2 = new JTextField(8);
            //adding components to new frame
            pane.add(save);
            pane.add(save2);
            pane.add(cancel);
            pane.add(moviename);
            pane.add(moviename2);
            pane.add(director);
            pane.add(director2);
            pane.add(genre);
            pane.add(genre2);
            pane.add(year);
            pane.add(year2);
            pane.add(plot);
            pane.add(plot2);
            pane.add(rating);
            pane.add(rating2);
            //setting positions of components for new frame
                Insets insets = pane.getInsets();
                Dimension size = save.getPreferredSize();
                save.setBounds(100 , 50 ,
                         size.width, size.height);
                 size = save2.getPreferredSize();
                save2.setBounds(200 , 50 ,
                         size.width, size.height);
                 size = cancel.getPreferredSize();
                cancel.setBounds(400 , 50 ,
                         size.width, size.height);
                 size = moviename.getPreferredSize();
                moviename.setBounds(100 , 100 ,
                         size.width, size.height);
                size = moviename2.getPreferredSize();
                moviename2.setBounds(200 , 100 ,
                         size.width, size.height);
                 size = director.getPreferredSize();
                director.setBounds(100, 150 ,
                         size.width, size.height);
                 size = director2.getPreferredSize();
                director2.setBounds(200 , 150 ,
                         size.width, size.height);
                size = genre.getPreferredSize();
                genre.setBounds(100 , 200 ,
                         size.width, size.height);
                 size = genre2.getPreferredSize();
                genre2.setBounds(200 , 200 ,
                         size.width, size.height);
                 size = year.getPreferredSize();
                year.setBounds(100 , 250 ,
                         size.width, size.height);
                size = year2.getPreferredSize();
                year2.setBounds(200 , 250 ,
                         size.width, size.height);
                 size = plot.getPreferredSize();
                plot.setBounds(100 , 300 ,
                         size.width, size.height);
                 size = plot2.getPreferredSize();
                plot2.setBounds(200 , 300 ,
                         size.width, size.height);
                size = rating.getPreferredSize();
                rating.setBounds(100 , 350 ,
                         size.width, size.height);
                 size = rating2.getPreferredSize();
                rating2.setBounds(200 , 350 ,
                         size.width, size.height);
        private static void createAndShowGUI() {
            //Create and set up the window.
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
            frame.add(new real2());
            //Display the window.
            frame.setSize(600, 360);
            frame.setVisible(true);
            frame.pack();
        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();
        public void actionPerformed(ActionEvent e) {
            if ("Add New".equals(e.getActionCommand())){
               frame1 = new JFrame("add");
               frame1.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
               addComponentsToPane(frame1.getContentPane());
               frame1.setSize(600, 500);
               frame1.setVisible(true);
                //disableing first frame etc:-
                if (frame1.isShowing()){
                addnew.setEnabled(false);
                help.setEnabled(false);
                exit.setEnabled(true);
                frame1.setVisible(true);
               }else{
                addnew.setEnabled(true);
                help.setEnabled(true);
                exit.setEnabled(true);           
            if ("Exit".equals(e.getActionCommand())){
                System.exit(0);
            if ("Save".equals(e.getActionCommand())){
                // whatever i ask it to do it wont for example---
                help.setEnabled(true);
            if ("Save" == e.getSource()) {
                //i tried this way too but it dint work here either
                help.setEnabled(true);
    }so if someone could help me by either telling me what to type or by replacing what iv done wrong that would be great thanks...

    (1)Java class name should begin with a capital letter. See: http://java.sun.com/docs/codeconv/
            JButton save = new JButton("Save");
            JButton save2 = new JButton("Save and add another");
            // ... etc. ...(2)Don't redeclare class members in a method as its local variable. Your class members become eternally null, a hellish null.
    how to make them work when clicked on(3)Add action listener to them.

  • Getting values from JLabel[] with JButton[] help!

    Hello everyone!
    My problem is:
    I have created JPanel, i have an array of JButtons and array of JLabels, they are all placed on JPanel depending from record count in *.mdb table - JLabels have its own value selected from Access table.mdb! I need- each time i press some button,say 3rd button i get value showing from 3rd JLabel in some elsewere created textfield, if i have some 60 records and 60 buttons and 60 labels its very annoying to add for each button actionlistener and for each button ask for example jButton[1].addActionListener() ...{ jLabel[1].getText()......} and so on!
    Any suggestion will be appreciated! Thank you!

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Testing
      public void buildGUI()
        final int ROWS = 10;
        JPanel[] rows = new JPanel[ROWS];
        final JLabel[] labels = new JLabel[ROWS];
        JButton[] buttons = new JButton[ROWS];
        JPanel p = new JPanel(new GridLayout(ROWS,1));
        final JTextField tf = new JTextField(10);
        ActionListener listener = new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            tf.setText(labels[Integer.parseInt(((JButton)ae.getSource()).getName())].getText());
        for(int x = 0; x < ROWS; x++)
          labels[x] = new JLabel(""+(int)(Math.random()*10000));
          buttons[x] = new JButton("Button "+x);
          buttons[x].setName(""+x);
          buttons[x].addActionListener(listener);
          rows[x] = new JPanel(new GridLayout(1,2));
          rows[x].add(labels[x]);
          rows[x].add(buttons[x]);
          p.add(rows[x]);
        JFrame f = new JFrame();
        f.getContentPane().add(p,BorderLayout.CENTER);
        f.getContentPane().add(tf,BorderLayout.SOUTH);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }

  • Problem with KeyAdapter and JButtons in a Jframe

    yes hi
    i have searched almost most of the threads here but nothing
    am trying to make my frame accepts keypress and also have some button on the frame here is the code and thank you for the all the help
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class RPg extends JFrame implements ActionListener
                private int width;
                private int hight;
                public    JPanel north;
                public    JPanel se;
                public    JButton start;
                public    JButton quit;
                public    Screen s;//a Jpanel
                public    KeyStrokeHandler x;
        public RPg() {
               init();
               setTitle("RPG");
               setSize(width,hight);
               setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
               setResizable(false);
               setVisible(true);
               x=new KeyStrokeHandler();
             addKeyListener(x);
             public void init() {
               north=new JPanel();
               Container cp = getContentPane();
               s=new Screen();
               this.width=s.width;
               this.hight=s.hight+60;
              start=new JButton("START");
                  start.addActionListener(this);
              quit=new JButton("QUIT");
                  quit.addActionListener(this);
              north.setBackground(Color.DARK_GRAY);
              north.setLayout(new FlowLayout());
              north.add(start);
              north.add(quit);
              cp.add(north, BorderLayout.NORTH);
              cp.add(s, BorderLayout.CENTER);
        public static void main(String[] args) {
            RPg rpg = new RPg();
       public void actionPerformed(ActionEvent ae) {
            if (ae.getActionCommand().equals("QUIT")) {
                     System.exit(0);
            if (ae.getActionCommand().equals("START")) { }
       class KeyStrokeHandler extends KeyAdapter {
               public void keyTyped(KeyEvent ke) {}
               public void keyPressed(KeyEvent ke){
                  int keyCode = ke.getKeyCode();
                  if ((keyCode == KeyEvent.VK_M)){
                     System.out.println("it works");
               public void keyReleased(KeyEvent ke){}

    Use the 'tab' key to navigate through 'contentPane > start > quit' focus cycle. 'M' key works when focus is on contentPane (which it is on first showing). See tutorial pages on 'Using Key Bindings' and 'Focus Subsystem' for more.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class RPG extends JFrame implements ActionListener {
        private int width;
        private int hight;
        public JPanel north;
        public JPanel se;
        public JButton start;
        public JButton quit;
        public Screen s;    //a Jpanel
        public RPG() {
            init();
            setTitle("RPG");
            setSize(width,hight);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setResizable(false);
            setVisible(true);
        public void init() {
            north=new JPanel();
            Container cp = getContentPane();
            registerKeys((JComponent)cp);
            s=new Screen();
            this.width=s.width;
            this.hight=s.hight+60;
            start=new JButton("START");
                start.addActionListener(this);
            quit=new JButton("QUIT");
                quit.addActionListener(this);
            north.setBackground(Color.DARK_GRAY);
            north.setLayout(new FlowLayout());
            north.add(start);
            north.add(quit);
            cp.add(north, BorderLayout.NORTH);
            cp.add(s, BorderLayout.CENTER);
        public static void main(String[] args) {
            RPG rpg = new RPG();
        public void actionPerformed(ActionEvent ae) {
            if (ae.getActionCommand().equals("QUIT")) {
                     System.exit(0);
            if (ae.getActionCommand().equals("START")) { }
        private void registerKeys(JComponent jc)
            jc.getInputMap().put(KeyStroke.getKeyStroke("M"), "M");
            jc.getActionMap().put("M", mAction);
        Action mAction = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("it works");
    class Screen extends JPanel {
        int width, hight;
        public Screen() {
            width = 300;
            hight = 300;
            setBackground(Color.pink);
    }

  • Problem with setCursor for JButton in cell on JTable

    i have a problem with setCursor to JButton that is in a cell of the JTable}
    this is the code
    public class JButtonCellRenderer extends JButton implements TableCellRenderer {
    public JButtonCellRenderer() {
    setOpaque(true);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus,
    int row, int column) {
    if (isSelected) {
    setForeground(table.getSelectionForeground());
    setBackground(table.getSelectionBackground());
    else {
    setForeground(table.getForeground());
    setBackground(Color.WHITE);
    setBorder(null);
    if(table.getValueAt(row,column) == null){
    setText("");
    if(isSelected){
    setBackground(table.getSelectionBackground());
    }else{
    setBackground(Color.WHITE);
    }else{
    if(table.getValueAt(row,column) instanceof JButton){
    JButton _button = (JButton)table.getValueAt(row,column);
    if(_button.getText().trim().equals("")){
    setText("<html>"+ "<font size=\"3\" COLOR=\"#0000FF\"><u><b>Ver...</b></u></font>"+"");
    }else{
    setText("<html>"+ "<font size=\"3\" COLOR=\"#0000FF\"><u><b>" + _button.getText() + "</b></u></font>"+"");
    return this;
    }

    Not quite sure I understand the problem, but I guess you have tried to call setCursor on your renderer and found it didn't work? The reason, I think, is that the renderer only renders a JButton. The thing that ends up in the table is in fact only a "picture" of a JButton, and among other things it won't receive and interact with any events, such as MouseEvents (so it wouldn't know that the cursor should change).
    There are at least two alternatives for you: You can perhaps use a CellEditor instead of a CellRenderer. Or you can add a MouseListener to the table and then use the methods column/rowAtPoint to figure out if the cursor is over your JButton cell and change the cursor yourself if it is.

  • Video out from iPod Classic looks "squished" on my TV

    I have a new iPod Classic which replaced a 5G video iPod. I have edited my photos in iPhoto to the 16:9 ratio to watch slideshows from my iPod on my 16:9 plasma TV using an iPod dock from Apple. Now when I hook up my new iPod to the same TV, using the same dock, the video output now looks "squished", and there are black bars above and below the image. When I watch the same slideshow on another TV using my Apple TV, the images look fine, and fill up the entire screen. Any idea why? Do I need a new dock?

    And your TV is set to "Full" or the like? I'm used to Sony HDTVs, so I don't know what the setting would be on your TV, but the largest Widescreen setting.
    That's the only thing I can think of, especially since you said when you tested it on another TV it worked. So it must be your TV and neither the iPod nor the cable. The way the iPod and cable work together really shouldn't change from TV to TV unless the TV itself has an issue.

  • Animated gif in a JButton which is a CellRenderer...

    I'm currently dealing with quite a huge thing...
    My cellRenderer is here to give a button aspect, this button has 3 kind of icons in fact :
    a cross when the line is ready to be treated
    a loading animation while in treatment... and here is the problem
    a tick whe the line has been treated
    i see the loader (but not always...) and not animated at all ...
    I change the states of the button in aother class, which has its own thread....
    .. as for no as see the lines being ticked line by line, cool, but if the loader could move between the 2 step, it would be perfect..
    Here is my class :
    * Create a special cell render for the first column of the images table
    * This cell render let us display a JButton associated with the given file in order
    * to permit its deletion from the tablelist
    * @author Gregory Durelle
    public class DeleteCellRender extends JButton implements TableCellRenderer , Runnable{
         private static final long serialVersionUID = 1L;
         int row;
         JTable table;
         public DeleteCellRender(){
             this.setIcon(Smash.getIcon("cross.png"));
              this.setBorderPainted(false);
              this.setForeground(Color.WHITE);
              this.setOpaque(false);
              this.setFocusable(false);
         public Component getTableCellRendererComponent( JTable table, Object value,boolean selected, boolean focused, int row, int column) {
              this.setBackground(table.getBackground());
              if(((DataModel)table.getModel()).getImageFile(row).isSent()){
                   this.setIcon(Smash.getIcon("tick.png"));//Smash is my main class & getIcon a static method to retrieve icons throug getRessource(url) stuff
                   this.setToolTipText(null);
              else if(((DataModel)table.getModel()).getImageFile(row).isSending()){
                   this.setIcon(Smash.getIcon("loader.gif")); //HERE IS THE PROBLEM, IT SHOULD BE ANIMATED :(
                   this.setToolTipText(null);
                   this.row=row;
                   this.table=table;
                 Thread t = new Thread(this);
                 t.start();
              else{
                   this.setIcon(Smash.getIcon("cross.png"));
                   this.setToolTipText("Delete this image from the list");
              return this;
         public void run() {
              while(true){
                   repaint();//SEEMS TO DO NO DIFFERENCE...
    }I tried to add a no-ending repaint but it does not make any difference... so if the Runnable annoy you, consider it deosn't exist ;)
    Someone has any idea of how to make an animated gif in a JButton which is in fact a CellRenderer ??....
    .. or maybe a better idea to make the loader appearing at the place of the cross, before the appearition of the tick....
    Edited by: GreGeek on 11 juil. 2008 23:04

    whooo :( you mean making a customized button ?
    like : public class MyButton extends AbstractButton{
       public void paintComponents(Graphics g){
          ...//img1 - wait 15ms - img2 - wait15ms - img3 - etc
    }that would be a solution, but i was pretty sure it would be possible to do more simple, and that i only forgot a very small thing to make it work...

  • Animated gif on JButton is not working

    Hi all,
    I have a JButton, which is used as a 'search button'. I want my search button to show an animated globe gif when search is going on. I have my code as below.
    JButton searchButton = new JButton(MyUtilities.searchIcon());
    ImageIcon animatedGlobe = MyUtilities.animatedGlobeGif();
    searchButton.setPressedIcon(animatedGlobe );
    At runtime the button is showing a static globe which is not animating.
    Can any one please answer what could be the problem?
    Thanks in advance,
    amar

    Thanx Demanic ,
    I am doing swings for first time. Can you please tell me how to repaint the button using seperate thread?
    Thanks,
    amar

  • IMAGE NOT DISPLAYED OVER JButton ON JDialog

    Hi,
    I am trying to display an image over a JButton inside a JDialog(pops up on button click from an applet). But it is invisible. But I am sure that it is drawn on the ContentPane since when i click partially/half at the position
    of the JButton I could see the JButton with the image. Actualy I am resizing the JDialog since I have two buttons, one to minimise and the other two maximise the size of the JDailog.
    All the buttons are in place but not visible neither at the first place nor when the JDialog is resized.
    The code is as follows:
    package com.dataworld.gis;
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.print.*;
    import javax.swing.*;
    public class PrintThisPolygon extends JDialog {
         protected Image image;
         protected JButton print;
         protected JButton resize;
         protected JButton desize;
         private int pX=0, pY=0, pWidth=0, pHeight=0;
         public PrintThisPolygon(JFrame parent, Viewer viewer) {
              super(parent, "Print Polygon", true);
              this.setModal(false);
              getContentPane().setLayout(null);
              image = this.viewer.getScreenBuffer();
              pane = new Panel();
              print = new JButton("print", new ImageIcon("images/print.gif"));
              print.setBounds(0,5,50,20);
              print.setEnabled(true);
              print.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent ae){
                        print();
              resize = new JButton("+", new ImageIcon("images/print.gif"));
              resize.setBounds(55,5,50, 20);
              resize.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent ae){
                        resizePlus();
              desize = new JButton("-", new ImageIcon("images/print.gif"));
              desize.setBounds(105,5,50, 20);
              desize.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent ae){
                        resizeMinus();
              getContentPane().add(print);
              getContentPane().add(resize);
              getContentPane().add(desize);
    public String getAppletInfo() {
         return "Identify Polygon\n"
    public void paint(Graphics g){
         System.out.println("Paint : pX " + pX + " pY :" + pY);
         g.drawImage(image, pX, pY, pWidth, pHeight, getBackground(), this);
    protected void print() {
         ImagePrint sp = new ImagePrint(this.viewer);
    public void resizeMinus(){
         repaint();
    public void resizePlus(){
         repaint();
    Can anybody has any clue. Can anybody help me out.
    Thanx

    I added resize code for those buttons and ended up with repaint problems too. When you manually resized the window everything was fine again. After a bit of digging around I found you need to call validate on the dialog and then things work.
    IL,
    There is the new scaling version of the code I modified above:package forum.com.dataworld.gis;
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class PanelPaintFrame extends JFrame {
         public static void main(String[] args) {
              PanelPaintFrame frame = new PanelPaintFrame ();
              frame.setVisible (true);
         public PanelPaintFrame ()  {
              setBounds (100, 100, 600, 600);
              setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
              JButton showPrintDialogButton = new JButton ("Show Print Dialog...");
              JPanel buttonPanel = new JPanel ();
              buttonPanel.add (showPrintDialogButton);
              getContentPane ().add (buttonPanel);
              showPrintDialogButton.addActionListener (new ActionListener ()  {
                   public void actionPerformed (ActionEvent e)  {
                        PrintThisPolygon printDialog = new PrintThisPolygon (PanelPaintFrame.this);
                        printDialog.show();
              pack ();
         public class PrintThisPolygon extends JDialog {
              protected ImageIcon myOrigonalImage = null;
              protected Image image;
              protected JButton print;
              protected JButton resize;
              protected JButton desize;
              private int pX=0, pY=0, pWidth=0, pHeight=0;
              JPanel pane = null;
              public PrintThisPolygon(JFrame parent/*, Viewer viewer*/) {
                   super(parent, "Print Polygon", true);
    //               this.setModal(false);
                   getContentPane().setLayout(null);
                   //  Substitute my own image
                   myOrigonalImage = new ImageIcon (PrintThisPolygon.class.getResource ("images/MyCoolImage.jpg"));
                   //  Start off full size
                   pWidth = myOrigonalImage.getIconWidth();
                   pHeight = myOrigonalImage.getIconHeight();
                   image = myOrigonalImage.getImage ().getScaledInstance(pWidth, pHeight, Image.SCALE_DEFAULT);
    //               image = this.viewer.getScreenBuffer();
    //               pane = new Panel();
                   //  Create a JPanel to draw the image
                   pane = new JPanel(){
                        protected void paintComponent(Graphics g)  {
                             System.out.println("Paint : pX " + pX + " pY :" + pY);
                             g.drawImage(image, pX, pY, pWidth, pHeight, getBackground(), this);
                   pane.setBounds (0, 0, pWidth, pHeight);
                   //  Load the button image using a URL
                   print = new JButton("print", new ImageIcon(PrintThisPolygon.class.getResource ("images/print.gif")));
    //               print = new JButton("print", new ImageIcon("images/print.gif"));
                   print.setBounds(0,5,55,20);
                   print.setEnabled(true);
                   print.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent ae){
                             print();
                   resize = new JButton("+", new ImageIcon("images/print.gif"));
                   resize.setBounds(55,5,50, 20);
                   resize.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent ae){
                             resizePlus();
                   desize = new JButton("-", new ImageIcon("images/print.gif"));
                   desize.setBounds(105,5,50, 20);
                   desize.addActionListener(new ActionListener(){
                        public void actionPerformed(ActionEvent ae){
                             resizeMinus();
                   //  Setup a transparent glass panel with no layout manager
                   JPanel glassPanel = new JPanel ();
                   glassPanel.setLayout (null);
                   glassPanel.setOpaque (false);
                   //  Add the image panel to the dialog
                   getContentPane().add(pane);
                   //  Add the buttons to the glass panel
                   glassPanel.add(print);
                   glassPanel.add(resize);
                   glassPanel.add(desize);
                   //  Set our created panel as the glass panel and turn it on
                   setGlassPane (glassPanel);
                   glassPanel.setVisible (true);
                   setBounds (100, 100, pWidth, pHeight);
    //               setBounds (100, 100, 500, 300);
              public String getAppletInfo() {
                   return "Identify Polygon\n";
    //          public void paint(Graphics g){
    //          protected void paintComponent(Graphics g)  {
    //               System.out.println("Paint : pX " + pX + " pY :" + pY);
    //               g.drawImage(image, pX, pY, pWidth, pHeight, getBackground(), this);
              protected void print() {
                   //  Pretend to print
    //               ImagePrint sp = new ImagePrint(this.viewer);
                   System.out.println ("Print view...");
              public void resizeMinus(){
                   //  Scale the image down 10%
                   int scaledWidth = pWidth - (int)(pWidth * 0.1);
                   int scaledHeight = pHeight - (int)(pHeight * 0.1);
                   scaleImage (scaledWidth, scaledHeight);
              public void resizePlus(){
                   //  Scale the image up 10%
                   int scaledWidth = pWidth + (int)(pWidth * 0.1);
                   int scaledHeight = pHeight + (int)(pHeight * 0.1);
                   scaleImage (scaledWidth, scaledHeight);
              private void scaleImage (int scaledWidth, int scaledHeight)  {
                   //  Create a new icon for drawing and retrieve its actuall size
                   image = myOrigonalImage.getImage ().getScaledInstance (scaledWidth, scaledHeight, Image.SCALE_DEFAULT);
                   pWidth = scaledWidth;
                   pHeight = scaledHeight;
                   //  Resize
                   setSize (pWidth, pHeight);
                   pane.setSize (pWidth, pHeight);
                   validate();
    }

  • Custom JButton displays properly on Win2K, not under Solaris

    We have an applet that creates a panel of custom JButtons, each of which has a set of associated icons, two of which are "active" and "inactive" (there are also disabled, rollover, etc. icons). At runtime, when a button is clicked, its icon property is set to the "active" one. If another button in the panel is clicked, the first button has its icon property set to the "inactive" one.
    This displays fine when the applet is running on a Win2k machine (with the Java 1.3 plugin under either Netscape 6.2 or IE 5.5, but when we run it on a SunRay connected to a Sun Ultra80 running Solaris 8 with Netscape 6.2 and the Java 1.3 plugin, the "inactive" icon for one particular button is blank - we get a white rectangle - but when we click on the rectangle (or mouseover it), the appropriate icon appears as it should.
    When I specify a different icon to be used (reusing the .gif file from one of the other buttons)I get the same behaviour. When I reorder the buttons in the panel, the same button (now in a different position) still behaves improperly.
    Any thoughts?
    Thanks,

    No solution, but for what it's worth.
    As part of my "diagnosis by trying things out" (NOT "debugging by..." - or at least I don't admit to that :) I created a second instance of the problem button and stuck it in the panel.
    Lo! the new instance had the problem, BUT THE FIRST WAS FINE. I did a few more experiments, and the first-created instance was the one to have problems, while the second is fine, so the current work-around is to make an instance, ignore it (just leave it as a field of the class that builds the panel, but don't add it to the panel), make another instance and use that in the panel.
    My boss is happy, our client is happy (they have a demo using the a group of Sunrays), but I really wish I knew what was going on. I don't THINK that the problem button was the first instance of its class to be created (I'm at home and the thought just came to me) but it's possible and raises some more hypotheses to test.

  • Need a little help with an animated JButton.

    I have a nice little button that on mouse entry runs a morf animation from one picture to another then stops.
    On leaving the button it runs the animation in reverse. The animation is done with two GIF images loaded as
    Icons using ImageIcon. Now this looks really nice, BUT it only dose it the first time the button is entered
    and the first time the button is exited. After this is abruptly switches from the "un-entered" button icon to the
    "entered" button icon (the end frame of the respective GIF animation's). I originally tried using the
    setRolloverIcon etc. When that did not work I thought that I would be able to get the images to be loaded
    each time by adding a MouseListener and using the mousePressed, mouseReleased, mouseEntered,
    mouseExited etc. methods. This gives me the situation described above. In the MouseListener methods a
    line like the following is used:
    ((JButton) e.getSource()).setIcon (new ImageIcon (MainWindow.
    class.getResource ("images/selected.gif")));
    How can I get the Button to run the animation every time it is entered | exited? The GIF from which the
    icons are made are set to run the animation through once, not an end less loop which would not be the
    desired effect.
    Any suggestions would be great
    Thank you
    M Pratten.

    Well I guess I should of just kept trying "lunch helps".
    Any way to get the image to reanimate each time the mouse pointer enters leaves the button I changed the
    code in the mouseListener to something like:
    ImageIcon i = new ImageIcon (MainWindow.class.getResource ("images/selected.gif"));
    i.getImage().flush ();
    ((JButton) e.getSource()).setIcon (i);
    I am assuming the flush puts the GIF animation back at its first frame so it has to redo the animation, which is
    exactly what I want.
    Now if any of the local experts know of a better way of doing this I would be happy to hear about it. But at
    the moment it seems to work just fine.
    Thanks to those that read my post.
    M Pratten.

Maybe you are looking for

  • Virtual pc 7 problem. please help me :(

    hi all. i use powerbook G4 1.67GHZ CPU (MAC OS X 10.4.4) my windows XP (installed under virtual pc 7) displays my CPU is : 293MHZ ( i just cant believe my eyes)..... aside, my video card becomes: S3 Trio32/64 and it has 4mb memory only. any1 could he

  • Premiere CC 7.2.2 crashes when trying to export via Media Encoder

    Hello, My computer is a: 2x Intel Xeon Processor E5-2650 (2000 MHz, 20MB); 16x Kingston DIMM 8 GB PC3-8500 ECC Reg.; PNY Quadro 4000 with 2048 MB GDDR5-RAM; PNY Tesla C 2075 2x 2000 GB Western Digital RE4 (7200 UPM/S-ATA II) as a RAID I 1x 120 GB OCZ

  • How to get my applet signed

    Hi I have an applet which has the functionality to print images.when i am working with appletviewer on local machine it works. when i tried to print through browser i am getting access denied error...i came to know that my applet has to get signed so

  • Problem when re-running a form that reads BLOB into OLE (form6i)

    I have a simple form which reads and writes a blob column into an OLE item. The form runs fine at the first round, but when I attempt to run agian it hangs and I have to do CTRL-ALT-DEL or reset the computer in most cases. This problem occures at the

  • Unbelievable ABAP oddity - SapScript related

    Sappers, I have officially come across the oddest ABAP problem that I have seen in 8 years.  I've spent 8+ hours trying every possible code variation to get around it but nothing works. Here's the story in summary. We have an invoice with shipping fi