Resizing a JButton during execution

Hello. I have problems with a JButton resizing during execution. I can set the size of a JButton in my JFrame constructor. However, when I try to change via an ActionListener has defined the JButton even nothing happens. I tried to call invalidate() on the JButton and the JPanel that contains nothing will do. Any help to fix this would be appreciated. Below the source code.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class framebuild extends JFrame
{
     JButton button1, button2;
     JLabel label;
     JPanel labelPanel = new JPanel();
     JPanel buttonPanel = new JPanel();
     
     public framebuild()
     {
          super("Error");
          setDefaultCloseOperation(EXIT_ON_CLOSE);
          setPreferredSize(new Dimension(300,300));
          setLayout(new BorderLayout());
          setResizable(true);
          
          clickresponse responder = new clickresponse();
          
          label = new JLabel("Resize button?");
          button1 = new JButton("OK");
          button1.addActionListener(responder);
          button2 = new JButton("Cancel");
          button2.addActionListener(responder);
          
          
          labelPanel.add(label);
          
          buttonPanel.add(button1);
          buttonPanel.add(button2);
          
          add(labelPanel, BorderLayout.CENTER);
          add(buttonPanel, BorderLayout.SOUTH);
     }
     
     private class clickresponse implements ActionListener
     {
          public void actionPerformed(ActionEvent e)
          {
               if( button1 == e.getSource() )
               {
                    button1.setPreferredSize(new Dimension(100,100));
                    button1.invalidate();
               }
               else
                    System.exit(0);
          }
     }
     
     public static void main( String[] args )
     {
          framebuild frame = new framebuild();
          frame.pack();
          frame.setVisible(true);
     }

}

