How can i add this button inside the canvas of Java?
How can i add the button ontop of this canvas? like floating... on top instead of开发者_JAVA技巧 having it in the grid using add(button);
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Myscreensaver extends Window
{
private static final Canvas canvas = new Canvas();
private Button button;
public Myscreensaver()
{
setLayout(new GridLayout(2,2));
canvas.setPreferredSize(new Dimension(200, 200));
add(canvas);
//add(button); no add the button in the canvas not in the grid, then it looks odd.
}
}
Why don't use use Swing instead of AWT. After all you are importing javax.swing.*. Then you would use a JWindow.
If you want the component to float in the center then you should be using a different layout manager. Maybe a GridBagLayout.
setLayout( new GridBagLayout() );
add(button, new GridBagConstraints());
MigLayout also has an option you could consider:
setLayout(new MigLayout("fill", "[grow,fill]"));
add(canvas);
add(button, "align 50% 50%");
This will float the button over the top of anything else added without absolute positioning. See their demo, Absolute Position, Glasspane Substitute
Same thought like the last poster. If you add the button after the canvas the button will be on the top of the canvas.You should document you're self about light and heavy weight components to because then you're will get fast results in this kind of problems. A simple explanation : http://www.blurtit.com/q132749.html
精彩评论