java 小程序中的 JPanel 布局

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4213759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 05:21:04  来源:igfitidea点击:

JPanel layout in applet

javaswing

提问by hesselbom

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.

我有一个不属于 JFrame 的 JPanel。由于各种原因,我必须通过我自己的“更新”方法调用面板的绘制方法。

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 (String 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.

这只会绘制面板的背景颜色。如果我在 addButton 方法中添加 button.setBounds(...) 那么它会绘制按钮但不受 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.

所以我希望按钮明显受到 BoxLayout 的影响。我对 Swing 的工作原理不太了解,所以我不确定如何做到这一点。JFrame 有一个 pack() 方法,我认为这是我需要的,但对于 JPanels 有一些等价物,因为 JPanels 没有那个方法。

回答by bragboy

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);
    }

}

alt text

替代文字