JFrame doubt?

Hi,
I need some help regarding JFrame. Actually i want to add the component in particular position in the GridLayout. I need to add a label in the label at
my code like this,
myLabel[0] = new JLabel(new ImageIcon(myUrl), SwingConstants.CENTER);
---- // array of labels here
JFrame f = new JFrame();
--- // frame code and GridLayout code
f.getContentPane().add(myLabel[0]);
myLabel[0].revalidate();My problem is somewhere i 'm revalidating. I want to put labels in specified locations like NORTH or SOUTH. but By revalidating it goes in to default mode. can you give any suggestions please..
Thanks
- balaji

The last 3 or 4 times I've seen you post a question you have posted it in at least two forums.
If you have a Swing question post it in the Swing forum.
If you have a general question post it in the Java Programming forum.
Don't cross post. I for one get frustrated when I answer a question in one forum only to find it has been answered by someone else in another forum. My time can be better spent answering questions that nobody has answered.
With regards to this question I suggest you read the Swing tutorial on "Using Layout Managers":
http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html

Similar Messages

  • Simple JFrame Doubt

    Why is the jextfield on the jframe so small.
    Also How do I update the textField of MyButton JFrame from JButtonActionListener?
    import java.awt.FlowLayout;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    public class MYButton extends JFrame {
         JButton jbnButton1;
         JTextField jtfClick;
         MYButton() {
              jbnButton1 = new JButton("Click Me");
              jbnButton1.addActionListener(new JButtonActionListener(MYButton.this));
              jtfClick = new JTextField();
              setLayout(new FlowLayout());
              getContentPane().add(jbnButton1);
              getContentPane().add(jtfClick);
              setSize(400, 400);
              pack();
              setTitle("Example JFrame");
              setVisible(true);
         public static void main(String args[]) {
              new MYButton();
         public JTextField getJtfClick() {
              return jtfClick;
         public void setJtfClick(JTextField jtfClick) {
              this.jtfClick = jtfClick;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    public class JButtonActionListener implements ActionListener {
         JFrame parent;
         public JButtonActionListener(JFrame p) {
              parent = p;
         public void actionPerformed(ActionEvent e) {
    //How do I update the textField of MyButton JFrame from here
    }

    hemanthjava wrote:
    Why is the jextfield on the jframe so small. Because it hasn't been given a preferred size and FlowLayout isn't going to assign it one. Why not initialize it like:
            jtfClick = new JTextField(12);
    Also How do I update the textField of MyButton JFrame from JButtonActionListener?You could pass a reference to the JFrame to the action listener by way of the listener's constructor.

  • Doubt in processing of  statements after calling JFrame class

    I have two java classes.
    The first one is Normal class and the second one is a JFrame class.
    In the first Class, i created an object for second JFrame class followed by a set of statements.
    Based on the input from the second class, i must process the statements, the problem i am facing is after creating the object for second frame class , the first class continues execution of the remaining statements. I must stop the execution of the statements until i get an input from the second class.
    How can i make the first class wait for an input from the second class.
    if possible provide me some source code.
    Thanks for your help!.

    Use a modal JDialog instead of a JFrame.
    db

  • Is correct? Application (JFrame) to Applet (JApplet)

    I need to convert a java application (JFrame) into an applet (JApplet), and I have seen a few "big steps":
    1�: make the class extends to JApplet instead of a JFrame
    2�: To replace the construction method by init ()
    3�: To comment the main method
    Is correct?, because I have some doubts that later I�ll explain
    Thanks

    I think in the init method (in a JApplet) I cannot call the super method. but my problem is how to change this? if in others files (in Files.java) I have calls to super metod, because thus it constructs a dialog box, asking for a file.
    In file Files.java I have a class called "Abort" (extends to JDialog) in whitch:
    /* class Files.java */
    class Abort extends JDialog
              boolean abort = true;
              JTextArea mensage = null;
              JButton acept = new JButton("Acept");
              JButton cancel = new JButton("Cancel");
              Abort(String nanemFile)
                   super(MainClassFile.mainWindow, " Attention!", true);
    /* clas Files.java */Please help

  • Question on JFrame

    Hi All,
    I have a small doubt to be clarified.We have JFrame class inside javax.swing package as every one knows it and closing of frame is possible with EXIT_ON_CLOSE and some other operations like DISPOSE_ON_CLOSE,HIDE_ON_CLOSE etc.But how to disable a frame(in the sense frame should not be visible initially and later should be enabled after some time).Is there any way to do this..Please help me on this query.
    Thanks in advance to all.

    Darryl.Burke wrote:
    Hmm. And did you read the API to see whether there were any mehods related to the visible property of JFrame?The method won't be easy to find in the JFrame API but is to be found in the API of one of JFrame's parents, namely the Window class. Please have a look here:
    [http://java.sun.com/javase/6/docs/api/java/awt/Window.html]

  • Graphics object of two JFrames in a single application

    Hi,
    I am trying to pop up two JFrames in a Java application, which are supposed to display different things(both have Jpanels to do so). However, I think that the same Graphics object is getting passed around, because the contents from the first JFrames's Jpanel is getting superimposed on the other's! I have tried explicity to insert a 'this.getGraphics()' in all the paints and then use those Graphics objects for drawing purposes, but that has not solved the problem yet!
    Any suggestions on what needs to be done?? Unfortunately, the code is too much to paste here:)
    Thanks!!!

    However, I think that the same Graphics object is getting passed aroundI doubt this. If you are override paint(..) or paintComponent(...) methods then you have a bug in your code. There is no need to explicitly insert a this.getGraphics(..) in your code.
    Maybe you are trying to use the same panel in two frames. This is not allowed.

  • Technical doubt about setBounds() method

    Hi all.
    I have a little doubt. I don't completely understand the behaviour of setBounds() method of a JComponent extending class.
    I prepared a little test application to explain this doubt. Here it is:
    import javax.swing.*;
    import java.awt.*;
    public class TestSetBounds extends JFrame{
        JPanel myPanel = new JPanel();
        MyComponent myComp = new MyComponent();
        public TestSetBounds() {
            super("SetBounds Test");
            setSize(480, 320);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            myPanel.add(myComp);
            setContentPane(myPanel);
            setVisible(true);
        public static void main(String args[]) {
            TestSetBounds tsb = new TestSetBounds();
    class MyComponent extends JComponent implements Runnable
        // setting dimension properties
        int compWidth = 25;
        int compHeight = 50;
        // these values are for testing
        int xStart = 490;
        int xEnd = -12;
        Thread t;
        public MyComponent()
            super();
            setOpaque(true);
            setVisible(true);
            if (t == null)
                t = new Thread(this);
                t.start();
        public void paintComponent(Graphics g)
            super.paintComponents(g);
            setBounds(xStart, 160, compWidth, compHeight);
            Graphics2D area2D = (Graphics2D) g;
            area2D.setColor(Color.RED);
            area2D.fillRect(0, 0, compWidth, compHeight);
        public Dimension getPreferredSize() {
          return new Dimension(compWidth, compHeight);
        public Dimension getMaximumSize() {
          return getPreferredSize();
        public void run()
            for(   ; xStart > xEnd; xStart--)
                repaint();
                try
                    {t.sleep(10);}
                catch (Exception exc) {}
    }   I tested two situations:
    a. Setting xStart = 100 and xEnd = -12, the application run how I expected. With negative value of x coordinate, my component is painted starting out of panel. We only can see my component portion which remains on the panel.
    b. Setting xStart = 490 and xEnd = 300. My component is initially painted out of panel, like test a. During for-cicle, xStart value decreases, entering the panel width value. At this point I must see the component portion which remain on the panel.But the component seems not be painted.
    Why this behaviour?
    Thanks,
    Massimiliano

    Your immediate problem can be solved by making two changes:
    a) your component has no initial size:
    setSize(25, 50); // this is new
    setOpaque(true);
    setVisible(true); // not requiredb) use setLocation() to reposition the component
    setLocation(xStart, 160);
    //repaint(); // not required since changing the location will cause a repaintHowever the code still has many areas of concern.
    For example, after the component has stopped moving, resize the frame. Notice how the component jumps to the top and middle of the frame? This is because by default a JPanel uses a LayoutManager. When you resize the frame the LayoutManager is invoked and the component is positioned based on the rules of the LayoutManager.
    So, you need to read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html]Using Layout Manager to understand the difference between using a Layout Manager and using "Absolute Positioning" (which is what you are attempting to do).
    You should not be altering the "size" or "location" of the component in the paintComponent() method (ie. get rid of the setBounds()). These changes should be done externally as we did by using the setLocation(..) method.
    When you fill the rectangle you should just use getSize().width and getSize().height, instead of your hard coded variables. Then you can dynamically change the size of your component by using the setSize() method.
    The size of the component should not be hard coded. Once you've made the above change you can simply do:
    MyComponent component = new MyComponent();
    component.setSize(25, 50);

  • Undecorated jframe resize problem

    i created a custom jframe look by setting a jframe to undecorated and designing my own maximize/minimize/close buttons and other things to improve its appearence
    the problem is that when set to undercorated all the default resizing/move methods are gone
    i tried implementing my own resize methods, they seem to work but it flashes like crazy while resizing
    anyone have any idea how to stop all the flashing or a better way to implement this?
    the following is a small example of the problem i am having, i only implemented the north resize part so the code can be easier to read.
    thnx in advance
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.imageio.*;
    import java.io.*;
    import java.awt.image.BufferedImage;
    public class TestFrame extends JFrame implements MouseMotionListener, MouseListener
         Point sp;
         int     compStartHeight;
         int minHeight = 100;
         JPanel frameContent = new JPanel();
         public TestFrame()
              super("testing frame");
              setSize(600, 600);
              setContentPane(frameContent);
              frameContent.setBackground(Color.black);
              frameContent.setLayout(new BoxLayout(frameContent, BoxLayout.Y_AXIS));     
              setUndecorated(true);
              addMouseMotionListener(this);
              addMouseListener(this);
              JButton testButton = new JButton("TEST");
              JButton testButton2 = new JButton ("TEST2");
              frameContent.add(testButton);
              frameContent.add(Box.createVerticalGlue());
              frameContent.add(testButton2);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setVisible(true);
         public void mouseMoved(MouseEvent e)
              Point p = e.getPoint();
              if (p.y > e.getComponent().getSize().height - 5)
                   setCursor( Cursor.getPredefinedCursor( Cursor.N_RESIZE_CURSOR ));
              else
                   setCursor( Cursor.getPredefinedCursor( Cursor.DEFAULT_CURSOR));
         public void mouseDragged(MouseEvent e)
              Point p = e.getPoint();
              int compWidth = getSize().width;
              if (getCursor().getType() == Cursor.N_RESIZE_CURSOR)
                   int nextHeight = compStartHeight+p.y-sp.y;
                   if (nextHeight > minHeight)
                        setSize(compWidth,nextHeight);
                        validate();
              else
                   int x = getX()+p.x-sp.x;     
                   int y = getY()+p.y-sp.y;     
                   setLocation(x,y);
         public void mousePressed(MouseEvent e)
              sp = e.getPoint();
              compStartHeight = getSize().height;
         public void mouseEntered(MouseEvent e)
        public void mouseExited(MouseEvent e)
              if (sp == null)
                   setCursor( Cursor.getPredefinedCursor( Cursor.DEFAULT_CURSOR));
        public void mouseClicked(MouseEvent e)
        public void mouseReleased(MouseEvent e)
              sp = null;
         public static void main(String[] args)
         new TestFrame();
    }

    I doubt there is a faster / easier way to resize.
    Have you tried adding
    public boolean isDoubleBuffered()
      return true;
    }To over-ride Component.isDoubleBuffered. This should sort out your flickering problem.
    Bamkin

  • Doubt with JMF

    Hi Java Rockers,
    Can any one clarify my doubt?
    I have a doubt in JMF.
    I just wrote a code to play audio and video and
    it was able to play audio and video in windows.
    When i run the same code in Mandriva Linux,
    'I obtained a message "Audio Bus Busy" and it does not played song.
    Actually What went to wrong?
    is it possible to play audio and videos With Java in Linux.?
    Java Version Used:JDK1.6

    Thank you Sir for your
    Suggestion and Help.Here is my Code:
    You please tell me necessary modifications that
    i have to make with this.
    I have 2 classes.
    One as JFrame and others a JPanel.
    JFrame Class:
    import java.net.URL;
    import java.io.File;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.ActionEvent;
    import java.awt.event.MouseAdapter;
    import java.awt.event.KeyEvent;
    import java.awt.event.ActionEvent;
    import javax.swing.JOptionPane;
    import java.util.Vector;
    import javax.media.*;
    class Media extends JFrame implements Runnable {
    MediaPanel mediaPanel ;
    Thread th;
    JScrollPane scrollPane2;
    Media(){
    MenuBar mbar=new MenuBar();
    Menu m=new Menu("File");
    MenuShortcut sc1=new MenuShortcut(KeyEvent.VK_O);
    MenuItem m1=new MenuItem("Open",sc1);
    m1.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
                   if(th!=null)
                        th.stop();
                   else{
                   Frame fr=new Frame();
                   FileDialog fd=new FileDialog(fr,"Open");
                   fd.setDirectory("E:\\songs");     
                   fd.setVisible(true);
                   try{
                   String name="file:\\"+fd.getDirectory()+"\\"+fd.getFile().toString();
                   URL mediaURL =new URL(name);
                   mediaPanel= new MediaPanel( mediaURL );
                   int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
                   int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
                   scrollPane2=new JScrollPane(mediaPanel,v,h);
                   setLayout(new BorderLayout());
                   getContentPane().add(scrollPane2,BorderLayout.CENTER);
                   if ( mediaURL != null ) {
                        mediaPanel.setVisible(true);
                        scrollPane2.setViewportView(mediaPanel);
                   repaint();
                   setSize(470,360);
                   //refresh_preview(new URL("file:\\"+fd.getDirectory()+"\\"+fd.getFile().toString()));
                   catch(Exception E){
                   JOptionPane.showMessageDialog(null,"Failed to play!"+"\n"+"Reason:"+"\n"+E.toString(),"Error",JOptionPane.ERROR_MESSAGE);
    MenuShortcut sc3=new MenuShortcut(KeyEvent.VK_E);
    MenuItem m3=new MenuItem("Exit",sc3);
    m3.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
              dispose();
    m.add(m1);
    m.add(m3);
    Menu Help=new Menu("Help");
    MenuShortcut hc1=new MenuShortcut(KeyEvent.VK_H);
    MenuItem H1=new MenuItem("About",hc1);
    H1.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
         JOptionPane.showMessageDialog(null,"Java ™ Media Player!","Version Info.. :",JOptionPane.INFORMATION_MESSAGE);
    MenuShortcut hc2=new MenuShortcut(KeyEvent.VK_Q);
    MenuItem H2=new MenuItem("JMF Installation Procedures",hc2);
    H2.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
         new HTMLHandler("file:\\"+System.getProperty("user.dir")+"\\html\\jmf.htm");
    MenuShortcut hc3=new MenuShortcut(KeyEvent.VK_S);
    MenuItem H3=new MenuItem("JMF Supportive File Formats",hc3);
    H3.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
         new HTMLHandler("file:\\"+System.getProperty("user.dir")+"\\html\\jmfdoc.htm");
    Help.add(H1);
    Help.add(H2);
    Help.add(H3);
    mbar.add(m);
    mbar.add(Help);
    setMenuBar(mbar);
    JLabel jl=new JLabel("Java Media Player",SwingConstants.CENTER);
    getContentPane().add(jl,BorderLayout.SOUTH);
    setSize(600,300);
    setTitle("Video/Audio Player in java");
    setVisible(true);
         Toolkit kit = Toolkit.getDefaultToolkit();
         Dimension screenSize = kit.getScreenSize();
         int screenWidth = screenSize.width;
         int screenHeight = screenSize.height;
         java.awt.Image img = kit.getImage("images//audio-category.jpg");
         setSize(screenWidth /2, screenHeight / 2);
         setLocation(screenWidth /4, screenHeight /4);
         setIconImage(img);
    Media(URL media_file){
    MenuBar mbar=new MenuBar();
    Menu m=new Menu("File");
    MenuShortcut sc1=new MenuShortcut(KeyEvent.VK_O);
    MenuItem m1=new MenuItem("Open",sc1);
    m1.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
                   if(th!=null)
                        th.stop();
                   else{
                   Frame fr=new Frame();
                   FileDialog fd=new FileDialog(fr,"Open");
                   fd.setVisible(true);
                   try{
                   String name="file:\\"+fd.getDirectory()+"\\"+fd.getFile().toString();
                   URL mediaURL =new URL(name);
                   mediaPanel= new MediaPanel( mediaURL );
                   int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
                   int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
                   scrollPane2=new JScrollPane(mediaPanel,v,h);
                   setLayout(new BorderLayout());
                   //JLabel jl=new JLabel("Java Media Player",SwingConstants.CENTER);
                   //getContentPane().add(jl,BorderLayout.SOUTH);
                   getContentPane().add(scrollPane2,BorderLayout.CENTER);
                   if ( mediaURL != null ) {
                        mediaPanel.setVisible(true);
                        scrollPane2.setViewportView(mediaPanel);
                   catch(Exception E){
                   JOptionPane.showMessageDialog(null,"Failed to play!"+"\n"+"Reason:"+"\n"+E.toString(),"Error",JOptionPane.ERROR_MESSAGE);
    MenuShortcut sc3=new MenuShortcut(KeyEvent.VK_E);
    MenuItem m3=new MenuItem("Exit",sc3);
    m3.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
              dispose();
    m.add(m1);
    m.add(m3);
    Menu Help=new Menu("Help");
    MenuShortcut hc1=new MenuShortcut(KeyEvent.VK_H);
    MenuItem H1=new MenuItem("About",hc1);
    H1.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
         JOptionPane.showMessageDialog(null,"Java ™ Media Player!","Version Info.. :",JOptionPane.INFORMATION_MESSAGE);
    MenuShortcut hc2=new MenuShortcut(KeyEvent.VK_Q);
    MenuItem H2=new MenuItem("JMF Installation Procedures",hc2);
    H2.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
         new HTMLHandler("file:\\"+System.getProperty("user.dir")+"\\html\\jmf.htm");
    MenuShortcut hc3=new MenuShortcut(KeyEvent.VK_S);
    MenuItem H3=new MenuItem("JMF Supportive File Formats",hc3);
    H3.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e){
         new HTMLHandler("file:\\"+System.getProperty("user.dir")+"\\html\\jmfdoc.htm");
    Help.add(H1);
    Help.add(H2);
    Help.add(H3);
    mbar.add(m);
    mbar.add(Help);
    setMenuBar(mbar);
    JLabel jl=new JLabel("Java Media Player",SwingConstants.CENTER);
    URL mediaURL = null;
    mediaURL = media_file;
    mediaPanel= new MediaPanel( mediaURL );
    int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
    int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
    scrollPane2=new JScrollPane(mediaPanel,v,h);
    setLayout(new BorderLayout());
    getContentPane().add(scrollPane2,BorderLayout.CENTER);
    getContentPane().add(jl,BorderLayout.SOUTH);
    if ( mediaURL != null ) {
    mediaPanel.setVisible(true);
    scrollPane2.setViewportView(mediaPanel);
    setSize(600,300);
    setTitle("Video/Audio Player in java");
    setVisible(true);
         Toolkit kit = Toolkit.getDefaultToolkit();
         Dimension screenSize = kit.getScreenSize();
         int screenWidth = screenSize.width;
         int screenHeight = screenSize.height;
         java.awt.Image img = kit.getImage("images//audio-category.jpg");
         setSize(screenWidth /2, screenHeight / 2);
         setLocation(screenWidth /4, screenHeight /4);
         setIconImage(img);
    void init(){
    public void refresh_preview(URL media_file){
    URL mediaURL = null;
    mediaURL = media_file;
    if ( mediaURL != null ){
    MediaPanel mediaPanel = new MediaPanel( mediaURL );
    mediaPanel.setVisible( true );
    scrollPane2.setViewportView(mediaPanel);
    public void run(){
    try{
    th.stop();
    catch(Exception E){}
    **JPanel Class:**
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.io.IOException;
    import java.net.URL;
    import javax.media.CannotRealizeException;
    import javax.media.Manager;
    import javax.media.NoPlayerException;
    import javax.media.Player;
    import javax.swing.JPanel;
    import javax.swing.JLabel;
    import javax.swing.ImageIcon;
    import javax.swing.JOptionPane;
    public class MediaPanel extends JPanel
    JLabel l=new JLabel();
    public MediaPanel( URL mediaURL ){
    setLayout( new BorderLayout() ); // use a BorderLayout
    // Use lightweight components for Swing compatibility
    Manager.setHint( Manager.PLUGIN_PLAYER, new Boolean(false));
    try
    // create a player to play the media specified in the URL
    Player mediaPlayer = Manager.createRealizedPlayer( mediaURL );
    // get the components for the video and the playback controls
    Component video = mediaPlayer.getVisualComponent();
    Component controls = mediaPlayer.getControlPanelComponent();
    if ( video != null )
    add( video, BorderLayout.CENTER ); // add video component
    else{
    add(l);
    l.setIcon(new ImageIcon("images\\black.jpg"));
    if ( controls != null )
    add( controls, BorderLayout.SOUTH ); // add controls
    mediaPlayer.start(); // start playing the media clip
    } // end try
    catch ( NoPlayerException e ){
    System.err.println( "No media player found" );
         JOptionPane.showMessageDialog(null,"Reason:"+"\n"+e.toString(),"ERROR",JOptionPane.ERROR_MESSAGE);
    catch ( CannotRealizeException c ){
    System.err.println( "Could not realize media player" );
         JOptionPane.showMessageDialog(null,"Reason:"+"\n"+c.toString(),"ERROR",JOptionPane.ERROR_MESSAGE);
    catch ( IOException i ){
    System.err.println( "Error reading from the source" );
         JOptionPane.showMessageDialog(null,"Reason:"+"\n"+i.toString(),"ERROR",JOptionPane.ERROR_MESSAGE);
    ]

  • Applet doubt

    I m taking this code from else where .but in o/p after login if u see on right side i get jtree-color-sports-food--like this menu.If i want my own menu how can i do this ,if any one have idea pls post me to [email protected] or post here
    java code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class LoginApplet2 extends JApplet {
    public void init() {
    add( new MainGui(), BorderLayout.CENTER );
    validate();
    public static void main(String[] args) {
    Runnable r = new Runnable() {
    public void run() {
    JFrame f = new JFrame("Log-In app.");
    f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    f.add( new MainGui(), BorderLayout.CENTER );
    f.pack();
    f.setLocationByPlatform(true);
    f.setVisible(true);
    SwingUtilities.invokeLater(r);
    class MainGui extends JPanel {
    JButton logIn;
    JLabel status;
    JPasswordField passwordField;
    JTextField username;
    JLabel logInLabel;
    JPanel mainPanel;
    JPanel usernamePasswordPanel;
    CardLayout cards;
    MainGui() {
    super.setLayout(new BorderLayout(3,3));
    status = new JLabel("Log-In to proceed");
    add(status, BorderLayout.NORTH);
    mainPanel = new JPanel();
    cards = new CardLayout();
    mainPanel.setLayout(cards);
    usernamePasswordPanel = new JPanel(new GridLayout(2,2,3,3));
    usernamePasswordPanel.add( new JLabel("Username:") );
    username = new JTextField(10);
    usernamePasswordPanel.add( username );
    usernamePasswordPanel.setBorder(new EmptyBorder(25,25,25,25));
    usernamePasswordPanel.add( new JLabel("Password:") );
    passwordField = new JPasswordField(10);
    usernamePasswordPanel.add( passwordField );
    logInLabel = new JLabel("Log In to use the app.");
    mainPanel.add(logInLabel,"login");
    JPanel mainApp = new JPanel(new BorderLayout(3,3));
    mainApp.add(new JScrollPane(new JTree()), BorderLayout.WEST);
    mainApp.add(new JTextArea(4,20), BorderLayout.CENTER);
    mainPanel.add(mainApp, "app");
    logIn = new JButton("Log In");
    logIn.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ae) {
    if (logIn.getText().equals("Log In")) {
    JOptionPane.showMessageDialog(
    logIn,
    usernamePasswordPanel,
    "Log-In (Pswd hint: any 4+ letters or digits)",
    JOptionPane.QUESTION_MESSAGE);
    checkPassWord();
    } else {
    logOut();
    add(logIn, BorderLayout.SOUTH);
    add(mainPanel, BorderLayout.CENTER);
    setBorder(new EmptyBorder(4,4,4,4));
    public void checkPassWord() {
    // change this for server based authentication
    if (passwordField.getPassword().length>3) {
    cards.show(mainPanel, "app");
    logIn.setText("Log Out");
    status.setText("Logged in as " + username.getText());
    } else {
    status.setText("Log In failed!");
    public void logOut() {
    cards.show(mainPanel, "login");
    logIn.setText("Log In");
    status.setText("Logged out");
    passwordField.setText("");
    related html::
    <html>
    <head></head>
    <body>
    <applet code="LoginApplet2.class" width=300 height=300>
    </applet>
    </body>
    </html>

    >
    I m taking this code from else where . ..>Where? If it is available on the net, it is better to give the URL.
    And whenever pasting code, code snippets, HTML/XML or input/output, please use the code tags. The code tags help preserve the indentation and formatting of the text. To use the code tags, select the text and click the CODE button on the Plain Text tab of the message posting form.(1)
    >
    .. but in o/p after login if u see on right side i get jtree-color-sports-food--like this menu.>Please spell words fully(2). For the sake of saving typing a couple of letters, it makes people seem like buffoons.
    >
    ...If i want my own menu how can i do this ,if any one have idea pls post me to [email protected] or post here >
    - (2) Those words are 'please' and 'you'.
    - The word I should always be upper case. Always.
    - Please add 2 spaces and a single upper case letter at the start of every sentence. This helps the reader, and you would not want to make it harder for people to help you, would you?
    - "If i want my own menu how can i do this" is a question, and should be 'marked' as a question with a question mark -> "If I want my own menu how can I do this?".
    - And since it came up - 'doubt' seems to be an Indian(/English) word for 'question'. These are international forums, so that subject should be 'applet question'
    - It is not a good idea to invite people on public forums to tutor you privately. It is generally felt that public forums are also to help people 'searching' for the answer later, and if a thread goes to email, that opportunity is lost.
    - Posting an email address to a public forum will attract a torrent of spam.
    But the 'short answer' to your question is..
    >
    java code:
    mainApp.add(new JScrollPane(new JTree()), BorderLayout.WEST);>..Use one of the [JTree constructors|http://java.sun.com/javase/6/docs/api/javax/swing/JTree.html#constructor_summary] *(<- link)* that accepts an argument. For further details, see [How to Use Trees|http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html] *(<- link)* in the Java Tutorial.
    (1) And here is how that snippet looks when inside code tags
        mainApp.add(new JScrollPane(new JTree()), BorderLayout.WEST);
    ...

  • JFrame setting inner size?

    Hello,
    I've a simple program which opens a JFrame with a JPanel inside it.
    I've set the layout to null and manually placed the JPanel with 0,0,600,400 as the bounds.
    The JFrame size is set to 600,500
    The problem: The JFrame has the correct size, but I want the size of the inside of the JFrame to be 600*500 instead of everything like title bar included, what's the best way to automatically do this?
    My sample program:
    import java.awt.Color;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    public class Problem {
        public static void main(String[] args) {
            aGUI gui = new aGUI();
            gui.setDefaultCloseOperation(3);
            gui.setSize(600, 500);
            gui.setVisible(true);
    class aGUI extends JFrame {
        public aGUI() {
            super("My example...");
            setLayout(null);
            JPanel p = new JPanel();
            p.setBounds(0, 0, 600, 400);
            p.setBackground(Color.red);
            add(p);
    }When you run it, and make the frame bigger, you'll notice that some of the red is hidden behind the frame...

    The_Pointer wrote:
    The problem: The JFrame has the correct size, but I want the size of the inside of the JFrame to be 600*500 instead of everything like title bar included, what's the best way to automatically do this?What is the exact problem I doubt. But in my habit, if you specify the size of the panel inside JFrame, how do you expect that'll be resized as the frame get maximized!!!

  • Problem with threads in JFrame

    Hy everyone...i have a small problem when i try to insert clock in my JFrame , because all i get is an empty text field.
    What i do is that i create inner class that extends Thread and implements Runnable , but i dont know ... i saw some examples on the intrnet...but they are all for Applets...
    Does any one know how i can implement this in JFrame (JTextField in JFrame).
    Actually any material on threads in JFrame or JPanel would be great....THNX.

    For my original bad thread version, I have rewritten it mimicking javax.swing.Timer
    implementation, reducing average CPU usage to 2 - 3%.
    Will you try this:
    import javax.swing.*;
    import java.awt.*;
    import java.text.*;
    import java.util.*;
    public class SamurayClockW{
      JFrame frame;
      Container con;
      ClockTextFieldW ctf;
      public SamurayClockW(){
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        con = frame.getContentPane();
        ctf = new ClockTextFieldW();
        con.add(ctf, BorderLayout.SOUTH);
        frame.setBounds(100, 100, 300, 300);
        frame.setVisible(true);
        ctf.start();
      public static void main(String[] args){
        new SamurayClockW();
    class ClockTextFieldW extends JTextField implements Runnable{
      String clock;
      boolean running;
      public ClockTextFieldW(){
        setEditable(false);
        setHorizontalAlignment(RIGHT);
      public synchronized void start(){
        running = true;
        Thread t = new Thread(this);
        t.start();
      public synchronized void stop(){
        running = false;
      public synchronized void run(){
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        try{
          while (running){
            clock = sdf.format(new Date());
            SwingUtilities.invokeLater(new Runnable(){
              public void run(){
                setText(clock);
            try{
              wait(1000);
            catch (InterruptedException ie){
              ie.printStackTrace();
        catch (ThreadDeath td){
          running = false;
    }

  • Can not refresh JFrame

    I am new to Java programming however I have undertaken a project to build a serial communication application using J2SE 1.4 w/javax.comm API. I am having a problem in which I detect a button click with action listener and post a JOptionPane message. Once the JOptionPane is closed I execute the desired task however the pane leaves a grey block overlaying the JFrame. I have been unable to figure out how to repaint the JFrame. Can anyone give me suggestions?
    Thanks
    D :-)

    A more active example:
    if (JOptionPane.showConfirmDialog(null, "Are you
    u sure?",
    "Are you sure?", JOptionPane.YES_NO_OPTION) ==
    N) == 0) {
    Thread t = new Thread(new Runnable() {
    public void run() {
    // Do your work in here!
    t.start();
    }This will leave the JFrame completely free to do
    whatever else it wants, so if you want it to do
    nothing, you may want to write a 'disableFrame()'
    method which disables everything, and perhaps stick a
    JProgressBar at the bottom to show that something's
    going on. This needs to be controlled via the 'run()'
    method.
    Let me know if this helps.
    RichardThanks Richard.
    Do I have to stop the thread explicitly. The task looks for a serial event.

  • Need to convert JApplet to JFrame

    I need to write code for where I have 60 balls bouncing around inside a window. The client will then be able to select a button and it will pull out a ball with the number 1-60 written on it. The user will be able to do this up to 7 times. Each time it is done the past numbers that have already appeared can not reappear. What I am stuck on right now is geting my balls into a JFrame. Can anyone give advice or show how to. I currently have my 60 balls running in a JApplet. Here is the JAVA code and the HTML code. Thanks!
    Here is the JAVA code
    import java.awt.*;
    import java.applet.*;
    import java.util.*;
    import javax.swing.*;
    class CollideBall{
    int width, height;
    public static final int diameter=20;
    //coordinates and value of increment
    double x, y, xinc, yinc, coll_x, coll_y;
    boolean collide;
    Color color;
    Graphics g;
    Rectangle r;
    //the constructor
    public CollideBall(int w, int h, int x, int y, double xinc, double yinc, Color c){
    width=w;
    height=h;
    this.x=x;
    this.y=y;
    this.xinc=xinc;
    this.yinc=yinc;
    color=c;
    r=new Rectangle(150,80,130,90);
    public double getCenterX() {return x+diameter/2;}
    public double getCenterY() {return y+diameter/2;}
    public void alterRect(int x, int y, int w, int h){
    r.setLocation(x,y);
    r.setSize(w,h);
    public void move(){
    if (collide){  
    double xvect=coll_x-getCenterX();
    double yvect=coll_y-getCenterY();
    if((xinc>0 && xvect>0) || (xinc<0 && xvect<0))
    xinc=-xinc;
    if((yinc>0 && yvect>0) || (yinc<0 && yvect<0))
    yinc=-yinc;
    collide=false;
    x+=xinc;
    y+=yinc;
    //when the ball bumps against a boundary, it bounces off
    if(x<6 || x>width-diameter){
    xinc=-xinc;
    x+=xinc;
    if(y<6 || y>height-diameter){
    yinc=-yinc;
    y+=yinc;
    //cast ball coordinates to integers
    int x=(int)this.x;
    int y=(int)this.y;
    //bounce off the obstacle
    //left border
    if(x>r.x-diameter&&x<r.x-diameter+7&&xinc>0&&y>r.y-diameter&&y<r.y+r.height){
    xinc=-xinc;
    x+=xinc;
    //right border
    if(x<r.x+r.width&&x>r.x+r.width-7&&xinc<0&&y>r.y-diameter&&y<r.y+r.height){
    xinc=-xinc;
    x+=xinc;
    //upper border
    if(y>r.y-diameter&&y<r.y-diameter+7&&yinc>0&&x>r.x-diameter&&x<r.x+r.width){
    yinc=-yinc;
    y+=yinc;
    //bottom border
    if(y<r.y+r.height&&y>r.y+r.height-7&&yinc<0&&x>r.x-diameter&&x<r.x+r.width){
    yinc=-yinc;
    y+=yinc;
    public void hit(CollideBall b){
    if(!collide){
    coll_x=b.getCenterX();
    coll_y=b.getCenterY();
    collide=true;
    public void paint(Graphics gr){
    g=gr;
    g.setColor(color);
    //the coordinates in fillOval have to be int, so we cast
    //explicitly from double to int
    g.fillOval((int)x,(int)y,diameter,diameter);
    g.setColor(Color.white);
    g.drawArc((int)x,(int)y,diameter,diameter,45,180);
    g.setColor(Color.darkGray);
    g.drawArc((int)x,(int)y,diameter,diameter,225,180);
    public class BouncingBalls extends Applet implements Runnable {
    Thread runner;
    Image Buffer;
    Graphics gBuffer;
    CollideBall ball[];
    //Obstacle o;
    //how many balls?
    static final int MAX=60;
    boolean intro=true,drag,shiftW,shiftN,shiftE,shiftS;
    boolean shiftNW,shiftSW,shiftNE,shiftSE;
    int xtemp,ytemp,startx,starty;
    int west, north, east, south;
    public void init() {  
    Buffer=createImage(getSize().width,getSize().height);
    gBuffer=Buffer.getGraphics();
    ball=new CollideBall[MAX];
    int w=getSize().width-5;
    int h=getSize().height-5;
    //our balls have different start coordinates, increment values
    //(speed, direction) and colors
    for (int i = 0;i<60;i++){
    ball=new CollideBall(w,h,50+i,20+i,1.5,2.0,Color.white);
    /* ball[1]=new CollideBall(w,h,60,210,2.0,-3.0,Color.red);
    ball[2]=new CollideBall(w,h,15,70,-2.0,-2.5,Color.pink);
    ball[3]=new CollideBall(w,h,150,30,-2.7,-2.0,Color.cyan);
    ball[4]=new CollideBall(w,h,210,30,2.2,-3.5,Color.magenta);
    ball[5]=new CollideBall(w,h,360,170,2.2,-1.5,Color.yellow);
    ball[6]=new CollideBall(w,h,210,180,-1.2,-2.5,Color.blue);
    ball[7]=new CollideBall(w,h,330,30,-2.2,-1.8,Color.green);
    ball[8]=new CollideBall(w,h,180,220,-2.2,-1.8,Color.black);
    ball[9]=new CollideBall(w,h,330,130,-2.2,-1.8,Color.gray);
    ball[10]=new CollideBall(w,h,330,10,-2.1,-2.0,Color.gray);
    ball[11]=new CollideBall(w,h,220,230,-1.2,-1.8,Color.gray);
    ball[12]=new CollideBall(w,h,230,60,-2.3,-2.5,Color.gray);
    ball[13]=new CollideBall(w,h,320,230,-2.2,-1.8,Color.gray);
    ball[14]=new CollideBall(w,h,130,300,-2.7,-3.0,Color.gray);
    ball[15]=new CollideBall(w,h,210,90,-2.0,-1.8,Color.gray);*/
    public void start(){
    if (runner == null) {
    runner = new Thread (this);
    runner.start();
    /* public void stop(){
    if (runner != null) {
    runner.stop();
    runner = null;
    public void run(){
    while(true) {
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    try {runner.sleep(15);}
    catch (Exception e) { }
    //move our balls around
    for(int i=0;i<MAX;i++)
    ball[i].move();
    handleCollision();
    repaint();
    boolean collide(CollideBall b1, CollideBall b2){
    double wx=b1.getCenterX()-b2.getCenterX();
    double wy=b1.getCenterY()-b2.getCenterY();
    //we calculate the distance between the centers two
    //colliding balls (theorem of Pythagoras)
    double distance=Math.sqrt(wx*wx+wy*wy);
    if(distance<b1.diameter)
    return true;
    return false;
    private void handleCollision()
    //we iterate through all the balls, checking for collision
    for(int i=0;i<MAX;i++)
    for(int j=0;j<MAX;j++)
    if(i!=j)
    if(collide(ball[i], ball[j]))
    ball[i].hit(ball[j]);
    ball[j].hit(ball[i]);
    public void update(Graphics g)
    paint(g);
    public void paint(Graphics g)
    gBuffer.setColor(Color.lightGray);
    gBuffer.fillRect(0,0,getSize().width,getSize().height);
    gBuffer.draw3DRect(5,5,getSize().width-10,getSize().height-10,false);
    //paint our balls
    for(int i=0;i<MAX;i++)
    ball[i].paint(gBuffer);
    g.drawImage (Buffer,0,0, this);
    Here is the HTML code
    <html>
    <body bgcolor="gray">
    <br><br>
    <div align="center">
    <applet code="BouncingBalls.class" width="1000" height="650"></applet>
    </div>
    </body>
    </html>

    In the future, Swing related questions should be posted in the Swing forum.
    First you need to convert your custom painting. This is done by overriding the paintComponent() method of JComponent or JPanel. Read the Swing tutorial on [Custom Painting|http://java.sun.com/docs/books/tutorial/uiswing/TOC.html].
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the [Code Formatting Tags|http://forum.java.sun.com/help.jspa?sec=formatting], so the posted code retains its original formatting.

  • Problem with Paining in a Panel in a JFrame.

    So I can paint directly on a JFrame, and I can paint on a class that extends Panel, and put the Panel on a JFrame. But if I try to Repaint the Panel it won't show on the JFrame. Do I have to do anything to the JFrame to show the changes to the objects inside as well?

    I'm not sure if you've done this, but don't change the paint method when using Swing components, use paintComponent instead. By default, the JFrame will paint its children. Just remember whenever overriding any of the paintComponent methods to call super.paintComponent(g) first.

Maybe you are looking for

  • How to pass a querry as a url parameter

    Hi Forum I need to pass an sql query as a url parameter I wrote the following code: String applicationURL = WDURLGenerator.getApplicationURL("local/AgencyFee_SettlementSummaryReport", "Ko_AgencyFee_PrinterFriendly"); applicationURL="?distACN="wdConte

  • Recommend new speakers to replace logitech k-530?  don't really need 5.1, but 2.1 would suffice

    Just setting up my Imac.  Learning that my Logitech K-530 system from my pc, is not very compatible due to the fact the Imac outputs digital/optical audio, but the old system wants analog. So, I suppose I really don't need 5.1 sound, since the system

  • Starting the DAC Server

    Hi All, For installing OBIA 11g i have installed OBIEE 111g and DAC 11g. While staring DAC server using startserver.bat file i am getting error like windows cannot find '-server'.Make sure typed name correctly, and then try againAnd startserver.bat f

  • Plz Help - Translation Builder Error!!

    hello , I'm new & clean for translation builder (6i) and now i'm got the error msg "XBD-00024 Translation Builder tables not found" and got error msg again when tried to add project ("XBD-00301: Project : XXX , insertion failed") What should i do? Ho

  • Rescue and Recovery to USB

    Hi, in preparation for my new machine, got a quick question. I though i read somewhere that you could make the rescue and recovery onto usb stick? Anyone with experience with this, either doing it or if it can be done. Lenovo x120e E-350, XT Momentus