开发者

JPanel layout in applet

I have a JPanel that is not part of a JFrame. For various reasons I have to call the panel's paint method through my own "update" method.

This is my code:

public void onLoad ()
{
    panel = new JPanel ();
    panel.setBounds (0,0,Main.WIDTH,Main.HEIGHT);

    panel.setLayout (new BoxLayout (panel, BoxLayout.Y_AXIS));

    addButton ("button1", panel);
    addButton ("button2", panel);
}

private void addButton (St开发者_运维百科ring text, Container container)
{
    JButton button = new JButton (text);
    button.setPreferredSize (new Dimension (100,20));
    button.setAlignmentX (Component.CENTER_ALIGNMENT);
    container.add (button);
}

public void onRender (Graphics2D g)
{
    panel.paint (g);
}

This only paints the panel's background color. If I add button.setBounds(...) in the addButton method then it does paint the buttons but not affected by the BoxLayout.

So I want the buttons to be affected by the BoxLayout obviously. I'm not that savvy on how exactly Swing works so I'm not sure how to do this. JFrame has a pack() method which I think is what I need but some equivalent for JPanels since JPanels doesn't have that method.


I don't know what you're looking for, but for me this works well.

import java.awt.Component;
import java.awt.Dimension;
import javax.swing.BoxLayout;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class TestApplet extends JApplet{
    public static void main(String[] args){
        new TestApplet();
    }
    public TestApplet(){
        this.setSize(400,400);
        this.add(getCustPanel());
        this.setVisible(true);
    }
    private JPanel getCustPanel() {
        JPanel panel = new JPanel ();
        panel.setLayout (new BoxLayout(panel, BoxLayout.Y_AXIS));
        addButton ("button1", panel);
        addButton ("button2", panel);
        return panel;
    }
    private void addButton (String text, JPanel container)
    {
        JButton button = new JButton (text);
        button.setPreferredSize (new Dimension(100,20));
        button.setAlignmentX (Component.CENTER_ALIGNMENT);
        container.add (button);
    }

}

JPanel layout in applet

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