Changing JButtons

I have a simple application which needs small images to change dependant on user input.
At the minute I have used an extended JButton (extended to implement mouseListener and focusListener) but I need the image I have on them to change if someone right clicks it. My attempts to get the image to change have failed miserably ;-)
Is it possible to alter components once they have been added to a pane?
If not, what would be the best way to achieve the desired result?
Cheers

Read up on some of these methods in AbstractButton: setIcon(), setSelectedIcon(), setRolloverIcon()...

Similar Messages

  • Problem occured when changing JButton to a type that extends JButton

    I picked up an old extra credit project I was working on from a college class to finish it. Here is what I orginially had as the variable.
    private JButton button_matrix = new JButton[9][9];I added a new class called SodokuCell...
    public class SodokuCell extends JButton {
    ...With a constructor:
    public SodokuCell(int _xCoord, int _yCoord, int _block){
         this.x = _xCoord;
         this.y = _yCoord;
         this.blocknum = _block;
    }I then changed my orginal JButton variable to SodokuCell and when I went to run it my GUI comes up with some odd results.
    http://img168.imageshack.us/img168/7762/oddguihb4.jpg
    When I run my mouse over where the buttons would be I get this
    http://img204.imageshack.us/img204/8895/oddgui2vv1.jpg
    Now what looks like buttons in the top left of each of the panels are not really buttons and I cannot figure out for the life of me how they got there but just changing a variable from a JButton to a class that extends JButton.
    If anyone needs any more code to help me solve this feel free to ask.
    Thanks.
    Message was edited by: gunth82: Changed image links to larger images.
    gunth82

    Ok here is a lot of the code in the GUI class
    public void arrangebuttons(){
              //************************** WEST PANEL ****************************************
              nw_panel.setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.black));
              n_panel.setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.black));
              ne_panel.setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.black));
              w_panel.setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.black));
              center_panel.setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.black));
              e_panel.setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.black));
              sw_panel.setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.black));
              s_panel.setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.black));
              se_panel.setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.black));
              nw_panel.setLayout(new GridLayout(3,3));
              nw_panel.setPreferredSize(new Dimension(panel_size_x, panel_size_y));
              n_panel.setLayout(new GridLayout(3,3));
              n_panel.setPreferredSize(new Dimension(panel_size_x, panel_size_y));
              ne_panel.setLayout(new GridLayout(3,3));
              ne_panel.setPreferredSize(new Dimension(panel_size_x, panel_size_y));
              w_panel.setLayout(new GridLayout(3,3));
              w_panel.setPreferredSize(new Dimension(panel_size_x, panel_size_y));
              center_panel.setLayout(new GridLayout(3,3));
              center_panel.setPreferredSize(new Dimension(panel_size_x, panel_size_y));
              e_panel.setLayout(new GridLayout(3,3));
              e_panel.setPreferredSize(new Dimension(panel_size_x, panel_size_y));
              sw_panel.setLayout(new GridLayout(3,3));
              sw_panel.setPreferredSize(new Dimension(panel_size_x, panel_size_y));
              s_panel.setLayout(new GridLayout(3,3));
              s_panel.setPreferredSize(new Dimension(panel_size_x, panel_size_y));
              se_panel.setLayout(new GridLayout(3,3));
              se_panel.setPreferredSize(new Dimension(panel_size_x, panel_size_y));
              //************************** EAST PANEL ****************************************
              east_nw_panel.setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.black));
              east_n_panel.setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.black));
              east_ne_panel.setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.black));
              east_w_panel.setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.black));
              east_center_panel.setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.black));
              east_e_panel.setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.black));
              east_sw_panel.setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.black));
              east_s_panel.setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.black));
              east_se_panel.setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, Color.black));
              east_nw_panel.setPreferredSize(new Dimension(east_panel_size_x, east_panel_size_y));
              east_n_panel.setPreferredSize(new Dimension(east_panel_size_x, east_panel_size_y));
              east_ne_panel.setPreferredSize(new Dimension(east_panel_size_x, east_panel_size_y));
              east_w_panel.setPreferredSize(new Dimension(east_panel_size_x, east_panel_size_y));
              east_center_panel.setPreferredSize(new Dimension(east_panel_size_x, east_panel_size_y));
              east_e_panel.setPreferredSize(new Dimension(east_panel_size_x, east_panel_size_y));
              east_sw_panel.setPreferredSize(new Dimension(east_panel_size_x, east_panel_size_y));
              east_s_panel.setPreferredSize(new Dimension(east_panel_size_x, east_panel_size_y));
              east_se_panel.setPreferredSize(new Dimension(east_panel_size_x, east_panel_size_y));
              east_nw_panel.setLayout(new GridLayout(3,3));
              east_nw_panel.setPreferredSize(new Dimension(east_panel_size_x, east_panel_size_y));
              east_n_panel.setLayout(new GridLayout(3,3));
              east_n_panel.setPreferredSize(new Dimension(east_panel_size_x, east_panel_size_y));
              east_ne_panel.setLayout(new GridLayout(3,3));
              east_ne_panel.setPreferredSize(new Dimension(east_panel_size_x, east_panel_size_y));
              east_w_panel.setLayout(new GridLayout(3,3));
              east_w_panel.setPreferredSize(new Dimension(east_panel_size_x, east_panel_size_y));
              east_center_panel.setLayout(new GridLayout(3,3));
              east_center_panel.setPreferredSize(new Dimension(east_panel_size_x, east_panel_size_y));
              east_e_panel.setLayout(new GridLayout(3,3));
              east_e_panel.setPreferredSize(new Dimension(east_panel_size_x, east_panel_size_y));
              east_sw_panel.setLayout(new GridLayout(3,3));
              east_sw_panel.setPreferredSize(new Dimension(east_panel_size_x, east_panel_size_y));
              east_s_panel.setLayout(new GridLayout(3,3));
              east_s_panel.setPreferredSize(new Dimension(east_panel_size_x, east_panel_size_y));
              east_se_panel.setLayout(new GridLayout(3,3));
              east_se_panel.setPreferredSize(new Dimension(east_panel_size_x, east_panel_size_y));
              for(int i=0;i<3;i++){
                   for(int j=0;j<3;j++){
                        //************************West Panel*****************************
                        button_matrix[i][j] = new SodokuCell(i,j,1);
                        button_matrix[i][j+3] = new SodokuCell(i,j+3,2);
                        button_matrix[i][j+6] = new SodokuCell(i,j+6,3);
                        button_matrix[i][j].addActionListener(new sodokuListener());
                        button_matrix[i][j+3].addActionListener(new sodokuListener());
                        button_matrix[i][j+6].addActionListener(new sodokuListener());
                        button_matrix[i+3][j] = new SodokuCell(i+3,j,4);
                        button_matrix[i+3][j+3] = new SodokuCell(i+3,j+3,5);
                        button_matrix[i+3][j+6] = new SodokuCell(i+3,j+6,6);
                        button_matrix[i+3][j].addActionListener(new sodokuListener());
                        button_matrix[i+3][j+3].addActionListener(new sodokuListener());
                        button_matrix[i+3][j+6].addActionListener(new sodokuListener());
                        button_matrix[i+6][j] = new SodokuCell(i+6,j,7);
                        button_matrix[i+6][j+3] = new SodokuCell(i+6,j+3,8);
                        button_matrix[i+6][j+6] = new SodokuCell(i+6,j+6,9);
                        button_matrix[i+6][j].addActionListener(new sodokuListener());
                        button_matrix[i+6][j+3].addActionListener(new sodokuListener());
                        button_matrix[i+6][j+6].addActionListener(new sodokuListener());
                        nw_panel.add(button_matrix[i][j]);
                        n_panel.add(button_matrix[(j+3)]);
                        ne_panel.add(button_matrix[i][(j+6)]);
                        w_panel.add(button_matrix[(i+3)][j]);
                        center_panel.add(button_matrix[(i+3)][(j+3)]);
                        e_panel.add(button_matrix[(i+3)][(j+6)]);
                        sw_panel.add(button_matrix[(i+6)][j]);
                        s_panel.add(button_matrix[(i+6)][(j+3)]);
                        se_panel.add(button_matrix[(i+6)][(j+6)]);
                        //************************East Panel*****************************
                        test_display[i][j] = new JLabel(button_matrix[i][j].toString());
                        test_display[i][j].setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black));
                        test_display[i][j+3] = new JLabel(button_matrix[i][j+3].toString());
                        test_display[i][j+3].setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black));
                        test_display[i][j+6] = new JLabel(button_matrix[i][j+6].toString());
                        test_display[i][j+6].setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black));
                        test_display[i+3][j] = new JLabel(button_matrix[i+3][j].toString());
                        test_display[i+3][j].setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black));
                        test_display[i+3][j+3] = new JLabel(button_matrix[i+3][j+3].toString());
                        test_display[i+3][j+3].setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black));
                        test_display[i+3][j+6] = new JLabel(button_matrix[i+3][j+6].toString());
                        test_display[i+3][j+6].setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black));
                        test_display[i+6][j] = new JLabel(button_matrix[i+6][j].toString());
                        test_display[i+6][j].setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black));
                        test_display[i+6][j+3] = new JLabel(button_matrix[i+6][j+3].toString());
                        test_display[i+6][j+3].setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black));
                        test_display[i+6][j+6] = new JLabel(button_matrix[i+6][j+6].toString());
                        test_display[i+6][j+6].setBorder(BorderFactory.createMatteBorder(1, 1, 1, 1, Color.black));
                        east_nw_panel.add(test_display[i][j]);
                        east_n_panel.add(test_display[i][(j+3)]);
                        east_ne_panel.add(test_display[i][(j+6)]);
                        east_w_panel.add(test_display[(i+3)][j]);
                        east_center_panel.add(test_display[(i+3)][(j+3)]);
                        east_e_panel.add(test_display[(i+3)][(j+6)]);
                        east_sw_panel.add(test_display[(i+6)][j]);
                        east_s_panel.add(test_display[(i+6)][(j+3)]);
                        east_se_panel.add(test_display[(i+6)][(j+6)]);
              main_panel.add(nw_panel);
              main_panel.add(n_panel);
              main_panel.add(ne_panel);
              main_panel.add(w_panel);
              main_panel.add(center_panel);
              main_panel.add(e_panel);
              main_panel.add(sw_panel);
              main_panel.add(s_panel);
              main_panel.add(se_panel);
              eastpanel.add(east_nw_panel);
              eastpanel.add(east_n_panel);
              eastpanel.add(east_ne_panel);
              eastpanel.add(east_w_panel);
              eastpanel.add(east_center_panel);
              eastpanel.add(east_e_panel);
              eastpanel.add(east_sw_panel);
              eastpanel.add(east_s_panel);
              eastpanel.add(east_se_panel);

  • Changing JButton Orientation

    Hi friends! I need to add a JButton to a JPanel, but I want to set the orientation to vertical, i.e. the text should appear in a vertical position.
    Any idea?
    Thanks in advance.

    I will create an image with the text I want and then set it as an Icon to the JButton.I had the same thought, and came up with this:import java.awt.Color;
    import java.awt.FlowLayout;
    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.Graphics2D;
    import java.awt.Insets;
    import java.awt.RenderingHints;
    import java.awt.image.BufferedImage;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    public class VerticalButton extends JButton {
        public VerticalButton (String caption, boolean clockwise) {
            Font f = getFont ();
            FontMetrics fm = getFontMetrics (f);
            int captionHeight = fm.getHeight ();
            int captionWidth = fm.stringWidth (caption);
            BufferedImage bi = new BufferedImage (captionHeight + 4,
                    captionWidth + 4, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g = (Graphics2D) bi.getGraphics ();
            g.setColor (new Color (0, 0, 0, 0)); // transparent
            g.fillRect (0, 0, bi.getWidth (), bi.getHeight ());
            g.setColor (getForeground ());
            g.setFont (f);
            g.setRenderingHint (RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            if (clockwise) {
                g.rotate (Math.PI / 2);
            } else {
                g.rotate (- Math.PI / 2);
                g.translate (-bi.getHeight (), bi.getWidth ());
            g.drawString (caption, 2, -6);
            Icon icon = new ImageIcon (bi);
            setIcon (icon);
            setMargin (new Insets (15, 2, 15, 2));
            setActionCommand (caption);
        public static void main (String[] args) {
            SwingUtilities.invokeLater (new Runnable () {
                public void run () {
                    JFrame frame = new JFrame ("Vertical Button Demo");
                    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
                    frame.setLayout (new FlowLayout ());
                    frame.add (new VerticalButton ("Vertical Up", false));
                    frame.add (new VerticalButton ("Vertical Down", true));
                    frame.pack ();
                    frame.setVisible (true);
    }db

  • Problem with JButtons Text field not updating

    Im working on a program (which has its full code included below incase its part of the problem) which wants to change a Jbutton's name during a program. The way I'm trying to make it change is by having a string, "test", be called "before update". then have the jbuttons text equal test. then, in an actionlistener, it changes string test to equal "after update". This doesn't update the Jbuttons text.
    I don't get any errors when I press the button, but the buttons name is not updating. Whats causing the buttons name not to be updated?
    Thanks for help in advance.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*; 
    public class TicTac extends JFrame {
    public int Teamplaying = 0;
    public int CrossA, CrossB, CrossC, CrossD, CrossF, CrossG, CrossH, CrossI, CircleA, CircleB, CircleC, CircleD, CircleE, CircleF, CircleG, CircleH, CirclI, TLB, TMB, TRB, MLB, MMB, MRB, LLB, LMB, LRB = 0;
    String test = "Before Update";
        public TicTac() {
             JPanel TicTac = new JPanel();
             TicTac.setLayout(new GridLayout(3,4));
                  TicTac.add(new JButton(test));
                  TicTac.add(new JLabel("a"));
                  TicTac.add(new JLabel("a"));
                  TicTac.add(new JLabel("a"));
                  TicTac.add(new JLabel("a"));
                  TicTac.add(new JLabel("a"));
                  TicTac.add(new JLabel("a"));
                  TicTac.add(new JLabel("a"));
                  TicTac.add(new JLabel("a"));
                  TicTac.add(new JLabel("a"));
                  TicTac.add(new JLabel("a"));
                  TicTac.add(new JLabel("a"));
                  TicTac.add(new JLabel("a"));
                  TicTac.add(new JLabel("a"));
                  setContentPane(TicTac);
             pack();
             setTitle("Add Numbers Together TicTac");
             setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             setLocationRelativeTo(null);
        class TopLeftBox implements ActionListener {
             public void actionPerformed(ActionEvent e) {
             String test = "After update";
             if (Teamplaying == 0) {
                  CrossA = CrossA + 1;
                  CrossD = CrossD + 1;
                  CrossG = CrossG + 1;
             else {
                  CircleA = CircleA + 1;
                  CircleB = CircleB + 1;
         public static void main(String[]args) {
        TicTac Toe = new TicTac();
        Toe.setVisible(true);
    }

    1) Strings are immutable meaning you can't change them.
    2) Even if you could, the two test strings are completely different variables.
    3) To change JButton text, you should call its setText method.
    4) For a JButton to perform an action on button press, it needs to have an actionlistener added to it via the addActionListener(...) method.
    5) Please read, study, and review the Sun Swing tutorials. You will benefit greatly from having a solid foundation in Swing basics before you try coding in Swing.
    Good luck.
    Edit: a small example code (SSCCE, if you will):
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Frame extends JFrame
        public Frame()
            JPanel panel = new JPanel();
            JButton button = new JButton("Before Update");
            button.addActionListener(new ButtonListener()); // add actionlistener here
            panel.add(button);
            setContentPane(panel);
            pack();
            setTitle("Frame");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setLocationRelativeTo(null);
        private class ButtonListener implements ActionListener
            public void actionPerformed(ActionEvent e)
                // get the button that called this action
                JButton button = (JButton)e.getSource();
                // update the button's text
                button.setText("After update");
        public static void main(String[] args)
            SwingUtilities.invokeLater(new Runnable()
                @Override
                public void run()
                    new Frame().setVisible(true);               
    }Edited by: Encephalopathic on Apr 28, 2008 9:26 PM

  • Changing Tabs in a TabbedPane

    I have created a JTabbedPane with four tabs each containing a panel with a JTable in a scrollpane. When i run i can only view first tab, clciing on the others show an empty tab. It's probably something simple! Another class adds this JPanel into a JFrame. Here is my code:
    import javax.swing.JTable;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.ImageIcon;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class EReg extends JPanel {
    public EReg() {
    JTabbedPane tabbedPane = new JTabbedPane();
    String[] changeOptions = { "standard modules", "resit modules", "other modules",
    "view all changes" };
    JButton button1 = new JButton("Get Details");
    JComboBox changes = new JComboBox(changeOptions);
    changes.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    JComboBox cb = (JComboBox)e.getSource();
    String viewType = (String)cb.getSelectedItem();}
    JPanel labelPanel1 = new JPanel(new GridLayout (2, 1));
    JLabel iDLabel1 = new JLabel("Student ID:");
    JLabel nameLabel1 = new JLabel("Name of Student:");
    labelPanel1.add(iDLabel1);
    labelPanel1.add(nameLabel1);
    JPanel textPanel1 = new JPanel(new GridLayout (2, 1));
    JTextField studID1 = new JTextField();
    JTextField name1 = new JTextField();
    textPanel1.add(studID1);
    textPanel1.add(name1);
    JPanel topPanel = new JPanel();
    topPanel.setLayout(new GridLayout(1,4));
    topPanel.add(labelPanel1);
    topPanel.add(textPanel1);
    topPanel.add(changes);
    topPanel.add(button1);
    JTable viewTable = new JTable();
    JPanel viewPanel = new JPanel(new BorderLayout());
    viewPanel.add(topPanel, BorderLayout.NORTH);
    viewPanel.add(viewTable, BorderLayout.CENTER);
    tabbedPane.addTab("View", viewPanel);
    tabbedPane.setSelectedIndex(0);
    JPanel updatePanel = new UpdatePanel();
    tabbedPane.addTab("Update", viewPanel );
    JPanel approvePanel = new ApprovePanel();
    tabbedPane.addTab("Approve", viewPanel);
    JPanel courseDetPanel = new CourseDetPanel();
    tabbedPane.addTab("Course Details", viewPanel);
    setLayout(new GridLayout(1, 1));
    add(tabbedPane);

    Here is the full code with the tabs...each class compiles but when run, it doesnt show the panel, "vPanel", it just shows an empty panel instead. Thanx.
    import javax.swing.JTable;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.ImageIcon;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JFrame;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class EReg extends JPanel {
    public EReg() {
    ViewPanel vPanel = new ViewPanel( );
    JTabbedPane tabbedPane = new JTabbedPane();
    tabbedPane.addTab("View",null, vPanel,"");
    tabbedPane.setSelectedIndex(0);
    setLayout(new GridLayout(1, 1));
    add(tabbedPane);
    public static void main(final String[] args) {
    JFrame frame = new JFrame("e-Reg Logged in as " );
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {System.exit(0);}
    frame.getContentPane().add(new EReg(),
    BorderLayout.CENTER);
    frame.setSize(800, 500);
    frame.setVisible(true);
    import javax.swing.JTable;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.ImageIcon;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class ViewPanel extends JPanel
    { JPanel viewPanel;
    public JPanel ViewPanel()
    {     String[] changeOptions = { "standard modules", "resit modules", "other modules",
    "view all changes" };
    JButton button1 = new JButton("Get Details");
    JComboBox changes = new JComboBox(changeOptions);
    changes.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    JComboBox cb = (JComboBox)e.getSource();
    String viewType = (String)cb.getSelectedItem();}
    JPanel labelPanel1 = new JPanel(new GridLayout (2, 1));
    JLabel iDLabel1 = new JLabel("Student ID:");
    JLabel nameLabel1 = new JLabel("Name of Student:");
    labelPanel1.add(iDLabel1);
    labelPanel1.add(nameLabel1);
    JPanel textPanel1 = new JPanel(new GridLayout (2, 1));
    JTextField studID1 = new JTextField();
    JTextField name1 = new JTextField();
    textPanel1.add(studID1);
    textPanel1.add(name1);
    JPanel topPanel = new JPanel();
    topPanel.setLayout(new GridLayout(1,4));
    topPanel.add(labelPanel1);
    topPanel.add(textPanel1);
    topPanel.add(changes);
    topPanel.add(button1);
    JTable viewTable = new JTable();
    viewPanel = new JPanel(new BorderLayout());
    viewPanel.add(topPanel, BorderLayout.NORTH);
    viewPanel.add(viewTable, BorderLayout.CENTER);
    return viewPanel;
    }

  • How do I change the image used on an movie project icon? iMovie seems to select an image at random from the images I imported.

    How do I change the image used on an movie project icon?
    iMovie seems to select an image at random from the images I imported.

    Not sure I understand how to use what you have posted. Here's what my init() looks like:
    public void init()
    setLayout(new BorderLayout());
    p=new Panel();
    p.setLayout(new GridLayout(1,1));
    callnowButtonURL = getURL(callnowButtonFilename);
    if (callnowButtonURL != null)
    callIcon = new ImageIcon(callnowButtonURL,"call");
    endcallButtonURL = getURL(endcallButtonFilename);
    if (endcallButtonURL != null)
    endIcon = new ImageIcon(endcallButtonURL);
    b=new JButton(callIcon);
    b.setBorder(new EmptyBorder(0,0,0,0));
    b.setBorderPainted(false);
    b.addActionListener(this);
    p.add(b);
    add(p,"Center");
    Now the ActionListener is basically:
    public void actionPerformed(ActionEvent e)
    if (mybool == false)
    <Perform actions here set mybool to true>
    Change JButton b to use EndIcon
    else
    <Perform actions here set mybool to false>
    Change JButton b to use CallIcon
    Can you clarify how to perform the action I require? You can have a couple of Dukes if you can help me sort this out.

  • An interesting problem with jbutton

    when you jButton.setbackground()
    jButton is not really change it's background,
    not the same as button,
    I can't find a way to change jbutton 's background color then,,
    who know how? :)

    no Sum-shusSue ,
    this away;-
    b1.setBackground(new java.awt.Color(0,0,255)); //blue
    or thataway;-
    b2.setBackground(Color.blue); // or blue
    when b1/b2 is button ,there's no problem
    but you can use in jButton,it don't work
    jButton.setOpaque before setbackground() then is ok

  • IllegalArgumentException: adding window to contentPane

    That's the exception I get on running this, but itdoesn't kill the program. Also, the switchColor() function changes the Box color to red the first time, but does not toggle. I've spent way longer on this then I'm proud to say.
    Please help.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class WindowButton1
    public static void main(String[] args)
         window = new MainWindow("Action example");
         Toolkit theKit = window.getToolkit();          
         Dimension wndSize = theKit.getScreenSize();  
         window.setBounds(0, 0,wndSize.width/2, wndSize.height/2);
         window.addWindowListener(new WindowAdapter()     
              // Handler for window closing event
              public void windowClosing(WindowEvent e)
                   window.dispose();                          
                   System.exit(0);                            
              window.setVisible(true); // Display the window
         static MainWindow window;          
    }//end WindowButton1
    class MainWindow extends JFrame
         MainWindow(String title)
         super(title);
         setJMenuBar(menuBar);                  
         fileMenu = new JMenu("File");
         connectItem = new JMenuItem();                                        
         connectItem = fileMenu.add("Connect...");
         connectItem.addActionListener(menuHandler = new Handler());
         menuBar.add(fileMenu);           
    }//end constructor
    //innerclass to handle "Connect" menu action
    class Handler implements ActionListener
         public void actionPerformed(ActionEvent e)
          win = new ConnectWindow("ColorButton Test");
          getContentPane().add(win,BorderLayout.CENTER);
          setVisible(true);
    }//end inner class
    private JMenu fileMenu;
    private JMenuItem connectItem;
    private JMenuBar menuBar = new JMenuBar(); 
    private Handler menuHandler;
    private ConnectWindow win;
    //separate class to display buttonBox
    class ConnectWindow extends JFrame
    ConnectWindow(String title)
         setTitle("Action Buttons");
         Toolkit kit = Toolkit.getDefaultToolkit();
         Dimension screenSize = kit.getScreenSize();
         int screenHeight = screenSize.height;
         int screenWidth = screenSize.width;
         setSize(screenWidth / 3, screenHeight / 3);
         setLocation(screenWidth / 4, screenHeight / 4);
    //buttons to go into panel
         JButton button1 = new JButton("Color Change");
         JButton button2 = new JButton("Cancel");
         JButton button3 = new JButton("Advanced");
         Dimension buttonSize = new Dimension(100,20);
         button1.setPreferredSize(buttonSize);
         button2.setPreferredSize(buttonSize);
         button3.setPreferredSize(buttonSize);
    //Event handling for the three buttons
         button1.addActionListener(new ActionListener()
         public void actionPerformed(ActionEvent e)
         switchColor();
         repaint();
    //Cancel button closes window
         button2.addActionListener(new ActionListener()
         public void actionPerformed(ActionEvent e)
         dispose();                            
    //Advanced button is dummy for now
         button3.addActionListener(new ActionListener()
         public void actionPerformed(ActionEvent e)
    //place buttons in panel
         Box buttonBox = Box.createVerticalBox();
         buttonBox.add(button1);
         buttonBox.add(button2);
         buttonBox.add(button3);
         //place button box in main window
         getContentPane().add(buttonBox, BorderLayout.CENTER);
         setVisible(true);
         }//end constructor
         public void switchColor()
              isRed = false;
              if (!(isRed))
              getContentPane().setBackground(Color.red);
              else getContentPane().setBackground(Color.white);
              setVisible(true);
              repaint();
              isRed = !(isRed);
         boolean isRed;
         private Box buttonBox;
         private JButton button1, button2, button3;
    }//end ConnectWindow

    Change ConnectWindow to
    class ConnectWindow extends JInternalFrameHope this helps youThanks! The last piece is toggling the colors. Here's my actionPerformed method, and the method it calls (taken from the above code:
    button1.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    switchColor();
    repaint();
    public void switchColor()
    isRed = false;
    if (!(isRed))
    WindowButton1.window.getContentPane().setBackground(Color.red);
    else getContentPane().setBackground(Color.white);
    setVisible(true);
    repaint();
    isRed = !(isRed);
    boolean isRed;

  • Adding a listener to an integer value?

    Hello All
    Is there a way of adding a listener to an integer value that produce an event (run a method with the object) when an integer value is changed? (Through a object.setValue(int) for example)
    Thanks for any help,
    Harold Clements

    Can any of the kilo-posters (that's with two o's) say if it's considered
    bad form to reuse a class that already exists - albeit for a slighty
    different purpose? What I'm thinking is that the SpinnerNumberModel
    is rather close to what's being looked for - the differences being that
    it'll handle any Numbers and has a "next" functionality that we ignore.
    Something like:import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Random;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.SpinnerNumberModel;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    public class NumberEg extends JFrame {
         private SpinnerNumberModel intModel;
         private Random rand = new Random();
         private JLabel aLabel;
         public NumberEg() {
                   // a thing that responds to changes - there could be
                   // many of these
              aLabel = new JLabel("I respond to changes...");
              add(aLabel, BorderLayout.CENTER);
                   // the thing which changes
              intModel = new SpinnerNumberModel(0, null, null, 0);
                   // a change listener which glues the two previous
                   // together - again there could be a number of these
              intModel.addChangeListener(new ChangeListener(){
                   public void stateChanged(ChangeEvent evt) {
                        aLabel.setText(intModel.getValue().toString());
                   // Meanwhile events like button clicks *cause* the
                   // changes
              JButton but = new JButton("Click me!");
              but.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt) {
                        intModel.setValue(rand.nextInt());
              add(but, BorderLayout.NORTH);
              but = new JButton("Reset");
              but.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt) {
                        intModel.setValue(0);
              add(but, BorderLayout.SOUTH);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              pack();
         public static void main(String args[]) {
              NumberEg test = new NumberEg();
              test.setVisible(true);
    }

  • Difference between manual resize and repaint, invalidate, validate etc etc?

    Using Jdk 1.5 and under windows XP I am drawing directly in a JPanel.
    And thus creating a drawing of my own when the system calls:
    public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D)g;
    Line2D lineInArrow =
    new Line2D.Double(. . . );
    g2.draw(lineInArrow);
    Ellipse2D ellipse = new Ellipse2D.Double(. . . );
    g2.draw(ellipse);
    The program of course has much more detail but that is the essence of it.
    Now, it turns out that my drawings sometimes become rather messed up and needs to be redrawn so I have tried calling. repaint(), invalidate(), validate(), paintImmediately() in many different combinations and several times.
    As the system is a more complex than just a JPanel - the JPanel is
    contained in a JScrollPane for instance and all is set in a JDialog - I have also tried calling the different parts with these methods and in many different combinations.
    Even calling the parts repeatedly from another Thread so that the methods get called every second or so does not help.
    NOTHING HAPPENS to the messed up drawing
    UNLES I DO A MANUAL RESIZE of the window. Then the drawing becomes OK!!!
    Yes, you guessed right, I have also tried resizing from the program
    by calls such as:
    Dimension currentSize = this.getSize();
    this.setSize(100, 100);
    this.setSize(currentSize);
    repaint();
    The window flickers - gets smaller and then gets back to its original size.
    But the drawing, if messed up, is still messed up in exactly the same way.
    SO WHAT IS HAPPENING WHEN I DO A MANUAL RESIZE BUT NEVER HAPPENS WHEN I DO ANY OF THE ABOVE?
    And, can I somehow initiate this - whatever it is - by programming rather than by a manual resizing of the window??

    With messed up I simply mean that it is not properly redrawn.
    For example a rectangle that should have been drawn is not shown - not drawn. Or a String is not drawn in its proper place.
    But when I do a manual resize (using the mouse) things are drawn correctly. Sometimes I have to do more than one resize to get everything drawn correctly.
    I might also add that I have tried some other more or less weird strategis to get this "manual resize like painting" activated such as:
    Calling the paintComponent method directly:
    Graphics g = this.mainDrawPanel.getGraphics();
    mainDrawPanel.paintComponent(g);
    Trying to make the system understand that something DO have changed:
    JButton aDummyButton = new JButton("Hi there - did you see me??");
    mainDrawPanel.add(aDummyButton);
    this.repaint();
    mainDrawPanel.remove(aDummyButton);
    this.repaint();
    Nothing makes anything happen - except the manual resize of the window.
    So what is so special about a manual resize of a window? What actually goes on when this happens? - That does NOT happen in all the other attempts?

  • Suitable GUI component

    hi,
    i got a gui screen to show availability of a badminton court.Currently I have a set of buttons side by side to indicate each hour.
    If venue is free for that hour,I would set colour as green,other wise red.
    My question is there any other bettern gui component to set colour to mark availability of the court?
    Thanks

    if its just a colored component with text you can you a JLabel.
    if you need a button its exactly as much work to use a JButton.
    *though if i recall correctly, people sometime have problems changing JButton colors?                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • How do you change the text of a JButton?

    This question probably has a simple answer. If I've already created multiple JButtons with no text inside them and I want to change the text inside them later, what method do I call?

    ksg089 wrote:
    This question probably has a simple answer. If I've already created multiple JButtons with no text inside them and I want to change the text inside them later, what method do I call?Someone will give you the direct answer, but the best answer is this: learn to read the API. This is a skill that will help you immensely more than my just telling you the method. It's a "set" method, I believe that it is in one of JButton's ancestors (AbstractButton?), and when you see it, it will be obvious to you that this is the solution. Good luck!
    the link is [here.|http://java.sun.com/javase/6/docs/api/javax/swing/JButton.html]
    Edited by: Encephalopathic on Mar 28, 2008 10:25 PM

  • Why does JButton background color change when  clicking ?

    Hello,
    I have defined :
    JButton mybutton = new JButton(Icon xxx) ;
    with no associated text and I set both foreground and background colors to black, and an empty border.
    This is because the background color of the container which contents this button is also black and I want to see only the button icon.
    When I click on the icon , the button background color becomes grey. How can I change this to make it remains black ?
    Thanks a lot.
    Gege

    Well, the color changes because that is how the look and feel is defined,
    presumably to give better feedback to the user that she has clicked the
    button.
    If you don't want this, you could try using a different L&F which doesn't do this.
    Alternatively, If you've only got the one button, you could just do
        UIManager.put( "Button.select", Color.BLACK );If you have multiple buttons, and you want the other buttons to behave
    normally, you can extend the one button and have it change the color
    while it is pressed, e.g.,
    import java.awt.*;
    import java.io.IOException;
    import java.net.URL;
    import javax.swing.*;
    public class ButtonSelect extends JFrame {
         public ButtonSelect() throws IOException {
              super();
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JPanel panel = new JPanel();
              panel.add( new JButton( "Normal" ) );
              Image img = Toolkit.getDefaultToolkit().getImage( new URL("http://www.google.com/intl/en/images/logo.gif" ) );
              ImageIcon ii = new ImageIcon( img );
              JButton b = new JButton( ii ) {
                   static final private String KEY = "Button.select";
                   public void paint( Graphics g ) {
                        Color save = null;
                        if ( getModel().isArmed() && getModel().isPressed() ) {
                             save = UIManager.getColor( KEY );
                             UIManager.put( KEY, Color.WHITE );
                        super.paint( g );
                        if ( save != null )
                             UIManager.put( KEY, save );
              b.setForeground( Color.WHITE );
              b.setBackground( Color.WHITE );
              b.setFocusPainted( false );
              panel.add( b );
              getContentPane().add( panel );
              pack();
              setVisible( true );
         public static void main( String[] a ) throws IOException {
              new ButtonSelect();
    }

  • JButton changes size

    My button changes size when it has label START and STOP. How can i do, it not changes (sorry for my english)
      import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Ramka extends JFrame {
         JButton b2 = new JButton("START");
         JPanel p1 = new JPanel(new FlowLayout());
        JPanel p2 = new JPanel();
        JButton b1 = new JButton("NOWA GRA");
         public Ramka() {
              setTitle("Waz");
              setSize(500,350);
              setLocation(200,100);
              setResizable(false);
            //JButton b2 = new JButton("START");
            Container cp = getContentPane();
            p1.setBackground(Color.blue);
            p2.setBackground(Color.red);          
            cp.add(BorderLayout.NORTH,p1);
            cp.add(p2);
            p1.add(b1);
            //b2.setText("STOP");
              p1.add(b2);
              b2.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent e){
                        if (b2.getText()=="START") {
                        b2.setText("STOP");}
                        else {
                             b2.setText("START");
    public class Waz {
         public static void main(String[] args) {
              Ramka ramka = new Ramka();
            ramka.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            ramka.show();
    }

    Add this as the last line of the constructor of Ramka:
    b2.setPreferredSize(b2.getPreferredSize());

  • Changing images on JButtons

    hi all,
    I have a collection of icons that having images available in multiple sizes. The program my company is working on is geared towards deaf/hard of hearing and sight impaired individuals.
    I have assigned all the buttons images - however I want to be able to change the image on the button at a user's whim.
    I have all the buttons in a collection and wanted to just iterate through them, retrieve the path of the image associated with them, modify it so that it reflects the right path for the right sized images, and then set it back to the button.
    I can't figure out or find where that property is.
    Can anyone help?

    I have to agree with camickr, storing buttons in a collection isn't really Swingish.
    Generally you assign actions to buttons, and for reusability's sake, you assign icons to these actions. If you change a button's action, when the icon is defined in the action, the icon (and text) change as well.
    Try this (example that switches button actions when a button is clicked):
    Test.java
    import java.awt.event.ActionEvent;
    import javax.swing.*;
    public class Test extends JFrame{
         private static final long serialVersionUID = 1L;
         private static AbstractAction [] actionList;
         public static void main( String args[]) throws Exception {
              JFrame f = new JFrame();
              f.setSize( 400, 400 );
              actionList = new AbstractAction[]{
                   new IconAndTextAction( "Foo", "/images/lock_function.png", 1 ),
                   new IconAndTextAction( "Bar", "/images/lock_payment.png", 0 )
              f.getContentPane().add( new JButton( actionList[0] ) );
              f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              f.setVisible( true );               
         private static class IconAndTextAction extends AbstractAction{
              private static final long serialVersionUID = 1L;
              private int nextinline;
              public IconAndTextAction( String text, String iconPath, int next ) {
                   putValue( Action.NAME, text );
                   putValue( Action.LARGE_ICON_KEY,
                        new ImageIcon(
                             Test.class.getResource( iconPath )
                   nextinline = next;
              @Override
              public void actionPerformed(ActionEvent e) {
                   ((JButton)e.getSource()).setAction( actionList[nextinline] );               
    }GL
    Alex

Maybe you are looking for