【发布时间】:2015-11-12 02:16:12
【问题描述】:
我有一个程序,它有两个按钮,一个是常规按钮,一个是根据鼠标滚动而变化的图片。目前,由于图片很大,JButton 自定义也很大,我可以更改自定义的大小并保持图像(和翻转图像)成比例吗?我试过setSize,它什么也没做。任何反馈将不胜感激!
custom.setSize(50, 50);
这是我所有的代码:
主类:
package Buttons;
import javax.swing.JFrame;
public class Main_buttons{
public static void main(String[] args) {
ButtonClass press = new ButtonClass();
press.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
press.setSize(500,500);
press.setVisible(true);
}
}
其他类:
package Buttons;
import java.awt.FlowLayout; //layout proper
import java.awt.event.ActionListener; //Waits for users action
import java.awt.event.ActionEvent; //Users action
import javax.swing.JFrame; //Window
import javax.swing.JButton; //BUTTON!!!
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane; //Standard dialogue box
public class ButtonClass extends JFrame {
private JButton regular;
private JButton custom;
public ButtonClass() { // Constructor
super("The title"); // Title
setLayout(new FlowLayout()); // Default layout
regular = new JButton("Regular Button");
add(regular);
Icon b = new ImageIcon(getClass().getResource("img.png"));
Icon x = new ImageIcon(getClass().getResource("swag.png"));
custom = new JButton("Custom", b);
custom.setRolloverIcon(x); //When you roll over the button that says custom the image will change from b to x
custom.setSize(50, 50);
add(custom);
Handlerclass handler = new Handlerclass();
regular.addActionListener(handler);
custom.addActionListener(handler);
}
public class Handlerclass implements ActionListener { // This class is inside the other class
public void actionPerformed(ActionEvent eventvar) { // This will happen
// when button is
// clicked
JOptionPane.showMessageDialog(null, String.format("%s", eventvar.getActionCommand()));//Opens a new window with the name of the button
}
}
}
【问题讨论】:
-
是的,我已经看过那个帖子了,但是由于某种原因,setPreferredSize() 也不起作用...?知道为什么吗?
-
@Billybobsteven “知道为什么吗?” - 不是没有一个代码示例来证明它不起作用......另外,你真的想要一个 40, 000 像素的按钮高的?不知道我知道有多少屏幕变得那么大......
-
每次更改像素尺寸时,此按钮的大小都会保持不变。那 40, 000 像素的高度是我不断改变的大小。将其从 50、50 更改为 100、50 更改为 90、75 等后,按钮和宽度都没有改变。
-
那是因为
FlowLayout使用组件的preferredSize来决定组件的布局方式,覆盖您传递给setSize的任何内容
标签: java swing user-interface button