First of all, a few notes on your code.

  • By convention, Java class names start with a capital letter and the first letter of each internal Word is capitalized. FrameBuild, no framebuild and ClickResponse, not clickresponse.
  • It is usually seen on evil as a diversion from the legacy of needlessly extend a class. Your class could contain a JFrame rather than extend the JFrame.
  • All Swing components should always be created and modified on the EDT and only on the EDT.

    When you make changes that affect the provision of an already visible from container, you must call, ( revalidate() and repaint()sometims) on the container.

    //button1.invalidate();
    buttonPanel.revalidate();
    

    DB

    Edit

  • Avoid the 'standard' listeners who need to identify the source of the event to determine what steps to take. Soon, they develop little handy in any real application.

    Here is the summary of my recommendations, adapted from your code.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class FrameBuild {
    
      JButton button1, button2;
      JLabel label;
      JPanel labelPanel = new JPanel();
      JPanel buttonPanel = new JPanel();
    
      public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
    
          @Override
          public void run() {
            new FrameBuild().makeUI();
          }
        });
      }
    
      public void makeUI() {
        label = new JLabel("Resize button?");
        labelPanel.add(label);
    
        button1 = new JButton("OK");
        button1.addActionListener(new ActionListener() {
    
          @Override
          public void actionPerformed(ActionEvent e) {
            button1.setPreferredSize(new Dimension(100, 100));
            buttonPanel.revalidate();
          }
        });
    
        button2 = new JButton("Cancel");
        button2.addActionListener(new ActionListener() {
    
          @Override
          public void actionPerformed(ActionEvent e) {
            System.exit(0);
          }
        });
    
        buttonPanel.add(button1);
        buttonPanel.add(button2);
    
        JFrame frame = new JFrame("Error");
        frame.add(labelPanel, BorderLayout.CENTER);
        frame.add(buttonPanel, BorderLayout.SOUTH);
    
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 300);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      }
    }
    

    Published by: Darryl Burke

  • Tags: Java

    Similar Questions

    • Resize controls programmatically during execution

      I have a series of controls on a GUI and a GUI I want to be able to resize according to the machine that is running the program.

      Basically, my logic is this. A GUI can fill the available display space, but not all, and must never be directed at a screen that is not designed for.

      Currently my laptop is having display problems and keep chaning the resolution thus masking the parts of my GUI.

      I want to resize (and place all controls visible and indicators - I know that those to whom they are) so that my GUI appears in a space about some default screen resolutions. (800 x 600, 1024 x 768 and 1280 x 1024)

      I can get the position and the limits of control, but I can't change the boundaries of a control (generic) with the property node. It's frustrating. one of my being a listbox controls large multicolumn who takes the largest part of the screen and really need resize according to the resolution of the screen.

      Any ideas?

      James

      Your immediate problem is change the size of a control is available only through specific property (and not generic) nodes.  Use the function "to the more specific" in the palette controls App to convert the reference type.  If the generic reference does not mention this reference type, it will return an error.

      Here's the code that changes all MCLs on public Service 100x200px

      Since you say that you know who controls that you want to change, you can do created references, too.

    • masking steps during execution

      I have a sous-suite that I point the user to when asked to isolate a card failure.  To give them some flexibility, I got a popup that gives them a certain number of options (see attachment).  I have an m.o. that indicates the individual steps these select/run (i.e. '1' or '3' in the png).  Control flow (denoted by '2') is the noise they don't really need to worry and may / will cause confusion (and possibly problems for me if they select them accidentally).  Is there a way to hide these measures flow during execution control so that the user sees '1' and '2' (and other similar 'valid' selections?

      If there wasn't a need explicit to have the flow control logic, then I'd be tempted to compact all in the post of the Popup Message action.

      By setting the Popup Message Action to go to the step, , use Custom Condition (TRUE):

      And by using the following Expression:

      Step.Result.ButtonHit == 1? RunState.Sequence.Main ["MR_RPack_R55"]. UniqueStepId:
      Step.Result.ButtonHit == 2? "" "RunState.Sequence.Main ["End_PCI_Isolation"]." UniqueStepId:
      Step.Result.ButtonHit is 3? RunState.Sequence.Main ["MR_R103"]. UniqueStepId:
      Step.Result.ButtonHit is 4? "" "RunState.Sequence.Main ["PCI_Intf_PT"]." UniqueStepId: «»

      It should be appropriate level following the Popup Message.

      (SequenceFile attached).

      I hope this helps.

      Charlie

    • Why get error during execution the FPGA VI?

      Hello world

      I have a lot of sense of wrong during execution of a program that has been correctly executed previously. I don't know what I did wrong.

      Now, whenever I run this FPGA VI, I get an error (in the attachment). And, then runs the FPGA VI, but it does not give the data required those he supposed to give as output.

      Any help or recommendations would be appreciated also.

      Thank you.

      Hi auree123,

      There are a few reasons for this error
      may occur.  Could you tell us more about what's going on?

      You are
      I get this error when you compile and if so, at what stage?

      It looks like
      as you may be running it in Interactive Mode, which means that you are viewing
      the front of the FPGA VI on the development computer that you are running - is
      that correct?  If so, you could try to create a VI on your host
      Open a FPGA reference and communicate with the FPGA programmatically rather than interactively.

      Thank you

      Morgan S

      Technical sales engineer

    • button conrol min and max range option during execution

      Is it possible to change the window button conrol min and max Beach setting during execution?

      Thank you very much Nick.

    • Edit/delete/add scene coordinates in the table during execution

      Hello world

      I managed to build table allows you to store and record the coordinates of the stage and remind to control steps. However, I need change/remove/add details of scene during execution. I also need to allow the user to directly edit the coordinate from the scene of the array. Wondering what someone knows what is the best way to do it? Or is it better to use the matrix or Cluster? Thanks in advance.

      Best regards

      Han Yen

      Han Yen wrote:

      Thanks much altenbach for all the advice. I tried to do a table 2D control. I've been playing with table in the control. However, I still can't find out how can I detect that I change the data in the table 2D with the more recent issue during execution? How can I then update my current table with the latest data?

      Well, the 2D table is updated immediately and you do not all the other tables.

      Do you mean that you want to update XAbs, etc. where the just changed line is already selected?

      In any case, here's a simple project, perhaps it will give you some ideas. I would recommend using also the tables for XYZPos, entrances etc. and the XYZabs. This simplifies the code because you reduce the number of terminals and table operations.

      Let me know if something is not clear to you.

    • Disable the extended FIFO FPGA target during execution

      Hello

      I use a FIFO extended target in my FPGA to constantly calculate the derivative of a measured value (dB/dt). Thus the FIFO stores all values during time dt. This means dt determines the number of items in the FIFO and dB is determined by the actual value less the oldest value in the FIFO. It works well when I initialize with the code in figure InitFIFO.

      But the FIFO of compensation is not possible (see figure clearFIFO). In the while loop if "reset dB" is false, as the new value of B is written on the FIFO, then the oldest value is read from, for the number of items in the FIFO remain constant. To change dt during execution, I need to clear the FIFO and initialize it with a new length (number of items). I tried the next loop, but it does not work. The FIFO does not initilized with the elements. The length is zero and the loop counter for (#deltaB Length2) is 0.

      What I am doing wrong? Is there a better way to erase a FIFO during execution in the FPGA? I'm now stuck for 2 days with this problem and looking forward to any idea or suggestion.

      Thank you very much. Best regards

      Andy

      Hej,

      Thank you for your response. You were correct, that deltab FIFO length was 0 because the defalt value was zero. The problem is that in my host vi on the RT system I put DeltaB FIFO length in a loop of high priority and as you can see when I restart the FPGA, DeltaB FIFO length has a valid value (the code in figure 1 works well with a local variable of DeltaB FIFO length in the FPGA). But the variable to set the variable "reset dB" is under the control of the loop of low priority of the host vi. And there, I had an entry DeltaB FIFO length unwired.

      So, I learned that a control FPGA read/write unwired sends a '0' or resets the variable to its default value in the FPGA. I assumed that nothing is transferred and the last variable is retained if you let a control read/write unwired. Now, I learned of this stupid error!

      Thanks a lot again!

      Andy

    • IMAQ, zoom to fit display control disappeared during execution.

      As in the title. The menu is impossible to call during execution of the control display Imaq. This has happened after the compilation of the code.

      Any idea why this happened?

      Francesco.

      I had this problem before.

      The solution is not very pretty, but it can be found here: http://forums.ni.com/t5/LabVIEW/Missing-quot-Zoom-to-fit-quot-in-application-EXE-build/td-p/905681

      Birgit

    • Enter the mathematical expression during execution

      Thanks to LabVIEW 7.0.  Is there a way to enter a mathematical expression during execution?  I am collection of bytes of a device in which the user may have to configure the runtime.  For example, if a package returns 2 bytes, i and j, the user wants to run an equation on the bytes as y = 200i - 3j.  The equation could be anything.  I looked at Expression nodes and formula, but it doesn't seem to be a way to get into the equation by program.  Anyone has any ideas on this subject?

      Thank you.

      I opened LV 7.1 which is the oldest I have.  In this version, the mathematics are in the palette to analyze it.

      In the functions palette click on search and type "parse" or "formula". These searches are formula several screw analysis

      If you have only the Base of LV version, you don't have these screws

      Lynn

    • modify VI during execution

      Dear users of LabView,

      I have a fairly general question about the development of a project, which requires a continuous control of the material. To be more precise, I develop LabView control and DAQ software for calorimeters in high volume in the last 2 years. Such a system requires several PID controls, and it has many subsystems. Because of the large heat capacity, it takes about 3-4 days to launch the system. So if I need to edit for example something in control of the final of a specific subsystem, I stop the LabView code, I have change the specific part, I restart the system, I wait for 3 days, and then I can see the result of my changes.

      My question is the sort of General: what is the good, let's say "best practice" to avoid such a dead time?

      Is it possible to change a VI during execution?

      I understand that if I run the independent screw, that dealing with subsystems, I could avoid this problem. But if I already have a compact 'main' VI, including all the subVIs, what can I do?

      It would be nice to have a sort of "hot swapping" feature in LabView, so during the execution of main VI of my project, I could change the Subvi that I want, and when it is ready to activate, the runtime would swap with the old version.

      Thanks for the tips and advice!

      Best wishes

      Hello

      It all depends on how works your vi...

      The only way I see is to use dynamic calls: a vi called dynamically is editable even if appellant vi is running.

      If you change the callee until the caller calls the vi vi.

      Is how the appellant under vi (this includes the values of connectors and run the VI):

      Best regards

    • How can I draw several plots by using the XY graph during execution?

      Hello

      I want to draw several plots in the graph XY to the means of execution user will select the number of plots that he wants to draw, depending on this value, I have to get these values and use table generation and then I give to graph XY.

      During execution, but how to do this?

      Please help me in this regard.

      Kind regards

      Herald

      Why start a new thread?

    • For a control that can be initilaized during execution

      In the case of an enumeration or a constatnt ring. The options to select should be listed when programming

      The option to select is possible during execution.

      I have a table, and I can send the 1st column of values in the menu drop-down, select one during execution.

      Help, please.

      Hi, Mike Grugh,.

      I don't know how to do it with a table drop-down list boxes, but if the number of lines in your file, then you can try the attached example.

      Kind regards

      Amine31

      (Give the congratulations to the right answers and Mark as a solution if your problem is resolved)

    • How to change the frequency of sampling DAQmx during execution?

      Hello guys. I'm using LabVIEW in the measures of the frequency response function. My application requires the sampling rate to change according to the frequency of the signal during execution.

      I tried to do it with a "structure of the event" and it works well when I change the rate manually via the front control but it backs do not work when I set up the sampling frequency to vary automatically (just a frequency sweep). Photos below:

      Why not the structure of the event feels the change in the value of "rate"?

      Thanks in advance for your help.

      Lucas

      Hello

      In "automatic mode" to change the sampling rate, the calculated rate is written in the local variable (as illustrated in the code).  Structure of the event does not change value in the local variable as an event.

      In order to make the structure of the event to recognize the change in value of an indicator such as event: write the new value to the property "Value (Sgnl)" corrosponding node to rate indicator (see figure below).  This will make the structure of the event accept the value change in the indicator as event.

      Note: Use architectures such as producers and consumers for such applications, which makes the application readable and expandable.

      See rear queries if any.

    • What would cause a constant changes during execution typedef enum

      Hello

      In my program I had a problem with a constant of enum for a selection of the tab value change during execution.  The enum is as part of the initialization of the program and when I step through the loop and then you see the property node of the climax to the value tab and in the next step of the enum changes its value.  I'm under LV 8.0

      Any information will be greatly appreciated.

      Gary


    • MCListbox property node does not during execution

      Hi I have problem with MCListbox property node. I wanted to fill the column with names and elements in the table.

      Initially, the program runs smoothly under development without error time.

      However when I she ran during execution of the table cannot be completed and produced by mistake. The error that says that "[get article] Config Registry.vi data: invalid object 0.

      I'm not sure what the error means that I need to find the bug in the moment of the execution because it works very well under development time. I found MCListbox property node errors after the names and elements are tempted to be filled in the table. I don't know why there are errors to the difference in time of development. See attachment below

      Thanks please advise

      Clement

      You read data from the configuration file? How do you get the path that it? You know that there is a difference (http://digital.ni.com/public.nsf/allkb/FD7DE8BC8FFC256C862565F4006BE363) between the path to the runtime and development environment? What LV version do you use? There are some recent changes. http://forums.NI.com/NI/board/message?board.ID=170&message.ID=473427&jump=true

    Maybe you are looking for

    • Thunderbolt target Display Mode does not (El Capitan)

      Hello I have two iMacs (iMac (21.5 - inch, mi 2011) and (iMac (27 - inch, mid 2011).)) I used sight to connect display mode target without problem with a MF639ZM (cable Apple black Thunderbolt, 2 M). I updated both the iMac OS X El Capitan, version 1

    • ASUS GeForce GTX 750TI install on Pavilion P6 2010UK leads to 3 beeps and black screen

      Hello I recently tried to install a 750TI Asus GeForce GTX on my HP Pavilion P6 2010UK using a SATA 6-pin PCI Express power connector, but after starting I get three beeps and a black screen. Can someone help me with this please? As an observation, t

    • Skype crashes

      I run on windows 10 technical overview. A week ago, nothing was wrong with the work of Skype, and I could talk to anyone I wanted. Now I can open Skype but as soon as I click on the client, it crashes. Help, please. Thank you.

    • No Stand in option

      Hello When I want to finish the job on my computer support option is not active. How can I make it active. concerning

    • Updated BIOS for HP probook 6460 b without Windows

      Hello. Product: hp probook 6460 b OS: Linux I am currently using BIOS version F01 (initial version). Do somebody know how how can I update the BIOS to the latest revision without windows. It seems that all BIOS HP softpacks works only on Windows. Tha