OK = new JButton(new ImageIcon("magic23_20.png"));
OK.setBorderPainted(false);
OK.setBounds(20,90, 80,160);//JButtont 图像只在下方显示,
不会居中显示,
怎么样才能居中显示呢?
OK.setBorderPainted(false);
OK.setBounds(20,90, 80,160);//JButtont 图像只在下方显示,
不会居中显示,
怎么样才能居中显示呢?
import java.awt.Dimension;import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;public class Test extends JFrame {
public Test() {
this.setTitle("1111");
this.setSize(300,400);
init();
this.setVisible(true);
} public void init() {
JPanel panel = new JPanel();
JButton button = new JButton(
new ImageIcon(
"D:\\Program Files\\SeamDev\\eclipse\\workspace2\\SwingTest\\src\\1.PNG"));
button.setPreferredSize(new Dimension(200,200));
panel.add(button);
this.add(panel); }
public static void main(String[] args) {
new Test();
}
}
很简单阿。
你随时可以自己设置啊:
OK.setHorizontalAlignment(SwingConstants.CENTER);
OK.setVerticalAlignment(SwingConstants.CENTER);
package util;import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;import javax.swing.ImageIcon;
import javax.swing.JButton;@SuppressWarnings("serial")
public class ImageButton extends JButton {
private Image normalImage;
private Image pressedImage; public ImageButton(Image normalImage) {
this(normalImage, null);
} public ImageButton(Image normalImage, Image pressedImage) {
this.normalImage = normalImage;
this.pressedImage = pressedImage;
setOpaque(false);
setContentAreaFilled(false);
} public static Image getImage(String path) {
Image img = new ImageIcon(path).getImage();
return img;
} public void setNormalImage(Image normalImage) {
this.normalImage = normalImage;
this.repaint();
} @Override
public Dimension getMaximumSize() {
return new Dimension(normalImage.getWidth(this), normalImage.getHeight(this));
} @Override
public Dimension getMinimumSize() {
return new Dimension(normalImage.getWidth(this), normalImage.getHeight(this));
} @Override
public Dimension getPreferredSize() {
return new Dimension(normalImage.getWidth(this), normalImage.getHeight(this));
} @Override
protected void paintComponent(Graphics g) {
// super.paintComponent(g);
int width = this.getWidth();
int height = this.getHeight(); Graphics2D g2d = (Graphics2D) g; g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if (getModel().isPressed()) {
g2d.drawImage(pressedImage, 0, 0, width, height, this);
} else {
g2d.drawImage(normalImage, 0, 0, width, height, this);
}
// super.paintComponent(g); // Let JButton draw the text on the button.
}
}