java - setSize() 不起作用?

标签 java swing user-interface button

我有一个程序需要两个按钮,一个是常规按钮,另一个是图片会根据鼠标滚动而改变。目前,由于图片很大,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
    }
}





}

最佳答案

正如一些用户提到的,您可以覆盖 getPreferredSize()getMinimum/MaximumSize()。或者您可以只为首选、最大和最小尺寸调用 setter 方法。如果您设置首选大小和最大大小...

custom.setPreferredSize(new Dimension(50, 50));
custom.setMaximumSize(new Dimension(50, 50));

然后你通常会得到那个尺寸。

关于java - setSize() 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32084346/

相关文章:

java - Swing、Eclipse RCP 还是该走哪条路?

c - 将类似 bash 的小部件插入 gtk

java - JPanel 之间的转换?

java.awt.Graphics ->graphics.drawImage 太慢,出了什么问题?

java - Android 布局的动态内容

java - Servlet + 注入(inject) - 多线程问题

java - Jframe 内的输入法?

android - 如何对齐屏幕底部的 View ?

html - 有没有办法将图像中的 GUI 转换为 html?

java - JUnit 中如何处理超时?