how to make a right side JPanel display always

时间:2015-07-21 13:08:02

标签: java swing jpanel

I have two Jpanels in a line, first JPanel used for showing a number of buttons and second showing left and right buttons. I want to show the left,right buttons always(when change the screen size)

    public class TestJPanel {
public static void main(String... args) {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    for (int i = 0; i < 10; i++) {
        panel.add(new JButton("Hello-" + i));
    }
    JPanel leftrightPanel=new JPanel();
    leftrightPanel.add(new Button("LEFT"));
    leftrightPanel.add(new Button("RIGHT"));
    JPanel contentPane = new JPanel();
    contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.LINE_AXIS));
    contentPane.add("West",panel);
    contentPane.add("East",leftrightPanel);
    frame.setContentPane(contentPane);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.setSize(400,280);
    frame.setVisible(true);
}}

2 个答案:

答案 0 :(得分:1)

根据JavaDoc,您add使用的String, Component方法已过时。无论如何,String参数仅用于组件的名称,与定位无关。就像现在一样,组件的放置方式与您规定的完全相同:沿水平轴。如果您希望更改它,可以执行各种操作,例如修改内部JPanel的布局,使用BorderLayout作为内容面板,以及将内部面板添加到适当的位置索引等。

当您说您希望最右侧的面板和按钮始终可见时,您需要指定左侧面板及其按钮的行为。他们应该占用多条线路吗?它们应该隐藏吗?他们应该缩小吗?如果你澄清你想要发生什么,我可以给你一个更具体的答案,但就目前而言,答案很简单就是你正在按照你所说的去做。

另外请注意,您使用JButtonsButtons不一致。使用其中一个,最好是JButtons,因为您使用的每个其他组件都是Swing。

答案 1 :(得分:0)

也许你想要这样的东西:

import (
    "github.com/gorilla/context"
)

...

func Middleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Middleware operations
        // Parse body/get token.
        context.Set(r, "token", token)

        next.ServeHTTP(w, r)
    })
}

...

func Handler() http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        token := context.Get(r, "token")
    })
}

这会将两个面板分隔到屏幕的左侧和右侧,中间有空格。中间的空间会随着框架的大小调整而改变。

JPanel contentPane = new JPanel();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.LINE_AXIS));
contentPane.add(panel);
contentPane.add(Box.createHorizontalGlue());
contentPane.add(leftrightPanel);

永远不要使用那样的硬编码魔术字符串。 API将为您提供一个供您使用的字段。当您正确使用BorderLayout时,您将使用:

contentPane.add("West",panel);

阅读How to Use BorderLayout上的Swing教程,了解有关使用约束和正确的add(...)方法的更多信息和工作示例。

相关问题