Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

need Help with java GUI programming

/*
my problem with this code is that after we compine

:>javac app1.java

and after runing

:>java app1

window pops up and after i press open menu item at the menu bar,
those number of buttons should appear on the frame.

and buttons simply doesnt appear on the frame.

in order to make the buttons appear, you have to resize the frame a lttle bit, then only you can see the active buttons;

this will be a very big issue when frames reSizable(false) occuers, if the frame is not resizable, then simply buttons wont pop up

is this a bug or a mistake by me? can somebody be kind enough to explain ? :)

*/

import java.awt.Frame;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.Menu;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class app1 extends Frame{

public static void main(String argv[]){
app1 fa=new app1();
//Change from BorderLayout default
fa.setLayout(new FlowLayout());
fa.setSize(400,300);
fa.setVisible(true);
}

app1(){
MenuBar mb = new MenuBar();

Menu m = new Menu("File");

mb.add(m);

MenuItem open = new MenuItem("Open");

open.addActionListener(menuOpen);

m.add(open);

setMenuBar(mb);

}//End of constructor

public void addBtns(){
this.add(new Button("One"));
this.add(new Button("Two"));
this.add(new Button("Three"));
this.add(new Button("Four"));
this.add(new Button("Five"));
this.add(new Button("Six"));
this.add(new Button("Seven"));
this.add(new Button("Eight"));
this.add(new Button("Nine"));
this.add(new Button("Ten"));
this.update(this.getGraphics());
}

ActionListener menuOpen = new ActionListener(){
public void actionPerformed(ActionEvent e){
addBtns();
}
};//end of anonymous class to handle menu item "open"

}//End
[2293 byte] By [danushka] at [2007-11-11 8:49:30]
# 1 Re: need Help with java GUI programming
the main problem i recognize is, that you operate directly on the frame,
eg, frame.add(component), frame.setLayout(...)
you shoud instead do the following:
1. get content pane of frame:
Container content = frame.getContentPane();
then you can add all components to the content pane, and also define the layout for the contentpane instead of the frame itself.
2. after modifying the contentpane, give it back to the frame:
frame.setContentPane(content);

this usually works fine.
and instead of using this.update(this.getGraphics());
try frame.repaint();
graviton at 2007-11-11 22:34:22 >
# 2 Re: need Help with java GUI programming
no mate, that theory wont work.

i replaced that frame.repaint() with frame.doLayout() which simply worked !

anyway thanks alot for your time on solving my matter.
danushka at 2007-11-11 22:35:16 >
# 3 Re: need Help with java GUI programming
1. get content pane of frame:
Container content = frame.getContentPane();
He's using AWT not Swing.
Phaelax at 2007-11-11 22:36:15 >