setSize()不起作用? [英] setSize() not working?
问题描述
我有一个程序,该程序带有两个按钮,一个是常规按钮,另一个是具有随鼠标悬停而变化的图片的按钮.当前,由于图片很大,因此JButton自定义也很大,是否可以更改自定义大小并保持图像(并翻转图像)成比例?我已经尝试过setSize,它什么也没做.任何反馈将不胜感激!
I have a program which takes two buttons, one that is regular and one that has a picture that changes depending on mouse roll over. Currently, since the picture is large, JButton custom is very large as well, can I change the size of custom and keep the image (and roll over image) proportionate? I have tried setSize, and it does't do anything. Any feedback would be appreciated!
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
}
}
}
推荐答案
正如某些用户所提到的,您可以覆盖 getPreferredSize()
和 getMinimum/MaximumSize()
.或者,您可以只调用setter方法以获取首选大小,最大大小和最小大小.如果您设置了首选尺寸和最大尺寸...
As some users have mentioned, you can override getPreferredSize()
and getMinimum/MaximumSize()
. Or you could just call the setter methods for the preferred, maximum, and minimum sizes. If you set the preferred size and the maximum size...
custom.setPreferredSize(new Dimension(50, 50));
custom.setMaximumSize(new Dimension(50, 50));
然后您通常会得到该尺寸.
then you will usually get that size.
这篇关于setSize()不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!