java swing jframe 居中_java – 在JFrame中居中图像?

考虑使用一些布局来帮助你.想到的那些包括BorderLayout和BorderLayout.CENTER位置的图标.您可以使用BoxLayout在一侧堆叠东西,使用JPanel,使用JPanel添加到主BorderLayout.

例如.,

import java.awt.BorderLayout;

import java.awt.Font;

import java.awt.event.ActionEvent;

import java.awt.image.BufferedImage;

import java.io.IOException;

import java.net.MalformedURLException;

import java.net.URL;

import javax.imageio.ImageIO;

import javax.swing.*;

@SuppressWarnings("serial")

public class About extends JDialog {

public static final String IMAGE_PATH = "http://upload.wikimedia.org/wikipedia/"

+ "commons/thumb/3/39/European_Common_Frog_Rana_temporaria.jpg/"

+ "800px-European_Common_Frog_Rana_temporaria.jpg";

public About(JFrame frame) {

super(frame, "About [PROGRAM]", true);

ImageIcon myIcon = null;

try {

URL imgUrl = new URL(IMAGE_PATH);

BufferedImage img = ImageIO.read(imgUrl);

myIcon = new ImageIcon(img);

} catch (MalformedURLException e) {

e.printStackTrace();

System.exit(-1);

} catch (IOException e) {

e.printStackTrace();

System.exit(-1);

}

JPanel main = new JPanel(new BorderLayout());

main.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

JLabel centerLabel = new JLabel(myIcon);

JLabel name = new JLabel("[PROGRAM]");

JLabel expandedName = new JLabel("[PROGRAM DESCRIPTION]");

JLabel copyright = new JLabel("[COPYRIGHT JUNK]");

JLabel credits = new JLabel("[CREDITS]");

name.setFont(new Font(name.getFont().getFamily(), Font.BOLD, 18));

copyright.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));

int eb = 20;

centerLabel.setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));

JPanel leftPanel = new JPanel();

leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.PAGE_AXIS));

leftPanel.add(name);

leftPanel.add(Box.createVerticalGlue());

leftPanel.add(expandedName);

leftPanel.add(copyright);

leftPanel.add(credits);

leftPanel.add(Box.createVerticalGlue());

main.add(centerLabel, BorderLayout.CENTER);

main.add(leftPanel, BorderLayout.LINE_START);

add(main);

pack();

}

public static void main(String[] args) {

final JFrame frame = new JFrame("GUI");

JPanel panel = new JPanel();

panel.add(new JButton(new AbstractAction("About") {

@Override

public void actionPerformed(ActionEvent e) {

About about = new About(frame);

about.setLocationRelativeTo(frame);

about.setVisible(true);

}

}));

frame.add(panel);

frame.pack();

frame.setLocationRelativeTo(null);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

}

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值