java居中,Java居中面板

For some reason i am having problems centering my panel vertically that is located inside another panel. I do exactly as the examples i studied but still no luck.

Down there is my code. Despite using setAlignmentY(0.5f) on my container panel, it still wont center when i resize the window.

Also the components inside container panel wont center either, despite setAligenmentX(0.5f).

I wonder if there is a solution for this, I pretty much tried everything out there but couldnt find a solution.

JLabel idLabel;

JLabel passLabel;

JTextField id;

JTextField pass;

JButton enter;

JPanel container;

public JournalLogin()

{

//setLayout(new FlowLayout());

//setPreferredSize(new Dimension(500, 500));

//setBorder(BorderFactory.createEmptyBorder(100, 100, 100, 100));

container = new JPanel();

container.setLayout(new MigLayout());

container.setAlignmentX(0.5f);

container.setAlignmentY(0.5f);

container.setPreferredSize(new Dimension(300, 300));

container.setBorder(BorderFactory.createTitledBorder("Login"));

add(container);

idLabel = new JLabel("ID:");

idLabel.setAlignmentX(0.5f);

container.add(idLabel);

id = new JTextField();

id.setText("id");

id.setAlignmentX(0.5f);

id.setPreferredSize(new Dimension(80, 20));

container.add(id, "wrap");

解决方案

setAlignmentX and Y are not the way to go about doing this. One way to center a component in a container is to have the container use GridBagLayout and to add the component without using any GridBagConstraints, a so-called default addition. There are other ways as well.

For example to alter Nick Rippe's example (1+ to him):

import java.awt.BorderLayout;

import java.awt.Dimension;

import java.awt.GridBagLayout;

import javax.swing.*;

public class UpdatePane2 extends JPanel {

private static final int PREF_W = 300;

private static final int PREF_H = 200;

public UpdatePane2() {

JPanel innerPanel = new JPanel();

innerPanel.setLayout(new BorderLayout());

innerPanel.add(new JLabel("Hi Mom", SwingConstants.CENTER),

BorderLayout.NORTH);

innerPanel.add(new JButton("Click Me"), BorderLayout.CENTER);

setLayout(new GridBagLayout());

add(innerPanel);

}

@Override

public Dimension getPreferredSize() {

return new Dimension(PREF_W, PREF_H);

}

private static void createAndShowGui() {

JFrame frame = new JFrame("UpdatePane2");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.getContentPane().add(new UpdatePane2());

frame.pack();

frame.setLocationRelativeTo(null);

frame.setVisible(true);

}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {

createAndShowGui();

}

});

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值