import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
public class Test5 {
public static void main(String[] args) {
new ImageFrame();
}
}
class ImageFrame extends JFrame implements ActionListener {
private JPanel topPanel = null;
private JPanel centerPanel = null;
private JButton selectButton = null;
private BorderLayout bl = null;
ImageFrame() {
super("Test");
setSkin();
try {
this.setIconImage(new ImageIcon(this.getClass().getResource("/images/titled.png")).getImage());
} catch (NullPointerException e ) {
System.out.print("文件不存在");
}
this.setBounds(450, 300, 500, 400);
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
this.add(createTop(),BorderLayout.NORTH);
this.setVisible(true);
}
private JPanel createTop() {
topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
selectButton = new JButton("select a pic");
selectButton.addActionListener(this);
topPanel.add(selectButton);
return topPanel;
}
private JPanel createCenter(ImageIcon imgIcon) {
centerPanel = new JPanel();
JLabel imgLabel = new JLabel();
imgLabel.setIcon(imgIcon);
bl = new BorderLayout();
centerPanel.setLayout(bl);
centerPanel.setBorder(BorderFactory.createLoweredBevelBorder());
centerPanel.add(imgLabel,BorderLayout.CENTER);
return centerPanel;
}
@Override
public void actionPerformed(ActionEvent e) {
Object obj = e.getSource();
if(obj == selectButton) {
JFileChooser chooser = new JFileChooser("F:\\Desktop\\External\\图片");
int choice = chooser.showOpenDialog(this);
if(choice == JFileChooser.APPROVE_OPTION) {
ImageIcon imgIcon = new ImageIcon(chooser.getSelectedFile().getPath());
createCenter(imgIcon);
this.add(centerPanel,BorderLayout.CENTER);
this.setVisible(true); }
}
}
private void setSkin() {
try {
UIManager.setLookAndFeel("org.fife.plaf.Office2003.Office2003LookAndFeel");
} catch (Exception e) {
System.err.println("皮肤设置有错误!");
e.printStackTrace();
return;
}
}
}
手动选择图片加载到centerPanel中,效果如图所示:
[img=http://b214.photo.store.qq.com/psb?/V14Iz91703rhTz/wEyWBbxdiTLY*rwI*itZzuxPR7EH8j4GCdJ7hxcOgk4!/b/YW41o3*ZnAAAYu01o39HmwAA][/img]
求教:如何解决图片居中的问题
谢谢!
2 个解决方案
#1
用setHorizontalAlignment方法
eg:
jLabel.setHorizontalAlignment(JLabel.CENTER);
eg:
jLabel.setHorizontalAlignment(JLabel.CENTER);
#2
谢谢~~解决了。
我看了下API文档,看得不是十分明白,能稍稍给点解释吗?
#1
用setHorizontalAlignment方法
eg:
jLabel.setHorizontalAlignment(JLabel.CENTER);
eg:
jLabel.setHorizontalAlignment(JLabel.CENTER);
#2
谢谢~~解决了。
我看了下API文档,看得不是十分明白,能稍稍给点解释吗?