A litle question in Swing.

Hello
I have a litle question in Swing.
when i add a component to a frame where on the frame it adds the component?
for example ,
I have a frame and it has a content pane. and i do like that
myPanel.add(myButton);
or
myPanel.add(myTextField);
to where it will add it?
to the bottom of the frame? to the top? to the middle?
Thanks in Advance!

to where it will add it?It's simply added to the collection of component objects within the container. How it gets displayed is dependent on the LayoutManager.
http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html
P.S. Swing questions belong in the Swing forum.
~

Similar Messages

  • I need help, I have alot of questions too (swing, code, optimizing...)

    Hi, I'm having a little trouble with aligning my GUI correctly. Here are screenshots from my laptop which runs OS 10.4 & my PC running Windows 2000:
    http://kavon89.googlepages.com/clipper.png <= On the laptop
    http://kavon89.googlepages.com/clipper_windows2000.jpg <= On the PC
    I don't know why the OS 10.4 looks almost perfect and the win 2k is a disaster. I played with it on my laptop and once i came over to my PC to post a problem about somthing else, i noticed this issue on my windows box. My guess is that either the JButton on OS 10.4 is smaller than the one for win2k and causing the automatic organizing to malfunction... or maybe the pixels are larger on my PC then on my laptop.
    I was thinking that I should make diffrent .jar's for each OS since there are GUI issues.... or is there a way to make it universal? (i read somwhere about GridBag?)
    Next off, Is there any way to reduce the size of the space between the JList box closest to the top of the frame & the buttons & text box below it? I tried all sorts of resizing and it seems stuck on some sort of space there which i would like to make compact.
    Those are all the swing questions i have ^
    About my code:
    I recently added 2 buttons which are at the bottom of the OS 10.4 screenshot, Clear Box & Drop All. Clear Box is the one I made work, or so I thuoght. I wrote this for my Clear Box button (by the way, the button is sapose to just clear the text box directly to the upper left of itself.)
           if(e.getSource() == buttonc)
               textfield.setText("");
           }I thought that was the best way to go about clearing the text box. just setting it to blank. But after some testing to ensure there were no reprocussions, I found a problem... When i select somthing from my JList and hit Clear Box, it deletes the entry in the JList when it is not sapose to. It also does it when there is text in the textbox and i have selected somthing in my JList. I haven't been able to figure out why. Here is my full source code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class winclipstart
      JButton buttona, buttond, buttonc, buttonda;
      DefaultListModel clippedtxt = new DefaultListModel();
      JTextArea textfield;
      JList ClippedLines;
      public static void main(String[] cheese){new winclipstart().buildGUI();}
      public void buildGUI()
        JFrame frame;
        Container contentPane;
        JPanel Bottom = new JPanel();
        JPanel Top = new JPanel();
        frame = new JFrame();
        frame.setTitle("Clipper 0.1 Beta");
        contentPane = frame.getContentPane();
        ClippedLines = new JList(clippedtxt);
        JScrollPane scroll2 = new JScrollPane(ClippedLines, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scroll2.setPreferredSize(new Dimension(400,150));
        textfield = new JTextArea(3,20);
        JScrollPane scroll1 = new JScrollPane(textfield, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        buttona = new JButton("Clip");
        buttond = new JButton("Drop");
        buttonc = new JButton("Clear Box");
        buttonda = new JButton("Drop All");
        Bottom.add(scroll1);
        Bottom.add(buttona);
        Bottom.add(buttond);
        Bottom.add(buttonc);
        Bottom.add(buttonda);
        Top.add(scroll2);
        Box All = Box.createVerticalBox();
            All.add(Top);
            All.add(Box.createVerticalStrut(5));
            All.add(Bottom);
        contentPane.add(All);
        buttonL cl = new buttonL();
        buttona.addActionListener(cl);
        buttond.addActionListener(cl);
        buttonc.addActionListener(cl);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        frame.setSize(424,314);
        ClippedLines.setDragEnabled(true);
      public class buttonL implements ActionListener
        public void actionPerformed(ActionEvent e)
           if(e.getSource() == buttona)
              String elementToAdd = textfield.getText();
              if(elementToAdd.equals("")==false) clippedtxt.addElement(textfield.getText());
           else
             int index = ClippedLines.getSelectedIndex();
             if(index > -1) clippedtxt.remove(index);
           if(e.getSource() == buttonc)
               textfield.setText("");
    }There is a stray dragenabled true line in there which on my ibook showed that it drags after holding the mouse button down a little longer than expected, and it shows im dragging , but obiously not dropping because i haven't configured dropping yet. but on my windows machine it shows nothing of it. oh and, on the ibook it shows it with a green "+" and then makes it look like im trying to put it inbetween two other lines but does nothing when dropped like expected
    Another question: In the beginning of my code i have it loading the entire library with the *, and i noticed after turning it into a .jar that it loads slower than i expected... would a way to speed it up be to specify exactly what i need loaded after the program is finished or would it make no diffrence?
    :-/ seems my program isn't as cross platform as i exptected java to be

    I solved the code problem myself after a careful run through of the code, the "else" in my subclass made it so that every button other than the Add button deleted a selected entry, i quickly fixed it and made it an if statement.
    Thank you for the link cotton.m
    My question bout optimizing still remains though:In the beginning of my code i have it loading the entire library with the *, and i noticed after turning it into a .jar that it loads slower than i expected... would a way to speed it up be to specify exactly what i need loaded after the program is finished or would it make no diffrence?

  • Some questions on swing

    import java.awt.*;
    import javax.swing.*;
    public class test {
         static final int n_label = 10;
         public static void main( String args[] )
              JLabel[] lab1;
              JWindow w = new JWindow();
              Container content_pane = w.getContentPane();
              w.setVisible( true );
              content_pane.setLayout( new BorderLayout( ) );
              lab1 = new JLabel[n_label];
              for(int k=0;k<n_label;k++) {
                   lab1[k] = new JLabel("Label " + k);
                   content_pane.add( lab1[k] );
              w.pack();
              w.show();
         //     System.exit(0);
    }i am testing this code from book.
    i am not getting a visible window...i am not sure whether window is creating or not. Is this code alright?
    can u suggest some modification so that things are visible.
    however, some question regarding this code.
    you see,
    w.setVisible( true ); and w.show(); i think both of them are same . Are not these two method doing the same job? Both of them are showing the window. I think one of them, we can drop. is not it?
    w.pack(); >> what pack() method does ? i found it is minimising something. what is that ?
    System.exit(0); >> is it really needed at all !!
    thanks

    thanks, i got some achievement. its suprising to me that only " label 9 " is coming ... where other labels has gone !! they are not on the window !!
    here is mine modified code
    import java.awt.*;
    import javax.swing.*;
    public class test {
         static final int n_label = 10;
         public static void main( String args[] )
              JLabel[] lab1;
              JWindow w = new JWindow();
         //     w.setSize(600,400);
              Container content_pane = w.getContentPane();
         //     w.setVisible( true );
              content_pane.setBackground(Color.red);
              content_pane.setLayout( new BorderLayout( ) );
              lab1 = new JLabel[n_label];
              for(int k=0;k<n_label;k++) {
                   lab1[k] = new JLabel("Label " + k);
              //     System.out.println(lab1[k]);
                   content_pane.add( lab1[k] );
              //w.pack();
              w.setBounds(100,100 ,600, 400) ;
              w.show();
              //System.exit(0);
    }Failing that you might want to toss some System.println() statements through your code to make sure that you're getting the objects created.
    i tried to print the objects....but some problem probably..its not coming properly.

  • Question about SWING and ActionEvent Object.

    When using a graphical component like a JButton,
    one typically adds an ActionListener Object to that button using the
    addActionListener method,
    in order for a click/appropriate action to execute desired Java code.
    One's desired code is within one's own ActionListener Object,
    which implements an appropriate interface and the equivalent of
    that interface's actionPerformed method.
    -How does one program one's own ActionEvent Object,
    and register that object (myActionEvent) with the java virtual machine
    such that your OWN event object is fired, instead of the
    default action?
    -Does instantiating one's appropriate ActionEvent object
    "fire" it as an event?

    Zac1234 wrote:
    When using a graphical component like a JButton,
    one typically adds an ActionListener Object to that button using the
    addActionListener method,
    in order for a click/appropriate action to execute desired Java code.Only for components that accept ActionListeners of course. This won't work with a JLabel for instance or any random "graphical component".
    -How does one program one's own ActionEvent Object,
    and register that object (myActionEvent) with the java virtual machine
    such that your OWN event object is fired, instead of the
    default action?Please explain exactly what you're trying to do here. Perhaps it's just me, but I'm not sure I understand what you mean by programming your own ActionEvent Object. An ActionEvent object can be simply created like any other object and by using the appropriate constructor (the API can help), but I don't think that you're talking here about ActionEven objects -- the parameter of the actionPerformed method, are you? Please give details as they are important here.
    -Does instantiating one's appropriate ActionEvent object
    "fire" it as an event?No, but again I'm stumped as to exactly what you're trying to do here.
    Finally, let's keep this discussion here, but next time, you will probably want to ask your Swing questions in the Swing forum.
    Best of luck.

  • Question on Swing, MVC and Events (Best Practices)

    Hi,
    I'm making a Swing application trying to follow the MVC pattern. To that end, I have an ApplicationView class and an ApplicationController class (as well as a DataModel). Obviously, I want to have the view as loosely coupled to the controller as possible so I can swap out the GUI later on if I want to. To that end, my controller is creating an instance of this view and passing it via its constructor a sub-class of ActionListener I created. This sub-class is an inner class of the model and basically handles all the button clicks and menu selections from the view and responds accordingly. My question is, is this the best approach or can someone reccomend a better way? Thanks in advance.

    Basically I have the same question, and I have frenetically been looking for a good answer to this... I've found that a common practice is to use actionlisteners (actually, all kinds of listeners) as nested classes in the GUI-code, also use a separate actionlistener for each event, e.g. having one actionlistener to handle events fired from one specific button, another actionlistener for another button etc.
    But this inevitally means that you get the GUI-code (more or less) interwoven with the source-code of your application. The positive effects of this is of course easy access to variables and graphical components in the rest of the code. But the downside is a potentially hard code to read and debug, also you make it difficult to separate the GUI-code from the source-code, if you for instance wanted to use the same GUI in another application.
    Take a look at the following code example (ListDemo.java) that uses several nested listener classes:
    http://java.sun.com/docs/books/tutorial/uiswing/components/list.html
    to download the app:
    http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/ListDemo.java
    Well this isn't perhaps much of an answer, it may however shed some light on matter.
    I would very much like to elaborate on this subject, so if anyone knows or has any practical examples of how to best use listeners and Swing-applications please feel free to reply this message or e-mail me personally at [email protected]
    All contributions are truly welcommed!
    Thanks
    /Mikael

  • Some general questions about swing

    Hi,
    I used to do some swing development couple years back but since then I have been more involved in the j2ee scene. I have lost some touch and was wondering if some of my questions can be answered. I'd appreciate every effort.
    First of all, I am trying to make an applet that can be used to upload multiple pics at the same time. Similar idea to facebook picture upload applet. My Q's are
    -> can every swing application be turned into an applet? or when the developer starts writing an application he should write it from an applet POV
    -> I noticed that the applet on facebook looks a lot like a window application. icons and the look and feel of the application is not that of a applets i saw couple years ago with sun java look and feel, how can this be achieved? is there some small example?
    -> can someone suggest an example || tutorial of an applet that shows how to upload an image to the server?
    and lastly for mental satisfaction :)
    -> how hard do you think it is to build such an application. I assume it will just have a JTree on the left side and on right side it will show contents of the folder that is currently clicked.
    Thanks for your time

    thanks for the tutorial link.
    However, the tutorial explains how to show icons from images. But what about in my case when the images arent even on the server yet.
    Basically when the user is browsing files and gets to their my pics folder on the right side i want to show icons of images in that folder. for this reason i doubt I will be able to use what they've implemented in that tutorial. As the pics havnt yet been uploaded by the user i have no direct access to the images.

  • Question to Swing Pros: Resizing of JFrame only with visible Rectangular  ?

    Hello folks,
    quite below is the quoted text message is from Java Substance Forum: http://www.nabble.com/Removing-top-left-substance-menu-and-deactivating-Background-painting-while-Resizing-a-Frame--to17775101.html
    Is it somehow possible to use substance or another LooknFeel with custom titelbar and still keeping a hidden JFrame background resizing? So if i resize a JFrame only a rectangular should be visible not the content of the window should dynamically resize.
    That would be a general Swing question to ask in Swing forums on java.net or on java.sun.com
    Thanks
    Kirill
    ----- Original Message ----
    From: PEL <liquidc4d@...>
    To: users@...
    Sent: Wednesday, June 11, 2008 9:07:36 AM
    Subject: Re: Removing top left substance menu and deactivating Background painting while Resizing a Frame?
    2. You would notice in your screenshots that you're running Substance
    under decorated mode, but Metal (and Windows) under undecorated mode
    (title pane coming from OS). Try running your app under decorated mode in
    Metal and see if the dynamic resizing is the same.
    Ok with decorated(false) the resizing of the frame shows only a border not
    the whole background of the frame, but then i have no stunning
    Glas3DDecoration painter :D
    Is it somehow possible to use substance with 3dglass titelbar and a hidden
    jframe background resizing?

    I've never seen a way to do that in Swing normally.
    Of course, if you could run something allowing transparent windows (some newer version of Java will support it, or Skin L&F, etc), I can imagine how you might fake it by using your own decorations, and on resize, create a transparent window with a border that is your resize window, and use that to resize, and then fix the final size to the real window when done.

  • PDA is under the environment of Jeode, carry out applet question with swing

    Purpose : Under the environment of Jeode in PDA, links APPLET webpage on websites, and APPLET is " import javax.swing. *".
    Question: Not knowing the problem of how to go to solve swing bug of applet , it is unable to read webpages to cause pda.

    Right. Make "number" a field, and take it out of the
    method signature for paint.
    Because you didn't use the same signature, you didn't
    override the existing paint(Graphics) method, you
    just overloaded it. That means that when the GUI
    thread tries to make your applet paint itself, it
    calls the original paint(Graphics) method, and not
    your paint(Graphics, int) method -- and so your
    method never gets called.
    Hi Paul,
    Not to sure whether is this what you mean by above statement, i just understand the statement in bold, anyway i ammend the program , this time i declare another variable outside the init() and paint() call int num
    import java.awt.*;
    import javax.swing.*;
    public class Draw extends JApplet
        int num;
        public void init()
        \\ask user for input (1, 2 or 3) = String numberStr
        num = Integer.parseInt(numberStr)
        public void paint(Graphics page)
            for (int index = 0; index < 100; index++)
            switch (num)
            \\ my statement code
    }Anyway it works, thanks..:)
    my last assigment before my exam.

  • Question on Swing?

    Hi,
    how Swing components are rendered in screen?
    Thanks in advance.

    Thanks for the reply.
    You had answered for my question i think, but i can't able to find the things you had mentioned in the post; in the link you had provided.
    The answer to the question as it is now involves a complex explanation of hardware abstraction layers, backbuffers, pixel formats, rendering pipelines, vertical retrace and monitor refresh rates, etc. etc.My Question is i had designed the login page using swing, it contains two labels two text field and one button. Now this entire page contains the all components. how the page will render in the screen?
    Thanks for the help.

  • Quick question on swing JButton (java programming)

    hi,
    Before you read, i am still a student! so if this question seems silly i am sorry, but i havent been able to find an answer!.
    I am using the following type of code:
    JButton SlowDownB = new JButton(new ImageIcon("Images/slow.jpg"));
    But the problem i have is that i am adding images of various sizes to different buttons, and i want all the buttons to be the same size (in a row). So i set the button sizes as follows:
    SlowDownB = new JButton(new ImageIcon("Images/slow.jpg"));
    SlowDownB.setPreferredSize(new Dimension(60,60));
    SlowDownB.setMaximumSize(new Dimension(60,60));
    SlowDownB.setMinimumSize(new Dimension(60,60));
    But now the problem is that it does not show the whole image :-(, is there a way to make the image/icon resize into the button?
    Thanks in advance to any replies,
    Regards,
    Daniel

    Maybe something like:
    List buttons = new ArrayList();
    // add the buttons to the List.
    Rectangle bigRect = new Rectangle();
    Rectangle r = new Rectangle();
    Dimension d = new Dimension();
    for (Iterator i = buttons.iterator(); i.hasNext();) {
      JComponent comp = (JComponent)i.next();
      r.setSize(comp.getSize(d));
      bigRect.add(r);
    d.width  = bigRect.width;
    d.height = bigRect.height;
    for (Iterator i = buttons.iterator(); i.hasNext();) {
      JComponent comp = (JComponent)i.next();
      comp.setSize(d);
    }

  • Question on swings help me

    Hi to all i am new to swings concept my problem is
    I taken 8 subjects with 100 marks and 5 labs with 75 marks in my application.
    Know my problem is when i am calculating subjects and labs i am not getting average .
    And but when i am calculate total divided by 13 i am getting average.
    For example : 8 subjects total is 560.
    5 labs total is 250.
    average = total/13
    i am getting average.
    But i want average like this i.e average = total /1175;
    i am taken total = subjects + labs;
    help me regarding this topic
    Thanks in advance

    Hello
    u r did "average = total/13; " this avg is not correct one .....
    bcos 8 subj is respect to 100 and remaining is respect to 75 .
    avg = (getting total marks / totalmarks)*100
    this is the correct way to calculate avg
    i am taken total = subjects + labs;
    all the best
    regards
    Amir

  • Ant questions: for Swing apps?

    I have used Ant for my J2EE programs by deploying the ear file to the server. For my swing desktop apps I have used an executable Jar file, or JBuilder makes me a windows .exe file.
    Can you use ant builds to make something appropriate for deploying Swing apps?
    Thanks!
    Amber

    Does this link help ?
    http://ant.apache.org/manual/CoreTasks/jar.html

  • Questions RMI & Swing & SwingWorker

    Suppose I have two headless servers (A&B) and one Swing client C (maybe a Swing Table that logs data from A & B). I've addLogEventListener(C) to both A & B. If A or B fires, do I need to worry about thing on the C side? I know that I must use SwingWorker for multithreading and don't think
    class C

    Actually, the restriction on non-GUI threads updating a GUI is very common - showing up for example in C++ GUIs/frameworks.
    If you have the potential for callbacks from more than one independent source, then you probably want some kind of synchronizing code so that they both don't attempt to update the GUIs model at the same time. Frankly I can't remember if the java GUI interface - that delas with threads - also handles THAT; I suspect not.
    If not, one thing you could try is to mke the callback method - or perhaps an inner method - synchronize on the CLASS that contains the callback. That implies that that object is not really part of the GUI, or you could really freeze things.

  • Question about Swing

    Why do we instantiate Swing components inside a class' constructor rather than in the main method?

    JavaNewbie12 wrote:
    Why do we instantiate Swing components inside a class' constructor rather than in the main method?Because it's a good idea.
    This has little to do with Swing really but relates to all Java programming. You should strive to do as little in your main method as possible. It's simply a hook to allow your program to be started.

  • !!!!!!!!!!!!!!!  Very Simple Question  about swings!!!!!!!!!!!!!!!!!!!!!!!!

    I have added two JRadioButtons to a ButtonGroup.i want to know which JRadioButton has been selected .i could not find any method which gives the state of the JRadioButton.pls advise.
    thanks

    And also:
    boolean isSelected = jRadioButton.isSelected()returns whether a specific JRadioButton was the one currently selected

Maybe you are looking for

  • CTIOS Login - IPCC Error [10156]

    Hi, Customer recently upgraded to ICM/CTIOS 7.5.9. Since then some agents are intermittently seeing the following error message when logging on. " IPCC Error [10156]Login denied because agent exceeded unsuccessful login attempts. " I haven't seen thi

  • How to create a 'window' in AE CS3

    Hello,      I have a video of a LED scroll sign and I am making it look like my own text scrolls across. I have text I created in Photoshop, saved as a ' .tiff ' , and imported into After Effects. I have put the text in the video and gave it a starti

  • How can apply configure file in ssis by using script task ?

    I had  two config file in ssis  1. config file as per QA 2. config file as per Production  I think apply dynamically by using script task for above file (acc to server) How can I apply in script task for config file path in C# script any one provide

  • Re: Tracking every return is over the top . . .

    i just experienced this exact situation. As the original post states Best Buy tracks every single return. This is is a ridiculous policy. I personally tried to return a Disney Infinity toy that i paid only $13.99 for. I had the orignal reciept and ev

  • Sales Order Line item category not getting Re detemining Correctly

    Dear all,             I need  help regarding the Sales order item category redetermination.             we are having two item categories YNAE and YNAG and it contains schedule  line categories CP and CB ( i.e for item         category  YNAE schedule