Adding Buttons

Hi,
I've got a JPanel including a few JButtons in a JApplet. All JButtons have an ActionListener (JButton.addActionListener(this);). There is an other JButton. By clicking on this Buttons an new Jbutton should be added to the JPanel and the JPanel should refresh.
It's no problem to add the button, but how can I add the ActionListener? addActionListener(this); does not work because the button is added in the ActionPerformed method of the Applet.
My second problem is to refresh the JPanel. I tried JPanel.repaint(); and getContentPane().repaint but it does not work.
Any ideas?
Thank you,
Jörn

what you should do is use <JPanel>.updateUI(); and <JPanel>.revalidate();
then for the action listener do what is listed below:
<JButton>.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
<then stick you shit in here>

Similar Messages

  • Adding Buttons to a ScrollPane??

    Hello Swing people,
    I have had this problem now for quite some time and still have had no luck in getting it right. I am coding an ordering system and on this form is a Jtable displaying product details. Beside the Jtable are category buttons one after the other in a vertical line and there are 18 of them - meaning they cannot fit on the screen!! Therefore i want these buttons to be in some kind of scollpane or list so they can all be viewed.
    I thought this would be a simple matter of adding buttons to a scrollpane and then to the panel but this has proved not the case! Does anyone know how i could do this as i have been trying this for too long without the help of you geniuses???
    To give u an idea of what i was trying here is a snippet of my code:
    import javax.swing.*;
    public class junk2 extends JFrame{
         junk2()    {
         JPanel panel = new JPanel();
         panel.setLayout(new java.awt.GridLayout(0, 1) );
         JButton []button = new JButton[20];
         for(int i=0; i<button.length; i++) {
              button=new JButton(""+(i+1) );
              panel.add(button[i]);
         JScrollPane scroll = new JScrollPane(panel);
         getContentPane().add(scroll, java.awt.BorderLayout.CENTER);
         setSize(50, 100);
         setDefaultCloseOperation( EXIT_ON_CLOSE );
         public static void main(String []args) {
              new junk2().show();
    This code is fine and puts buttons in a vertical line but the buttons only have numbers on them from 1-20, i want the names of the buttons i have declared to be in here - therefore allowing the action performed on these buttons to be recognised and therefore work too! - anyone know how to get around this??
    Also the scrollpane with these buttons in apears in a whole new frame being that it is a small test program but does anyone know how to ensure the buttons appear in the scrollpane only and not in a new frame??
    all 25 dukes if someone can sort this long problem out!!!

    Hi guys thanks a lot for your replies, i compiled both of them and they are fine! the first reply is more what i am looking for but there is still a problem, i am finding it difficult to incorporate this piece of code into my order form class.
    Im trying to take out the current declarations of my JButtons and replace it with the code i was given (reply 1) and obviously keep my action performed methods there as they will be the same but cant seem to do this!
    If anyone can add in the code from reply 1 into my code below or at least help me i will give u the 25 dukes, taking into consideration i still want the form (panel) to be displayed as well as the panel or scrollpane containing the JButtons???
    Can u help - cheers in advance!!
    Pc
    public class OrderForm extends JFrame implements ActionListener {
         private JPanel panel;
         private JButton saveArchive,unCompleted,submitOrder,checkSheet,clear,exit,bread,fruit,dairy,
    salads,cakes,frozen,meat,cheeses,sauces,dry,drinks,soup,cleaning,boxes,cups,cutlery,lids,misc,stick,soup2;
         private JScrollPane pane;
         private JTextField textorderno,textorderdate,textdelivdate,textemp,textshop,textsupp;
         private JLabel heading1,heading2,orderno,orderdate,delivdate,emp,shop,supplier;
         private String todaysDate, deliveryDate;
         private ResultSet result;
         private ResultSet shops;
         private int column_count;
         private JComboBox combobox;
         ResultSetTableModel model = new ResultSetTableModel();
         Result rs = new Result(); 
         Orders orderSaving = new Orders();
         ProductOrders tableSaving = new ProductOrders();
         private boolean save;
         JTable table;
         public OrderForm()throws SQLException {
              displayForm();
              displayFields();//Have not provided coz it aint needed for this
              displayButtons();//Wont need this anymore i dont think
              getContentPane().add(panel);
              setVisible(true);
         public void displayForm() throws SQLException{
              setTitle("Pret Ordering System");
              setSize(700,600);
              // Center the frame
              Dimension dim = getToolkit().getScreenSize();
              setLocation(dim.width/2-getWidth()/2, dim.height/2-getHeight()/2);
              //Creates the coloured bored around the panel
              panel = new JPanel();
              panel.setLayout( null );
              Border paneltitled = BorderFactory.createLineBorder(Color.red.darker().darker(),10);
              panel.setBorder(paneltitled);
              ResultSet result = rs.setBreadProds();
              model.fillTableModel(result);
              table = new JTable(model);
              for(int i = 0; i < column_count; i++) {          
                   table.getColumnModel().getColumn (i).setPreferredWidth (200);                   
              table.setSelectionForeground( Color.white );
              table.setSelectionBackground( Color.red.darker().darker() );
              pane = new JScrollPane(table);
                  pane.setBounds(190, 230, 440, 200);
                  panel.add(pane);
              combobox = new JComboBox();
              ResultSet shops = rs.getSupplierNames();
              while(shops.next()){  
                   combobox.addItem(shops.getString("supplier_name"));
    //Hope you can help - cheers

  • Captiave 2 - Adding Buttons to Question Slides

    I need to use the Captivate Question Slide "maker" to create
    interactive questions with navigation back to the "Jeopardy-esque"
    main page. When doing so, the question slide maker prevents adding
    buttons/navigation, etc.
    Any work arounds, hints, suggestions?
    Thanks...

    Hi Beta Bob and welcome to our community
    As you have seen, you cannot insert interactive objects
    (Buttons, Click Boxes or Text Entry Boxes) on Question slides.
    The only workaround I can think of is to sort of simulate the
    question slide using these objects on a standard slide.
    Cheers... Rick

  • Standard buttons not displaying ALV when added button by creating PF status

    Hi  All,
    I have added a button(using SE41) in application toolbar for ALV grid using Factory method.But the problem is I am unable to see the standard tool bar buttons(Layout,Download,Mail etc).
    Even I tried adding buttons(using standard FCODES) to the PFstatus.Now the buttons are visible but the functionality is not working for all buttons.Its working only for Graphic and Change layout buttons.
    Can any one suggest...??
    -Phaniram

    Disregard DKS's response...that's the older stuff and you're using NetWeaver ALV.
    In SALV you can cause those buttons to appear, but you may need to copy the SALV_STANDARD GUI from one of the SALV* named program using SE80...sounds like you have that part, but you may need to turn functions ON...
    Perhaps something like this would help:
    data:  gr_f_list  type ref to cl_salv_functions_list,
             gr_alv     type ref to cl_salv_table,
    SALV toolbar & GUI functions
      gr_f_list = gr_alv->get_functions( ).     "Get Toolbar functions
      gr_f_list->set_all( abap_true ).          "All On
      gr_f_list->set_view_lotus( abap_false ).  "Lotus 123 off
      gr_f_list->set_view_excel( abap_false ).  "Excel in Place Off
      gr_f_list->set_graphics( abap_false ).    "Graph tool off
    For undesired buttons, set each tool OFF after turning all ON.

  • How to make separation between added buttons into a jToolBar?

    Hi friends,
    I have made a jToolBar (using NetBeans IDE 5.5) with several buttons, but i dont know how to make custom separation between those added buttons. I will appreciate it if anyboy give me some tips.
    Thanks in advance,
    Reza_mp

    I don't know about NetBeans but yeah U can add horizontal atruts and verticals struts between two components, i.e.
    1.) add first component
    2.) add horizontal or vertical struts(according to ur toolbar)
    3.) add second component
    4.) add add horizontal or vertical struts(according to ur toolbar)
    this will definitely solve ur problem.
    If it does, don't forget to pay ur points.

  • Recently added     button accidently deleted How do I get this button back?

    'Recently added' button accidently deleted How do I get this button back?
    I can not find where my tracks off a cd are
    on my imac with out this button or
    icon on the left hand side of itunes.
    HELP I am technically challenged but
    relatively intelligent musician!

    catcowkitty wrote:
    'Recently added' button
    that button is actually a *smart playlist* which you can create yourself quite easily.
    in iTunes, choose +new smart playlist+ from the file menu and recreate the following rules:
    the screenshot is from my original recently added playlist.
    JGG

  • Can i restore the 'recently added' button in the sidebar of iTunes?

    It happend that I accidencially erased the 'Recently Added' button from the sidebar in iTunes which is a bit of a dissaster for me as I often add mp3's from musicproductions elsewere. It makes it quite difficult to find the songs without that button.

    Hi Jimzgoldfinch
    It worked, i have a new smart playlist up and running. That's great, thanks a lot!
    Sam Foh

  • Adding button to a custom table cell (and handling them)

    Hi
    I'm wondering if it's possible to add a button on each row of a table view using a custom table cell view. If it's possible, I'm really wondering how I can handle the click events on these buttons.
    Thanks

    No.
    Try creating a view and adding it to a cell. Let us know what problems you have, and we can try to help.

  • Adding Button to Active Form

    Hi,
    I created button in PO  on Form load event. its working fine.but
    how to add a button on the active(PO)  form once My add-on is started?
    Regards,
    Ganesh k

    Hi,
    i checked for the existance of my button in my active form, if not exist i added my button in et_FORM_ACTIVATE  Event. its working now.
    If pVal.EventType = et_FORM_ACTIVATE And pVal.FormTypeEx = "142" And FLAG = False Then
                oOrderForm = sbo_application.Forms.GetFormByTypeAndCount(pVal.FormType, pVal.FormTypeCount)
                Dim ii As Integer
                For ii = 0 To oOrderForm.Items.Count - 1
                    If oOrderForm.Items.Item(ii).UniqueID = "MyBtnId" Then
                        FLAG = True
                    End If
                Next ii
                If FLAG = False Then
                    ADDBUTTON()
                End If
            End If
    Thanks For the Suggestions..
    regards,
    Ganesh K

  • Problem wiht added button on invoice form

    I have added a custom button on invoice form.
    Scenario 1:
    I open the invoice form then the custom button is added and the et_ITEM_PRESSED event on custom button in catched. All is ok!
    Scenario 2
    I open a custom form and after close it.
    After I open the invoice form then custom button is added but et_ITEM_PRESSED event on custom button in not catched!!
    Could somebody please help me?
    Thanks

    Hi Domenico,
    It could be that the custom form gets an exception and then no other events might be caught. Try and put try...catch clauses around all your code and show messages when an error is received. This might be the cause of the problem - an unhandled exception.
    Hope it helps,
    Adele

  • Adding buttons on title line

    I am relatively new to Flex and I have run into a slight
    problem that I that I think is because of lack of experience. I
    have a panel and I have set the title attribute but now I am
    required to add buttons to the right of the title. I am not sure
    what the best way to do this is or even if it is viable. I have
    read in other places throughout the internet that it is possible to
    add buttons to the title of an object, but I do not know how to do
    to proceed. I have thought about it and I think making an HBox and
    adding a label for the title and then the required buttons might
    work, but when it compiles it leaves a blank space above my new
    HBox that just does not look good. Is there someway to override the
    title of the panel or set its height to 0, or better yet some way
    to add buttons to the title line of the panel? Any help would be
    appreciated.

    Check out post...
    http://www.adobe.com/cfusion/webforums/forum/messageview.cfm?forumid=60&catid=585&threadid =1271263&highlight_key=y&keyword1=button

  • Adding button events stops core functonality!

    This should be an easy one; here is a piece of code that i have adapted from the Java website!
    The problem occured when i added the code for the buttons in Public void actionPerformed.
    Instead of animating; the picture is static and will only advance by 1 frame if i press either the play or stop buttons! if u remove the code for the buttons the animation works fine!
    what am i doing wrong?
    (T1 to T10 can be any random gif pictures)
    I was wondering if i need a new actionPerformed class or something????
    hope you can help me
    kind regards
    RSH
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class ImageSequenceTimer extends JFrame
                                    implements ActionListener {
        ImageSQPanel imageSQPanel;
        static int frameNumber = -1;
        int delay;
        Thread animatorThread;
        static boolean frozen = false;
        Timer timer;
         //Invoked only when this is run as an application.
        public static void main(String[] args) {
            Image[] waving = new Image[10];
            for (int i = 1; i <= 10; i++) {
                waving[i-1] =
                    Toolkit.getDefaultToolkit().getImage("images/T"+i+".gif");
            JFrame f = new JFrame("ImageSequenceTimer");
            f.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            ImageSequenceTimer controller = new ImageSequenceTimer();
            controller.buildUI(f.getContentPane(), waving);
            controller.startAnimation();
            f.setSize(new Dimension(350, 350));
            f.setVisible(true);
        //Note: Container must use BorderLayout, which is the
        //default layout manager for content panes.
        void buildUI(Container container, Image[] dukes) {
            int fps = 10;
            //How many milliseconds between frames?
            delay = (fps > 0) ? (1000 / fps) : 100;
            //Set up a timer that calls this object's action handler
            timer = new Timer(delay, this);
            timer.setInitialDelay(0);
            timer.setCoalesce(true);
            JPanel buttonPanel = new JPanel();
            JButton play = new JButton("PLAY");
            play.addActionListener(this);
            JButton stop = new JButton("STOP");
            stop.addActionListener(this);
            JButton restart = new JButton("RESTART");
            JButton back = new JButton("Back");
            imageSQPanel = new ImageSQPanel(dukes);
            container.add(imageSQPanel, BorderLayout.CENTER);
            imageSQPanel.addMouseListener(new MouseAdapter() {
                public void mousePressed(MouseEvent e) {
                    if (frozen) {
                        frozen = false;
                        startAnimation();
                    } else {
                        frozen = true;
                        stopAnimation();
           container.add(buttonPanel, BorderLayout.SOUTH);
           buttonPanel.add(play);
           buttonPanel.add(stop);
           buttonPanel.add(restart);
           buttonPanel.add(back);
        public void start() {
            startAnimation();
        public void stop() {
            stopAnimation();
        public synchronized void startAnimation() {
            if (frozen) {
                //Do nothing.  The user has requested that we
                //stop changing the image.
            } else {
                //Start animating!
                if (!timer.isRunning()) {
                    timer.start();
        public synchronized void stopAnimation() {
            //Stop the animating thread.
            if (timer.isRunning()) {
                timer.stop();
        public void actionPerformed(ActionEvent e) {
            //Advance the animation frame.
            frameNumber++;
            //Display it.
            imageSQPanel.repaint();
            {JButton button = (JButton) e.getSource();
             String label = button.getText();
             if("PLAY".equals(label))
             { start();
             else if("STOP".equals(label))
             { stop();
        class ImageSQPanel extends JPanel{
            Image dukesWave[];
            public ImageSQPanel(Image[] dukesWave) {
                this.dukesWave = dukesWave;
            //Draw the current frame of animation.
            public void paintComponent(Graphics g) {
                super.paintComponent(g); //paint background
                //Paint the frame into the image.
                try {
                    g.drawImage(dukesWave[ImageSequenceTimer.frameNumber%10],
                                0, 0, this);
                } catch (ArrayIndexOutOfBoundsException e) {
                    //On rare occasions, this method can be called
                    //when frameNumber is still -1.  Do nothing.
                    return;
    }

    You get ClassCastException at JButton button = (JButton) e.getSource(); therefore
    1. Always look if there are any exceptions thrown
    2. In this case e.getSource() does not always return JButton object reference, actionPerformed is also called by Timer. This is a source of your exception: you cast correctly only once - when button is pressed; then Timer calls actionPerformed, exception is thrown and animation stops.
    Here s corrected code
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Test extends JFrame
                                    implements ActionListener {
        ImageSQPanel imageSQPanel;
        static int frameNumber = -1;
        int delay;
        Thread animatorThread;
        static boolean frozen = false;
        Timer timer;
        JButton play, stop; // <------------------------------------
         //Invoked only when this is run as an application.
        public static void main(String[] args) {
            Image[] waving = new Image[10];
            for (int i = 1; i <= 10; i++) {
                waving[i-1] =
                    Toolkit.getDefaultToolkit().getImage("images/T"+i+".gif");
            JFrame f = new JFrame("ImageSequenceTimer");
            f.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            Test controller = new Test();
            controller.buildUI(f.getContentPane(), waving);
            controller.startAnimation();
            f.setSize(new Dimension(350, 350));
            f.setVisible(true);
        //Note: Container must use BorderLayout, which is the
        //default layout manager for content panes.
        void buildUI(Container container, Image[] dukes) {
            int fps = 10;
            //How many milliseconds between frames?
            delay = (fps > 0) ? (1000 / fps) : 100;
            //Set up a timer that calls this object's action handler
            timer = new Timer(delay, this);
            timer.setInitialDelay(0);
            timer.setCoalesce(true);
            JPanel buttonPanel = new JPanel();
            play = new JButton("PLAY"); // <------------------------------------
            play.addActionListener(this);
            stop = new JButton("STOP"); // <------------------------------------
            stop.addActionListener(this);
            JButton restart = new JButton("RESTART");
            JButton back = new JButton("Back");
            imageSQPanel = new ImageSQPanel(dukes);
            container.add(imageSQPanel, BorderLayout.CENTER);
            imageSQPanel.addMouseListener(new MouseAdapter() {
                public void mousePressed(MouseEvent e) {
                    if (frozen) {
                        frozen = false;
                        startAnimation();
                    } else {
                        frozen = true;
                        stopAnimation();
           container.add(buttonPanel, BorderLayout.SOUTH);
           buttonPanel.add(play);
           buttonPanel.add(stop);
           buttonPanel.add(restart);
           buttonPanel.add(back);
        public void start() {
            startAnimation();
        public void stop() {
            stopAnimation();
        public synchronized void startAnimation() {
            if (frozen) {
                //Do nothing.  The user has requested that we
                //stop changing the image.
            } else {
                //Start animating!
                if (!timer.isRunning()) {
                    timer.start();
        public synchronized void stopAnimation() {
            //Stop the animating thread.
            if (timer.isRunning()) {
                timer.stop();
        public void actionPerformed(ActionEvent e) {
            //Advance the animation frame.
            frameNumber++;
            //Display it.
            imageSQPanel.repaint();
             if(e.getSource() == play) // <------------------------------------
             { start();
             else if(e.getSource() == stop) // <------------------------------------
             { stop();
        class ImageSQPanel extends JPanel{
            Image dukesWave[];
            public ImageSQPanel(Image[] dukesWave) {
                this.dukesWave = dukesWave;
            //Draw the current frame of animation.
            public void paintComponent(Graphics g) {
                super.paintComponent(g); //paint background
                //Paint the frame into the image.
                try {
                    g.drawImage(dukesWave[Test.frameNumber%10],
                                0, 0, this);
                } catch (ArrayIndexOutOfBoundsException e) {
                    //On rare occasions, this method can be called
                    //when frameNumber is still -1.  Do nothing.
                    return;
    }

  • Adding button in standard screen

    Hi,
    I need to add a button in va01 t.code(Sales order)..When we click that button means it want to open a customized screen.How to add a customized screen in standard t.code..
    I am new to this exits.Can anyone help me how to do this.

    Hi Mahesh,
    For finding any exit for a standard t-code follow this way,
    1) Goto that screen where you need to add button( here VA01)
    2) Click System->Status
    3) There Double click the 'GUI Status' for that screen.
    In VA01 main screen it is A0. So double click that A0
    4) In the Application toolbar there is one exit for adding a button after the Copy button.
    You can insert your button details and give the Function code. Then in the user exit you can capture that function code and process accordingly.
    Though seems easy do it carefully with modification assistant on.
    Cheers,
    Kothand

  • Adding buttons to details overlay

    I am trying to build a showreel using Dan Carr's Web Video template as a basis: what I want to do is create different groupings of short films, so when you click on the background details of one, others are recommended, which may be out of sequence. The tutorial says' ...When a user clicks this area, the media pauses while a related detail element pops up and transitions into view. You can use this feature to add text, links, animations, or any content you prefer to expand upon the chapter's theme.'
    Well, I can't!  I've tried various ways in; lately I've been trying to place button links to other video chapters by extending SimpleButton and adding an onClick function : giving an E4X address of where to go within the config.xml - but can't make it happen. How should I be doing this please?

    I am trying to build a showreel using Dan Carr's Web Video template as a basis: what I want to do is create different groupings of short films, so when you click on the background details of one, others are recommended, which may be out of sequence. The tutorial says' ...When a user clicks this area, the media pauses while a related detail element pops up and transitions into view. You can use this feature to add text, links, animations, or any content you prefer to expand upon the chapter's theme.'
    Well, I can't!  I've tried various ways in; lately I've been trying to place button links to other video chapters by extending SimpleButton and adding an onClick function : giving an E4X address of where to go within the config.xml - but can't make it happen. How should I be doing this please?

  • Adding Button to titlebar

    I just want to ask that is there any way to add button on the title bar, with those three buttons on a right, i.e, Close, Maximize, Minimize. Is there any way for it?

    In general, it is very bad practice to access internal structures of UI delegates. Every time you find yourself casting getUI() result to a specific class and accessing the internal components, you are digging a very nasty hole. In this case, just adding the button is not enough - the internal frame title pane has a custom layout manager that knows nothing about it.
    You will have to dig much deeper and create your own UI delegate for internal frames to handle all the cases (including theme support, rollover effects, layout and RTL). Another option is to use Substance LAF that provides an API to add custom buttons to title panes [1]. This example shows how to do this for top-level frames, but the same would work for internal frames as well.
    [1] https://substance.dev.java.net/docs/api/SetRootPaneCustomTitleButtons.html

Maybe you are looking for

  • Imessage fonts won't change

    I have a new imac--mountain lion--used it a couple times in iMessage and was able to adjust the font size.  All of a sudden it reverted to a small font and when I click on the change font button, it is selectable but does not give me the screen to ch

  • Authentication iMessage Error Yosemite

    I have a collection of Apple kit here (Who doesn't eh!) but have an issue with JUST ONE of them a MacPro using a FireWire Camera. With the Messages Application. When I try and log into iMessage via Messages/Preferences I get the following message. "C

  • Video stutter, etc with Adobe Premiere Elements 8

    Have had the the program for few days, and actually was excited about using it.  I have Windows Vista.  The video that I am trying import is on a Western Digital storage.  The playback in the work area is stutteringm fuzzy and not clear.  I am bangin

  • Can I sell my old Adobe Premiere 6.0 software

    Presently I'm using Premiere Pro CS3 Production Premium software. Earlier, I had purchased the Adobe Premiere 6.0 upgrade on E-bay, but never used the software because I decided to buy CS3. I also own Premiere 5.0 and Premiere Pro. Am I allowed to se

  • Never seen that before

    When I try to open my application there are several logs and that I dont understand why: > <Jun 7, 2010 2:33:51 PM BRT> <Error> <oracle.bpm.analytics.cubes> <BEA-000000> <Exception javax.ejb.EJBTransactionRolledbackException: EJB Exception: ; nested