Swing layout + awt paintcomponent issue

Hi guys
I have a small issue while creating my very first application, or better, creating its GUI.
i would like to insert in a jpanel three JTextFields on top of the panel where the user could eventually enter data, once the data are entered, a paintComponent displays the results beneath it using graphics, with simple drawLine from the paintComponent method.
The problem is that i dont succeed to design a "good looking" panel where i can combine the organized layout of the fields and the space left for the lines of the paintcomponent method
i can enter the fields and the lines like this:
//contstructor definition
add(field10);
add(field2);
add(field3);
//eof constructor definition
public void paintComponent(Graphics g){
g.drawString("ciao"20,20);
}but i cannot do this...
//contructor definition
setLayout(new GridLayout(3,2));
add(field10);
add(field2);
add(field3);
//eof constructor definition
public void paintComponent(Graphics g){
g.drawString("ciao"20,20);
}because the GridLayout will occupy the whole panel and the size of the fields will be huge, so that there will be no space left for the paintComponents.
What i would like to do is to let the GridLayout to occupy only the upper part of the JPanel so that the part below could be left to graphic content.
I hope it sounds clear.
Thank you
Take care
Edited by: classboy on Sep 8, 2009 9:28 PM

One of the keys to understanding use of layout managers with Java is that they can be nested. More accurately, you can next Components and have each one use its own layout manager. One solution to your problem is to have a main JPanel use a BorderLayout, then add another JPanel, say called textFieldPanel that uses GridLayout and holds the three JTextFields. This panel can be added to the main panel BorderLayout.SOUTH or .NORTH, depending on your preference, and then have a third JPanel a drawingPanel that overrides paintComponent and displays the graphics, and add this to the main JPanel BorderLayout.CENTER.
The iterations possible here are close to endless.
Much luck.

