The method add(...) in java.awt.Container made me in confuse

B

Bruce .J Sam

Here is my two java code file:
/* ********************************************************** */
//MyContainer.java
package sam.gui;

import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JApplet;
import javax.swing.JFrame;

public class MyContainer extends JApplet {
private MyButton[] myButton = new MyButton[2];
private static int counter = 0;
public MyContainer() {
myButton[0] = new MyButton(5, 5, 200, 30);
myButton[1] = new MyButton(5, 40, 200, 30);
for (int i = 0; i < myButton.length; i++) {
add(myButton);
}
}
public void paint(Graphics g) {
for (int i = 0; i < myButton.length; i++) {
System.out.println("MyButton : " + (i+1));
myButton.draw(g);
}
}

public static void main(String[] args) {
MyContainer container = new MyContainer();
JFrame f = new JFrame();
f.getContentPane().add(container);
f.pack();
f.setSize(new Dimension(300, 200));
f.show();
}
}
/* ********************************************************** */
//MyButton.java
package sam.gui;

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;

public class MyButton extends Component {
private Color m_rectColor = new Color(128, 73, 0);

public MyButton(int x, int y, int width, int height) {
setBounds(x, y, width, height);
}

public void draw(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g.setColor(m_rectColor);
g.fillRect(0, 0,
getBounds().width, getBounds().height);
System.out.println("x = " + getBounds().x);
System.out.println("y = " + getBounds().y);
System.out.println("width = " + getBounds().width);
System.out.println("height = " + getBounds().height);
}
}
/* ************************************************************ */
I thinked the runned result should be below:
MyButton : 1
x = 5
y = 5
width = 200
height = 30
MyButton : 2
x = 5
y = 40
width = 200
height = 30
But in fact, its result is here:
MyButton : 1
x = 5
y = 5
width = 200
height = 30
MyButton : 2
x = 0
y = 0
width = 292
height = 173
I don't know why the result would like this? I have used add(...)
method to add two component MyButton to the container MyContainer, But
the bounds of the second component is not I want.
So this problem made me go into confuse.
 
T

Tommi Johnsson

You have forgot to set layout before adding components in it.

.....
getContentPane ().setLayout (null);
for (int i = 0; i < myButton.length; i++) {
getContentPane().add (myButton);
}
.....


- jt
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,736
Latest member
zacharyharris

Latest Threads

Top