我有一个窗口(JFrame
),其中包含特殊类型的JButton
(我自己的扩展JButton
的按钮类)。当按钮大小发生变化时,该窗口会自行调整大小(例如,当我单击按钮时,它的字体大小会增加,JButton 的整个大小也会增加)。
我不想让 JFrame
适合按钮,但让我决定窗口应该有多大,所以 pack()
不是解决方案。
我正在考虑一种组件监听器,它可以根据按钮大小的变化调整窗口大小,但我找不到任何东西。
代码示例(工作中,单击按钮):
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JOptionPane;
public class ResizingButton extends JButton {
public ResizingButton(String txt) {
super();
setText(txt);
addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
int newFontSize = getFont().getSize() + 1;
setFont(new Font(Font.SANS_SERIF, Font.PLAIN, newFontSize));
FontMetrics metrics = getFontMetrics(getFont());
int width = metrics.stringWidth(getText());
int height = metrics.getHeight();
Dimension newDimension = new Dimension(width + 40, height + 10);
setPreferredSize(newDimension);
setBounds(new Rectangle(getLocation(), getPreferredSize()));
}
});
}
}
<小时/>
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
@SuppressWarnings("serial")
public class Zadanie2 extends JFrame {
JButton jb1, jb2;
public Zadanie2() {
createGUI();
}
private void createGUI() {
setSize(200, 80);
setLayout(new FlowLayout());
add(new ResizingButton("tekst"));
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Zadanie2();
}
}
最佳答案
That window suppose to resize itself when the button size is changing(in example when I click on the button its font size increases and the whole size of JButton too).
覆盖自定义按钮的 getPreferredSize()。
I do not want make JFrame fit the buttons, but let me decide how big the window should be, so pack() is no solution.
现在,当您调用 pack() 时,框架将根据按钮的新首选大小进行调整。
I was thinking about a kind of component listner which would resize window on button size change but I could not find anything.
ComponentListener
有一个 componentResized()
事件。因此,您可以将监听器添加到按钮。仅当您的自动调整大小代码与仅使用 pack() 不同时,您才会使用此方法。
关于java - 向 JButton 添加 onResize 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16739456/