Similar Messages

  • Unable to run jar file without lib folder containing swing-layout-1.0.jar

    I have done my project through NetBeans 5.0. Eventhough I have copied my lib foloder containing swing-layout-1.0.jar inside my project.jar, I am still unable to run my project.jar in other systems, it is creating an error as Could not find the main class. Program will exit. But if I copy the lib foloder containing swing-layout-1.0.jar in the same path as the project.jar, then my project.jar is running.
    But I want to give only the project.jar for other users and not also lib foloder containing swing-layout-1.0.jar each time.
    Could someone please help me with this.

    When you develop GUI applications using the Netbeans you may endup using netbeans specific jar files in your auto generated code.
    And when you build jar files with netbeans it copy the third party jar files used in a application in to a lib folder in the same directory as the jar file of your project. And then set a class path entry to those jar files in your project jar file's manifest file.
    So if you want to redistribute the package you have to redistribute your jar file and every thing in the lib folder in with the same directory structure.
    If you want to change the structure you will have to change the class path to suit the new structure.

  • Swing Layouts

    Why is laying out component sizes in Swing so incredibly opaque?
    Each time I build a swing interface it seems to be a series of visual compromises, and ending up in more TLOC than any other part of even a complex application. Changing one value seems to always mess up everything else or have unexpected side-effects! Half the time, changing the most obvious values have no effect at all. I frequently end up just clearing out ALL layout hints/settings from the UI and starting from scratch with a GridBagLayout just to get something fairly sensible. Yes I am frustrated.
    If any part of the increasingly wonderful java platform needs a major review, then it is the Swing layout APIs or at least the documentation of the exact behaviour and dependencies of methods that influence sizes.
    Either I am stupid (which I would be most willing to accept), or component layout/orientation/sizing/behaviour is very, very far from intuitive.
    I'd love to become a Swing-super-guru-expert, but as I am expected to be an expert on so many other things, I simply do not have the time to spend on it. I believe that it would be much better for the platform as a whole if the UI platform was made more intuitive or at the very least much better documented.
    I am seriously considering moving to SWT, as I just don't have the time or energy to figure all this out.
    /k1

    Oh btw - all the GUI editors I've ever used tend to compound the problems by introducing their own
    quirks, dependencies and restrictions! That's been my experience to date which is why I've steered clear of them.
    As far as swing architecture not being mature. I think the architecture gives you the building blocks, from there any layout mangers can be created. Maybe Sun could provide a few more LayoutManagers but I suspect their tactic is to provide the minimum from which you can do everything so keeping the API size down.
    So don't restrict yourself to those available in the JDK. Have a google and get some freebies. There are all sorts of alternative Layouts there. The fact that these are freely available elsewhere is quite likely why SUn haven't bothered to introduce more themselves some that spring to mind are TableLayout, GridLayout, ProportionalLayout, LabelledLayout
    To my mind it's the beauty of swing that allows it to be so easily extended in this way.
    SpringLayout came in in JDK1.4 http://www.onjava.com/pub/a/onjava/2002/09/11/layout.html but I'm not familiar with that as yet as I write systems that must be JDK1.3 compatible. It looks like a better replacement for GridBagLayout there are probably alternative versions of this to be found on the web..

  • Shall i use Swing or AWT for creating a chessboard applet??

    Hi,
    I need to build an applet which should dislpay a chessboard where i should
    be able to move the pieces around, read in a game analysis, etc...
    I am a beginner and i would like some advice on if i should use swing or awt?
    Which one is it easier to work with in terms of dispaying the pieces, moving the pieces and achieving other more challenging functionalities?
    Is it good idea to mix both of them? i.e have a japplet and use a canvas for displaying the board??
    Any advice would be much obliged.

    I used to think AWT
    And someone told me Swing was better..and that all of the Drag-n-Drop stuff doesn't work well with AWT.
    I have to admit that I used AWT up until a project about 3 months ago--I liked it better, but Swing does seem to have more builtins for handling the things you would need to for the Chess Board. Not that you CAN'T do them with AWT, but that they are harder to do with AWT.
    As far as reading in game analysis, etc..that really is independent of Swing/AWT

  • Need  java code to perform refresh button action using swings and awt

    i need java code to perform refresh button action using swings and awt.please help me

    Wait ! Noboby ? OK, I'll do it
    public void onBtnAction ()
        if (!fresh)
            refresh ();
    }Seriously, did you expect anyone to answer such a cryptic question ?

  • Swing layout error

    i have posted this in the jdbc forum but i have not recieved any responsed yet so im posting it here in the hope that one of you might
    have a solution.
    I searched this forum, and i was surprised to find that none had this problem. I ll get to the point.
    I am using netbeans, so i downloaded the mysql driver , added it to the project library and compiled and ran my program . I did not have any problems.
    so i triedt to run the app on a different machine and it gave me the
    popular swing layout error. I fixed that error. by adding some lines to the xml file mentioned in the netbeans faq.
    Now it gives me another popular error when i try to run the .jar file from command line on the same machine i developed the app
    the errror is
    System Exception Output : com.mysql.jdbc.Driver
    is there a way to avoid this error like the swing layout error
    thanks in advance

    So, nothing whatsoever to do with a Swing layout error, then :o)

  • Quick practical question: swing vs. awt

    Hi,
    I have an app/applet w/ a fairly simple calculator-type gui. But I want it to run well even on old Pentiums. How much will it matter if I use swing or awt, in terms of performance of the app, ie. user response to gui input? Is it really noticeable?
    Does the system resource usage differ as well even while there is no user input?
    TIA,
    Reggie

    In my experience swing often performs better than awt does, as far as memory and speed...
    Swing can't run in IE without a plugin tho, so consider that before you start switching

  • Swing layout books ?

    Hi,
    We are a small group of developers and have written quite a lot of Java apps and GUIs, but seems to struggle sometimes getting good layouts on forms etc that we are designing. We obviously know about the different layout managers but i'm not sure we're using them fully or really know them inside out. What we're looking for is more information about how to get the best layouts, tips and tricks, or a complete treatise on the layout managers.
    Can anyone recommend a good book on using Swing layout managers, and/or general GUI design principles ? The Sun tutorial is a pretty good start, but is there anything else ?
    Many thanks
    Alistair

    hi,
    Professional Java Programming in this link,(but not free download)
    http://www.amazon.com/Professional-Java-Programming-Brett-Spell/dp/186100382X

  • Swing vs AWT (which should I learn?)

    I am writting an mp3 player in Java. I am fairly new to Java as all I know is the programming language; I do not know how to make a GUI. I want to make a cross platform mp3 player that should run on mac, windows and Linux. I also want to use some custom buttons made in Photoshop.
    Should I invest time in learning Swing or AWT?
    Thank you for your help.

    Hello,
    this depends on how far You intend to go with "customizing". Swing leaves a few things to the Operating System e.g. Windows or Linux. My swing apps look different under Linux than they do under Windows, because the Frame in which these apps are are drawn is administered by the OP System. On the other hand if customizing means for example changing the java cup icon upper left or changing the Title of the frame, then You will have no problems. More generally spoken: nearly everything can be done as long as You stay with the possibilities You have (Buttons, TextField, Bars ... have a look at the Swing Platfrom !).

  • Swing layout/size problem with JFrame and JApplet.

    I have a class that extends a JFrame, the classes layout is BorderLayout. I then have a class that extend JApplet, this classes layout is GridBagLayout (this class has a JTabbedPane - which contains JPanels). The problem I'm having is no matter how big I make the size of the applet or frame (using setSize), the applet/frame stays the same size - no matter how large I make it.
    Can anyone please help?
    Thanks,
    dosteov

    Here is the basic code:
    Thanks in advance,
    dosteov
    public class EADAdm extends JApplet
    EADAdmFrame theFrame = new EADAdmFrame(this);
         public void init()
              // Take out this line if you don't use symantec.itools.net.RelativeURL or symantec.itools.awt.util.StatusScroller
    //          symantec.itools.lang.Context.setApplet(this);
              // This line prevents the "Swing: checked access to system event queue" message seen in some browsers.
              getRootPane().putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
              // This code is automatically generated by Visual Cafe when you add
              // components to the visual environment. It instantiates and initializes
              // the components. To modify the code, only use code syntax that matches
              // what Visual Cafe can generate, or Visual Cafe may be unable to back
              // parse your Java file into its visual environment.
              //{{INIT_CONTROLS
              getContentPane().setLayout(new GridBagLayout());
              setEnabled(false);
              getContentPane().setBackground(java.awt.Color.lightGray);
              setSize(800,800);
              getContentPane().add(AdmTab, new com.symantec.itools.awt.GridBagConstraintsD(0,1,2,1,0.5,0.5,java.awt.GridBagConstraints.CENTER,java.awt.GridBagConstraints.HORIZONTAL,new Insets(3,12,4,14),120,120));
              AdmTab.setFont(new Font("Dialog", Font.PLAIN, 12));
              titleLbl.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
              titleLbl.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
              titleLbl.setText("EAD Administration");
              getContentPane().add(titleLbl, new com.symantec.itools.awt.GridBagConstraintsD(0,0,1,1,0.0,0.0,java.awt.GridBagConstraints.CENTER,java.awt.GridBagConstraints.NONE,new Insets(12,36,0,0),307,15));
              titleLbl.setForeground(java.awt.Color.blue);
              titleLbl.setFont(new Font("Dialog", Font.BOLD, 15));
              exitBtn.setText("Exit EAD Administration");
              exitBtn.setActionCommand("Exit EAD Administration");
              getContentPane().add(exitBtn, new com.symantec.itools.awt.GridBagConstraintsD(0,2,2,1,0.0,0.0,java.awt.GridBagConstraints.CENTER,java.awt.GridBagConstraints.NONE,new Insets(6,371,10,14),66,8));
              exitBtn.setFont(new Font("Dialog", Font.PLAIN, 12));
         //theFrame.setVisible(false);
         login();
         AdmTab.addTab("Administration", new LogoPanel() );
         userPanel = createUserPanel();
         AdmTab.addTab("Edit Users", userPanel );
         fpoPanel = createFPOPanel();
         AdmTab.addTab("Edit FPO", fpoPanel );
         regulationPanel = createRegulationPanel();
         AdmTab.addTab("Edit Regulations", regulationPanel );
         rolloverPanel = createRolloverPanel();
         AdmTab.addTab("Rollover", rolloverPanel );           
              //{{REGISTER_LISTENERS
         SymMouse aSymMouse = new SymMouse();
              this.addMouseListener(aSymMouse);
              SymAction lSymAction = new SymAction();
              exitBtn.addActionListener(lSymAction);
              SymKey aSymKey = new SymKey();
              this.addKeyListener(aSymKey);
         theFrame.getContentPane().add(this);
    public class EADAdmFrame extends JFrame
    EADAdm theApplet;
    public EADAdmFrame(EADAdm theMainApplet)
              //{{INIT_CONTROLS
         //     theApplet = theMainApplet;
         //     this.getContentPane().add(theApplet);
              getContentPane().setLayout(new BorderLayout(0,0));
              getContentPane().setBackground(java.awt.Color.lightGray);
              setSize(1000,1000);
              setVisible(false);
         theApplet = theMainApplet;
              //{{REGISTER_LISTENERS
              SymWindow aSymWindow = new SymWindow();
              this.addWindowListener(aSymWindow);
              SymComponent aSymComponent = new SymComponent();
              this.addComponentListener(aSymComponent);

  • Dealing with Swing Layouts

    I have a collection of small panels with fixed size (around 50x50), and a main panel with size around 600x480.
    At run time I need to show this collection of panels on my main panel.
    Based on your experience, what would be the best layout to show them on my main panel?
    I have tried setting up a GridLayout on my main panel, but my small panels always got resized to fill my main panel, no matter how I tried to stablish the number of rows (length % rows == 0? 0 : 1 + len depending on my collection size.
    Also tried with a flowlayout, but when I added a JSCrollPanel, instead of adding new rows, my scrollpanel kept adding them on the same line :( I even enforced my scroller to
    Is this the correct behaviour? Am I doing something wrong? (I'm sure I do :))
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.GridLayout;
    import java.util.List;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import static javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER;
    public class JClass extends JFrame{
        private JPanel panel;
        private JScrollPane scroll;
        protected JClass() {
            panel = new JPanel();
            scroll = new JScrollPane(panel);
            scroll.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_NEVER);
            JPanel menu  = new JPanel();
            JButton but  = new JButton("show");
            but.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                   display(5);
            BorderLayout layout = new BorderLayout();
            FlowLayout layout2 = new FlowLayout();
            layout2.setAlignment(FlowLayout.LEFT);
            panel.setLayout(layout2);
            menu.add(but);
            this.setPreferredSize(new Dimension(640,480));
            this.setLayout(layout);
            this.add(scroll, BorderLayout.CENTER);
            this.add(menu,BorderLayout.WEST);
            pack();       
        public void display(int n){
            JButton button;      
            for(int i = 0; i < n; i++){
                button = new JButton();
                button.setPreferredSize(new Dimension(30,30));
                this.panel.add(button);
            this.validate();
            this.repaint();     
        public static void main(String args[]) {
            JClass app = new JClass();
            app.setDefaultCloseOperation(EXIT_ON_CLOSE);
            app.setVisible(true);
    }

    Thanks Camickr.
    And just for the sake of it, do you think is there a way to do it with GridLayout? I mean, fixing the number of columns to three, but without resizing the small panels I will be adding. Maybe by fixing the preferredSize of the panel with the gridlayout to the small panels width * 3 + something?
    In my previous iteration I tried it but this content panel would always take my maximum space, thus expanding my small panels... :(

  • Swing layout

    in AWT, the layout was control by the GridBag Layout and constraints, how can i control the layout of the button in swing to the layout that i want it to be?

    hi,
    everyone has this problem at first :) ...
    you need to set your Layout to null rather than GridBag or whatever...
    then on each component (button,label etc) you can call the .setBounds() method.
    this takes 4 ints i think...x,y,width,height so you can positition the things wherever you want then
    alexs

  • Is it possible to use events for objects that do not use swing or awt

    Dear Experts
    I want to know if events are possible with plain java objects. A simple class that is capable of firing an event and another simple class that can receive that event. My question is
    1. If it is possible - then what is the approach that needs to be taken and would appreciate an example.
    2. Is Observer Pattern in java going to help?
    To explain further i am doing [Add,Modify,Delete,Traverse] Data tutorial using swing in Net beans. I have a ButtonState Manager class that enables and disables buttons according to a given situation. For example if add is clicked the modify button becomes Save and another becomes Cancel. The other buttons are disabled. What i want is the ButtonStateManager class to do a little further - i.e. if Save is clicked it should report to DBClass that it has to save the current record which was just added. I am foxed how this can be done or what is the right way. Thanks for reading a long message. Appreciate your help.
    Best regards

    Thanks Kayaman
    i guess i am doing something else maybe it is crazy but i need to work further i guess... i cant post the entire code as it is too big but some snippets
    public class DatabaseApplication extends javax.swing.JFrame {
        ButtonStateManager bsm;
        /** Creates new form DatabaseApplication */
        public DatabaseApplication() {
            initComponents();
            // ButtonStateManager has a HUGE constructor that takes all the buttons as argument!
            bsm = new ButtonStateManager(
                    btnAdd,
                    btnModify,
                    btnDelete,
                    btnQuit,
                    btnMoveNext,
                    btnMovePrevious,
                    btnMoveLast,
                    btnMoveFirst );One of the methods in the ButtonStateManager Class is as follows
      private void modifyButtonState()
            btnAdd.setText("Save");
            btnModify.setEnabled(false);
            btnDelete.setText("Cancel");
            btnQuit.setEnabled(false);
            ...Finally the Crazy way i was trying to do ... using EXCEPTIONS!
      void modifyClicked() throws DBAction
            if(btnModify.getText().equalsIgnoreCase("MODIFY"))
                modifyButtonState();
            else
                throw new DBAction("SaveAddedRecord");
        }And Finally how i was Tackling exceptions....
      private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {                                      
          try {
                bsm.addClicked();
            } catch (Exception e1) {
                processDBAction(e1.getMessage());
        private void processDBAction(String msg)
            if(msg.equalsIgnoreCase("SAVEMODIFIEDRECORD"))
                System.err.println(msg);
                bsm.normalButtonState();
            }Edited by: standman on Mar 30, 2011 4:51 PM

  • Running the Swing or AWT code in the UNIX

    I have developed the code to modify the XML attribute values using Java. Those attribute values are accepted from the GUI which i have designed using swings as well as AWT.
    The code is perfectly working in the DOS/Windows environment. The applet/Display is perfectly popping up and accepting the data and it is making the required changes in the XML and creating the new XML.
    But the problem i am facing is,
    I compiled the same code in UNIX and then run the code. But it threw the exception as below. Can anyone help me out for this. What i need to do in order to run that code successfully??.
    bash-3.00$ java GUIAjay
    No X11 DISPLAY variable was set, but this program performed an operation which requires it.
    at java.awt.GraphicsEnvironment.checkHeadless(GraphicsEnvironment.java:159)
    at java.awt.Window.<init>(Window.java:407)
    at java.awt.Frame.<init>(Frame.java:402)
    at javax.swing.JFrame.<init>(JFrame.java:207)
    at GUIAjay.<init>(GUIAjay.java:44)
    at GUIAjay.main(GUIAjay.java:39)
    I tried to set the X11 window server as:
    export DISPLAY=10.5.21.117:0
    But yet the User Interface is not popping up in the UNIX??.
    May be the problem is because GUI is not supported in UNIX.. So please suggest me on this..

    *Don't post general Java questions here*

  • Using Java swing layout

    I'm rather new at this and i'm having trouble creating my desired layout, actually i'm having trouble picking my desired layout.
    this is how i'd want my program to look...
    name place time address
    mary Hos. 12:00 70 sine st. JButton
    Kay Sch. 1:00 13 cos st. JButton
    JButton("OK")
    Hopefully you have some idea of where i'm heading. I don't want a table because i want this to be uneditable so i'm doing with with panels. the spots marked "JButton" are of course Buttons (their functions are not important). at the bottom is a single "OK" Jbutton that is aligned with the other JButtons above it.
    my issues are as follows,
    I have just 4 title labels (name, place, time, address) but there are essentially 5 components that make up the body of the list (all the others + a JButton). can anyone tell me what Layout i should use?? i've tried GridBag but i'm having trouble with the JButtons. And How in the world can i place the final OK button?

    I suppose those things were supposed to be arranged in columns? Then you want a JTable. And if you want it to be uneditable, then just make it uneditable. There's no need for enormous workarounds.

Maybe you are looking for