Icon on JButton

I'm having an odd problem. Seemingly, I've done mostly everything correctly, but something must be wrong somewhere.
I'm trying to make JButtons with icon on them. I've made one, but the icon won't show. Here's my code:
          ImageIcon selectedIcon = new ImageIcon("selected.png", "Selected Menu");
          JButton characterScreenIcon = new JButton(selectedIcon);Now, that one actually works. But when I try to use setAction() on it, the icon disappears. This is the setAction line:
          characterScreenIcon.setAction(new ShowCharacterScreen());And here is the ShowCharacterScreen class:
     public class ShowCharacterScreen extends AbstractAction {
          public ShowCharacterScreen() {
               super();
          public void actionPerformed(ActionEvent e) {
               JButton icon = (JButton)(e.getSource());
               icon.setIcon(selectedIcon);
               JOptionPane.showMessageDialog(frame, "Button 1 pressed");
     }Now, it is worth noting that the action does work perfectly fine. I get the Dialog box. It's just the icon disappears when I use setAction() on it.
I would like to know why this happens, so I can figure out how to fix it.

hii,
are you meaning this one ??? --->
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.swing.*;
class TerraGUI {
    //GUI Fields
    static JFrame frame = new JFrame("TWOReborn");
    JPanel mainPane;
    JPanel characterPane;
    ImageIcon nonSelectedIcon;
    ImageIcon selectedIcon;
    public Container createContentPane() {
        mainPane = new JPanel();
        characterPane = new JPanel();
        characterPane.setPreferredSize(new Dimension(218, 442));
        characterPane.setBorder(BorderFactory.createLineBorder(Color.black));
        Image ViewMmImage = ImageViewMmLoader.getImage(TerraGUI.class, "resources/passed.png");
        Image ViewMmImage1 = ImageViewMmLoader.getImage(TerraGUI.class, "resources/failed.png");
        selectedIcon = new ImageIcon(ViewMmImage);
        nonSelectedIcon = new ImageIcon(ViewMmImage1);
        JPanel controlsAndStatus = new JPanel();
        JButton characterScreenIcon = new JButton();
        characterScreenIcon.setIcon(selectedIcon);
        characterScreenIcon.setMargin(new Insets(0, 0, 0, 0));
        characterScreenIcon.setAction(new ShowCharacterScreen());
        controlsAndStatus.add(characterScreenIcon);
        characterPane.add(controlsAndStatus);
        mainPane.add(characterPane);
        return mainPane;
    private static void createAndShowGUI() {
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        TerraGUI terra = new TerraGUI();
        frame.getContentPane().add(terra.createContentPane());
        frame.pack();
        frame.setVisible(true);
    public class ShowCharacterScreen extends AbstractAction {
        private static final long serialVersionUID = 1L;
        public ShowCharacterScreen() {
            super("", selectedIcon);
        public void actionPerformed(ActionEvent e) {
            JButton icon = (JButton) (e.getSource());
            icon.setIcon(null);
            icon.setIcon(nonSelectedIcon);
            JOptionPane.showMessageDialog(frame, "Button 1 pressed");
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
final class ImageViewMmLoader {
    private ImageViewMmLoader() {
    public static Image getImage(Class<?> relativeClass, String filename) {
        Image returnValue = null;
        InputStream is = relativeClass.getResourceAsStream(filename);
        if (is != null) {
            BufferedInputStream bis = new BufferedInputStream(is);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                int ch;
                while ((ch = bis.read()) != -1) {
                    baos.write(ch);
                returnValue = Toolkit.getDefaultToolkit().createImage(baos.toByteArray());
            } catch (IOException exception) {
                System.err.println("Error loading: " + filename);
        return returnValue;
}... kopik

Similar Messages

  • Problem in displaying Icon on JButton

    Hi,
    I have a problem ..
    In my program I have to set Icon for a Jbutton and wait for 2 secs and then remove the Icon..
    I used jb.setIcon(Imageicon) (jb is button reference) to set the icon and jb.setIcon(null) to remove Icon
    Now no Icon is displayed on the button at all....
    My code looks like below mentioned
    jb.setIcon(Imageicon)
    Thread.sleep(2000);
    jb.setIcon(null)
    plz reply mee at the earliest...

    the code snipped is like this..
    the below mentioned code is in actionPerformed method
    pres.setIcon(iial.get(Integer.parseInt(pres.getName())));  //icon for prev is already set
              System.out.println("Icon for pres is set now");
    // need to wait for 2 seconds before both the icons are set to null
              prev.setIcon(null);
              pres.setIcon(null);Here prev and pres are references to JButtons.
    I tried the swing timers but couldnt succeed (i might be implemented them in an incorrect way coz im not familiar with them)
    plz cud you provide me with am example program or a solution to above scenario in a program.....
    Here is the actual program if you want you can run it with keeping atleast 9 images in tn folder and changing maxpics value to 9
    Game.java
    package com;
    //Concentration Game
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.lang.reflect.InvocationTargetException;
    import java.util.ArrayList;
    import java.util.Collections;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    public class Game extends JFrame implements ActionListener {
         private static final long serialVersionUID = 1L;
         public static void main(String args[]) throws InterruptedException,
                   InvocationTargetException {
    System.out.println();
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
             Game cg = new Game();
              cg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         Logic logic;
         private int[][] arr;
         private Container contents;
         private JLabel controlLabel;
         private JPanel controlPanel;
         private JButton[][] gameBoardLabel;
         private JPanel gamePanel;
         private ArrayList<ImageIcon> iial;
         private boolean isNewAction = true, isFirstAction = true;
         private JButton prev, pres;
         private long s_time, e_time, t_time;
         private int SIZE, arrvalue, maxpics = 51, pairscount, no_of_pairs;
         public Game() {
              super("Concentration Game");
              logic = new Logic();
              logic.populateArray();
              logic.shuffle();
              logic.printArray();
              arr = logic.getArray();
              SIZE = logic.getSize();
              no_of_pairs = (SIZE * SIZE) / 2;
              iial = new ArrayList<ImageIcon>();
              for (int i = 1; i <= maxpics; i++) {
                   iial.add(new ImageIcon(this.getClass().getClassLoader()
                             .getResource("tn/image" + i + ".jpg")));
              Collections.shuffle(iial);
              System.out.println("Completed loading images");
              contents = getContentPane();
              contents.setLayout(new BorderLayout());
              gameBoardLabel = new JButton[SIZE][SIZE];
              new JPanel();
              gamePanel = new JPanel();
              controlPanel = new JPanel();
              gamePanel.setLayout(new GridLayout(SIZE, SIZE, 5, 5));
              controlLabel = new JLabel("Game not started");
              for (int r = 0; r < gameBoardLabel.length; r++) {
                   for (int c = 0; c < gameBoardLabel[r].length; c++) {
                        arrvalue = arr[r][c];
                        System.out.println(arrvalue);
                        if (arr[r][c] == 0) {
                             gameBoardLabel[r][c] = new JButton();
                             gameBoardLabel[r][c].setEnabled(false);
                        else
                             gameBoardLabel[r][c] = new JButton();
                        gameBoardLabel[r][c].addActionListener(this);
                        gameBoardLabel[r][c].setName("" + arrvalue);
                        gameBoardLabel[r][c].setPressedIcon(iial.get(arrvalue));
                        gamePanel.add(gameBoardLabel[r][c]);
              controlPanel.add(controlLabel);
              contents.add(gamePanel, BorderLayout.CENTER);
              contents.add(controlPanel, BorderLayout.SOUTH);
              setSize(400, 500);
              setVisible(true);
              System.out.println(this);
         @Override
         public void actionPerformed(ActionEvent e) {
              JButton jb = (JButton) e.getSource();
              // System.out.println(jb.getName());
              System.out.println(e.getSource());
              if (isFirstAction) {
                   controlLabel.setText("Game Started");
                   s_time = System.currentTimeMillis();
                   isFirstAction = false;
                   System.out.println(this);
              if (isNewAction) {
                   prev = pres = jb;
                   jb.setIcon(iial.get(Integer.parseInt(jb.getName())));
                   isNewAction = false;
                   return;
              prev = pres;
              pres = jb;
              if (pres == prev)
                   return;
              if (pres.getName().equals(prev.getName())) {
                   pres.setIcon(iial.get(Integer.parseInt(pres.getName())));
                   pres.removeActionListener(this);
                   prev.removeActionListener(this);
                   controlLabel.setText("pair matched");
                   resetAttributes();
                   System.out.println("haha----last count==" + ++pairscount);
                   if (pairscount == no_of_pairs) {
                        e_time = System.currentTimeMillis();
                        t_time = (e_time - s_time) / 1000;
                        controlLabel.setText("Game Over in " + t_time + " secs");
                        System.out.println("done");
              System.out.println(pres);
              pres.setIcon(iial.get(Integer.parseInt(pres.getName())));
              controlLabel.setText("pair didn't match");
              System.out.println("pres is set now");
              prev.setIcon(null);
              pres.setIcon(null);
              resetAttributes();
         private void resetAttributes() {
              prev = pres = null;
              isNewAction = true;
    Logic.java
    package com;
    import java.util.ArrayList;
    import java.util.Collections;
    import javax.swing.JOptionPane;
    public class Logic{
          ArrayList<Integer> al;
          int arr[][],arrlist[][],elements=1;
          int SIZE;
    int[][] getArray()
              return arrlist;
    int getSize(){
         return SIZE;
    public static void main(String args[]){
         Logic logic =new Logic();
                logic.populateArray();
               logic.shuffle();
               logic.printArray();
               //System.out.println(logic.elements);
    void populateArray(){
         String input=JOptionPane.showInputDialog(null,"Enter Size of the array (less than 11)" );
         SIZE=Integer.parseInt(input);
         int cnt = 0;
         arrlist=new int[SIZE][SIZE];
         al=new ArrayList<Integer>();
         for (int r = 0; r < SIZE; r++)
              for (int c = 0; c < SIZE; c++)
                   al.add(elements);
                   cnt++;
                   if (cnt == 2)
                        cnt = 0;
                        elements++;
    public  void printArray() {
         for (int i = 0; i < SIZE; i++)
          for (int j = 0; j < SIZE; j++)
            arrlist[i][j] = al.get(j + i * SIZE);
            System.out.print(" "+arrlist[i][j]);
          System.out.println();
    public  void shuffle() {
              Collections.shuffle(al);
         if(SIZE%2!=0)
              int cindex=(SIZE*SIZE)/2; //center index
              int celement=al.get(cindex); //center element
              int lindex=al.indexOf(elements); //index of large element
              //al.remove(cindex);
              //al.add(cindex, 0);
              al.remove(lindex);
              al.add(lindex, celement);
              al.remove(cindex);
              al.add(cindex, 0);
    }

  • How do I retain Jbutton text for action event & set img icon on Jbutton

    I need to retain the text on my button as I use this to identify the action event in actionPerformed method when the button is pressed.
    Hoe do I add an image icon to the Jbutton without effecting this?
    [/b]
    class CalcPanel extends JPanel
        implements ActionListener, CurrencyVals
    //currency panel data members
        JButton[] cb = new JButton[4];
    JPanel cbkeys = new JPanel(new GridLayout(4,1));
    //Toolkit tk = Toolkit.getDefaultToolkit();
        //Image img = tk.getImage("D:/temp/ausflag.jpg");
    public CalcPanel(){
    ImageIcon b = new ImageIcon("D:/temp/ausflag.jpg","AUS");
        cb[AUS]= new JButton(b);  //cb[AUS]= new JButton("AUS");
          cbkeys.add(cb[AUS]);
          cb[AUS].addActionListener(this);
    setLayout(new BorderLayout());
        add(display, BorderLayout.NORTH);
        add(keys, BorderLayout.CENTER);
        add(cbkeys, BorderLayout.EAST);
        add(label, BorderLayout.SOUTH);
        public void actionPerformed(ActionEvent evt){
          Object source = evt.getSource();
          int id;
          if (keyBoard) {
            if (source instanceof JButton) {
              String s = ((JButton)source).getText();
    [/b]Regards
    Synfield

    if(keyBoard) { ??! [/b]... do have cause to feel flattered?
    Copy and paste this and save a small eg;- 25px high x 50px wide Jpeg image in the same file and call it "new.jpg", then study it, this posted program (again?) to see where your code went astray.
    THEN, figure out what you want to do with your code ...keep at it!
    Sue x
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class ButtonIcon extends JFrame implements ActionListener {
    String []str ={"abc","def","ghi","jkl","mno","pqr","st","uvw"};
    JButton b[] = new JButton[str.length];
       JButton on = new JButton("ON");
       JButton off = new JButton("OFF");
       JButton picture;
       JPanel panel;
       String str2="";
       Font font = new Font("Comic Sans MS" ,0, 14);
       boolean keyBoard;
       ImageIcon icon = new ImageIcon("new.jpg");
    public ButtonIcon(){
       Container c = getContentPane();
       panel = new JPanel();
       panel.setLayout(new FlowLayout());
       picture = new JButton(icon);
       for (int j=0; j<=str.length-1; j++){
             b[j]= new JButton(str[j]);
             b[j].setFont(font);
             panel.add(b[j]);
             b[j].addActionListener(this);
       on.addActionListener(this);
       off.addActionListener(this);
       panel.add(on);
       panel.add(off);
       panel.add(picture);
       c.add(panel);
       public void paint (Graphics g) {
          super.paint (g);
          Graphics2D G = (Graphics2D) g;
          G.setColor(Color.red);
          G.setFont(font);
          G.drawString(str2, 25, 150);
    public void actionPerformed(ActionEvent evt){
        String command = evt.getActionCommand();
        if (keyBoard) {
           if (evt.getSource() instanceof JButton ) {
               str2 += command;
           if (evt.getActionCommand().equals("OFF")) str2 = "";
        if(command.equals("ON")) keyBoard = true;
        if(command.equals("OFF")) keyBoard = false;
    repaint();
    public static void main (String []args){
       ButtonIcon boo = new ButtonIcon();
       boo.setSize(300,200);
       boo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE );
       boo.setVisible(true);

  • How to put an icon to Jbutton with Jbuilder 5?

    I have tried to make a jbutton with icon on it,
    i create an image icon object and pass it to the jbutton.seticon method...
    When create the image icon, it need the path of the icon file, what is the relative path of image in jbuilder?
    (not absolute e.g file:///)
    Thanks

    What you need to do is
    if your current class is Test and you image file is in the same directory called cat.gif then do the following
    button.setIcon(new ImageIcon(Test.class.getResource("cat.gif")));
    this should work
    if you image file is in the previous directory you just type in "../cat.gif" and if you have a image directory reltaive then you put in "images/cat.gif"
    I hope this helps

  • Adding Icon to JButton

    I have an icon "glass.ico".
    Now I want to add it to my JButton showButton instead of the discription.
    I tried a
    ImageIcon glass = new ImageIcon(System.getProperty("user.dir")+"\\glass.ico);but it did not show anything!
    Below the code of my buttons and their toolbar.
              JToolBar toolBar = new JToolBar();
              showButton = new JButton("Anzeigen");
              showButton.setPreferredSize(new Dimension(90, 10));
              close = new JButton("Schlie�en");
              close.setPreferredSize(new Dimension(90, 10));
              save = new JButton("Speichern");
              save.setPreferredSize(new Dimension(90, 10));
              print= new JButton("Drucken");
              print.addActionListener(new PrintListener(table.getModel()));
              delete = new JButton("Eintrag l�schen");
              delete.setPreferredSize(new Dimension(90,10));
              delete.setVisible(false);
              addActionListeners();
              toolBar.setFloatable(false);
              toolBar.setPreferredSize(new Dimension(600, 30));
              toolBar.setLayout(new BoxLayout(toolBar, BoxLayout.X_AXIS));
              toolBar.add(showButton);
              toolBar.add(print);
              toolBar.add(Box.createRigidArea(new Dimension(50,0)));
              toolBar.add(save);
              toolBar.add(delete);
              toolBar.add(Box.createRigidArea(new Dimension(50,0)));
              toolBar.add(close);

    Hello,
    I believe java can only display, gif, jpg and png images.
    For example:
    JButton newButton = new JButton(new ImageIcon("Image.gif"));

  • Icons in JButtons

    Hi everybody!!
    Someone can tell me if this is correct???
    I wanna put some Icons in my buttons, I have a directory where I stored that images.
    The code I use to add the images is...
    Button butValue=new JButton();
    Icon icon=new ImageIcon("/nombre/images/purify.jpg");
    butValue.setIcon(icon);
    The classpath is set to the directory where is nombre directory.
    It works well at home, but when I tried to run my application in other computer the images aren't loaded.
    Someone knows the solution???
    Thanks a lot

    I'm not sure what your directory structure is but I believe you should not use the leading "/" when specifying the file location. I think the file it is looking for is "c:/nombre/images/purify.jpg"
    If your class is in a directory: c:/java/test. The by removing the "/" I think it will look for a file called "c:/java/test/nombre/images/purify.jpg".
    If that doesn't work then the easiest way to test you program is to move the image into the same directory as the class and just use "purify.jpg" as the filename.

  • Removing ICON on JButton on runtime?

    Hi,
    I am still new to GUI, is there anyway i can remove the image ICON at the button action during runtime. Thanks alot.
    Icon qMark = new ImageIcon("images/qmarkanim.gif");
    button = new JButton[ 10 ]; //create button
    for ( int i = 1; i < 10; i++ ) {
         button[ i ] = new JButton(qMark);
    button[ i ].setFocusPainted( false );//set the visibility of the focus off
    button[ i ].setActionCommand( Integer.toString( i ) );//set action command name
    button[ i ].setFont( new Font( "Dialog", 1, 48 ) );//set the desired font
    button[ i ].setPreferredSize( new Dimension( 100, 100 ) );//square button
    button[ i ].setToolTipText( "Click to make your move" );//tooltiptext display
    button[ i ].addActionListener( new ActionListener() {//action listner
    public void actionPerformed( ActionEvent evt ) {
    buttonAction( evt.getActionCommand() ); }
    //getActionCommand - return the string name of who's action
    p1.add( button[ i ] );
    }//end of for
    private void buttonAction( String btn ) {
    int index = Integer.parseInt( btn );
    if ( button[ index ].getText() == "" ) {//check the button is it filled with text
         button[ index ].setText( sign );//sign = "X"
    status[ index ] = sign;
    checkGameStatus();//method checkGameStatus
    nextMove();//method nextMove
    }//end of if
    else
    JOptionPane.showMessageDialog( MyGame.this,
    "This square is already occupied, \nplease try another one.",
    "Oops...", JOptionPane.ERROR_MESSAGE );

    button.setIcon( null );

  • First the text and then the icon in JButton

    Hi,
    I want to create a button with a String followed by an icon. When I do
    JButton aButton = new JButton("Select", new MetalComboBoxIcon());
    It puts the icon first and then the string. I want to a create a button that looks like JComboBox.
    How would I do this?
    thx.

    setHorizontalTextPosition(SwingConstants.LEFT).
    Check out http://java.sun.com/j2se/1.3/docs/api/javax/swing/AbstractButton.html#setHorizontalTextPosition(int).
    Good luck,
    -- Scott

  • Using icons as Jbuttons, how does the ActionListener distinquish this

    This may sound really simple, but I did search the forums, and also read up as much as I can find about the topic, but I haven't seen a solution.
    I am creating a button out of an image. I've sucessfully (except for a small annoyance, that I am still working on), created this button and sized it to the exact size of the image that is the button. This button, which is an image, sits on a JPanel that has other buttons as well, which are just text. I have the ActionListener check which button is pressed using ActionEvent.getActionCommmand(). But the problem is, with the icon button, there is no text that is associated with it. I was thinking that perhaps I could set some sort of ID for the icon button, but I didn't see any method that let me set that. So how does one distinguish when an icon button has been pressed? Thanks in advance

    This may sound really simple, but I did search the forums, and also read up as much as I can find about the topic, but I haven't seen a solution.The Swing tutorial is the best source of information:
    http://java.sun.com/docs/books/tutorial/uiswing/components/button.html

  • Icons on JButtons

    I wrote a calculator but I wasn't satisfied with the teeny tiny images on the JButtons. So I made the images bigger by using ImageIcons. but now I can't figure out how to get the JButtons to respond when I klick o them. for instance:
    public void actionPerformed(ActionEvent e) {
         String command = e.getActionCommand();
         if (command == "0") {
             gui.display.setText(gui.display.getText() + "0");
    }This is what I had in the first place and it worked fine but now with the ImageIcons I can't figure what the value of "command" should be. If anybody could make a short example for me it would be greatly appreciated

    This is a standard method for all Swing components. You use:
    button.setFont(...);If you don't know what a Font is, then read the API.
    if I don't first see a working example of the code being implemented...If you don't know how to create a Font, then search the forum for examples that use the method in question.
    Could you also give me a working example of how to set the action command? Did you read the API and search for a method that would set the action command?
    Read the JButton API and follow the link to the Swing tutorial on "How to Use Buttons" for a working example.
    Again, this is basic knowledge for writing a Java program. You need to learn how to use the API to take advantage of tutorials and examples already posted in the forum.

  • An icon completely changes a JButton's UI

    This is a Java developer question. I could not elsewhere to ask. Already checked ADC.
    An Aqua JButton appears correctly in a Java 1.6.0 JFrame. But when I add an icon to the JButton, it is no longer an Aqua JButton. Not sure what is painting it, but it is really ugly.
    My question is "Does Apple support icons in JButton and other Java UI components?"
    Thank you,
    Don Leckie

    I could not elsewhere to ask.
    http://discussions.apple.com/category.jspa?categoryID=164

  • Icon on a JButton..

    hi,
    I have been trying to add a icon to JButton, but the icon dosent show up..
    my code..
    ImageIcon s = new ImageIcon("color.gif");
    JButton btn = new JButton("Ok");
    btn.setIcon(s);
    everything works but the icon dosent show up on the button.
    -i have the file color.gif in my directory were the program is.
    for the last 24 hrs i have been trying to figure out why....
    help me out guys..

    I changed the following and it started working, i dont know the reason why? but i will be very glad if someone explains why?
    ----old------
    ImageIcon s = new ImageIcon("color.gif");
    JButton btn = new JButton("Ok");
    btn.setIcon(s);
    ----modified----
    ImageIcon s = new ImageIcon("z:\\java\\color.gif");
    JButton btn = new JButton("Change");
    btn.setIcon(s);
    (\\ - one the actual directory and the other used to escape '\'(dir))

  • Setting Icon Image in JDialog

    The following code sets the top-left icon of a JDialog box.But when I uncomment the line
    'setResizable(false)' the Icon is not seen.
    So how do run the code if I want the JDialog box not Resizable ?
    Code is as follows...................................
    import javax.swing.event.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class Main extends JFrame {
    private AboutBox about;
    public Main() {
    super("Main test");
    setSize(450, 350);
    ImageIcon icon = new ImageIcon("no.gif");
    setIconImage(icon.getImage());
    JButton button = new JButton("Open dialog");
    getContentPane().setLayout(new FlowLayout());
    getContentPane().add(button);
    button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    about = new AboutBox(new JFrame());
    about.setVisible(true);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
    System.exit(0);
    public static void main(String []args) {
    Main main = new Main();
    main.setVisible(true);
    class AboutBox extends JDialog {
    public AboutBox(JFrame owner) {
    super(owner, "About Swing Menu", true);
    ImageIcon icon = new ImageIcon("no1.gif");
    owner.setIconImage(icon.getImage());
    JButton button = new JButton("Close");
    getContentPane().setLayout(new FlowLayout());
    getContentPane().add(button);
    button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    dispose();
    setSize(250, 150);
    // setModal(true);
    // setResizable(false);

    add a component listerner and override the componentResized.
    jframe.addComponentListener(new ComponentAdapter() {
              public void componentResized(ComponentEvent e) {
                        //code to reset back to the original window size
    User can still do the "resizing", but once user releases the mouse, it will reset back to the original size

  • Adding icon in JTableHeader (Java 1.3)

    I need to add Up, Down or not Icon in the header sorted Table with java 1.3.1
    Can you send my some example ?

    This worked in 1.2.
    JButton icon = new JButton(SomeImage.gif);
    table.getColumnModel.getColumn(0).setHeaderValue(icon);
    table.getColumnModel().getColumn(0).setHeaderRenderer( new JComponentCellRenderer() );
    class JComponentCellRenderer implements TableCellRenderer
    /**overwrites the getTableCellRendererComponent method to return
    * a swing componet on the table header
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column)
    return (JComponent)value;
    }

  • Focus rectangle of JButton

    Hi,
    I am working on a GUI. putting some icon buttons (JButton). The problem is I am having buttons quite bigger than my icon picture size (having border arround it) with a rectangle on the button. How can I get ride of that rectangle? How can I make the size of the button exactly equal to the size of icon? And how can I make the look and feel of JButton as the old pressable Button (AWT) style? Appreciate you help and time.

    Okay, there are a few ways of doing each thing that you are talking about here. For example, to make the button look like the old AWT buttons, you can simple make the border a raisedBevel border.
    To make the button be the same size as the image, set the insets of the button to
    new Insets(0,0,0,0);The final part of stopping it drawing the focus, is to use the method
    setFocusPainted(false);This is the easy solution. A more powerful solution, but more difficult, is to override the ButtonUI and draw the button exactly as you want. It may be worth looking how the MetalButtonUI works if you do want to take this route.
    Hope this helps
    wwe8

Maybe you are looking for