gpt4 book ai didi

java - 调整 JButton 的大小

转载 作者:行者123 更新时间:2023-12-02 04:09:27 24 4
gpt4 key购买 nike

我想知道如何调整代码中“alarmClockButton”的大小,我尝试过 setSize();和 setPreferredSize();然而它们都不起作用。我为此使用 GridBagLayout。有什么想法吗?

 public class MainMenu {

// JFrame = the actual menu / frame.
private JFrame frame;
// JLabel = provides text instructions or information on a GUI —
// display a single line of read-only text, an image or both text and an image.
private JLabel background, logo;
// JButton = button.
private JButton alarmClockButton;

// Constructor to create menu
public MainMenu() {
frame = new JFrame("Alarm Clock");
alarmClockButton = new JButton("Timer");
alarmClockButton.setPreferredSize(new Dimension(1000, 1000));
// Add an event to clicking the button.
alarmClockButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// TODO: CHANGE TO SOMETHING NICER
JOptionPane.showMessageDialog(null, "This feature hasn't been implemented yet.", "We're sorry!",
JOptionPane.ERROR_MESSAGE);
}
});
// Creating the background
try {
background = new JLabel(new ImageIcon(ImageIO.read(getClass()
.getResourceAsStream("/me/devy/alarm/clock/resources/background.jpg"))));
logo = new JLabel(new ImageIcon(ImageIO.read(getClass()
.getResourceAsStream("/me/devy/alarm/clock/resources/logo.png"))));
} catch (IOException e) {
e.printStackTrace();
}
background.setLayout(new GridBagLayout());
frame.setContentPane(background);
GridBagConstraints gbc = new GridBagConstraints();
// Inset = spacing between each component
gbc.insets = new Insets(15,15, 15, 15);
// Positioning
gbc.gridx = 0;
gbc.gridy = 0;
frame.add(logo, gbc);
// Positioning
// Keep x the same = aligned. On same x-coordinate (think math!)
gbc.gridx = 0;
// Y = 2 down
gbc.gridy = 1;
frame.add(alarmClockButton, gbc);
frame.setVisible(true);
frame.setSize(550, 200);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
alarmClockButton.setForeground(Color.RED);
}

}

谢谢!

最佳答案

您可以通过 GridBagConstraints 影响按钮的大小,例如...

使用ipadxipady,它们添加到组件preferredSize

gbc.ipadx = 100;
gbc.ipady = 100;

产生类似...的东西

enter image description here

您还可以使用...

gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;

这会改变组件将占用的空间量以及组件在给定单元格内的填充方式...

Clock

注意:

由于您使用 JLabel 作为背景组件,因此您将受到标签的首选尺寸的限制,该尺寸是通过 icon 计算得出的仅 text 属性,它不会使用布局管理器来计算这些结果。

关于java - 调整 JButton 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33929525/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com