gpt4 book ai didi

java - 使用按钮更改 Jframe 的高度

转载 作者:行者123 更新时间:2023-12-01 21:13:10 25 4
gpt4 key购买 nike

我想通过单击按钮来更改 jFrame 的高度。

但我不知道从哪里开始。我只有一个按钮,不知道代码。

*编辑:我知道可以改变 JFrame 的大小并将其位置移动到右上角的代码是这样的

    Dimension screenSize = new Dimension(Toolkit.getDefaultToolkit().getScreenSize());
setPreferredSize(new Dimension(311, 430));
Dimension windowSize = new Dimension(getPreferredSize());
int wdwLeft = 530 + screenSize.width / 2 - windowSize.width / 2;
int wdwTop = 0;
pack();
jButton2.setEnabled(false);
setLocation(wdwLeft, wdwTop);

但我不知道可以改变JFrame大小的具体代码

*EDIT2:这是我的public static void main(String args[])

public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
final VoucherChecker frame = new VoucherChecker();
frame.setVisible(true);
}
});
}

我不知道如何调用frame来使用frame.setSize

最佳答案

要在按下按钮时运行代码,请添加 ActionListener使用 .addActionListener() 方法添加到按钮。看看这里的代码,看看它是否适合您:(阅读评论以了解发生了什么)

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Main {

private JFrame frame;

public static void main(String[] args){

SwingUtilities.invokeLater(new Runnable(){

@Override
public void run() {
new Main(); //Create a Main object, wrapped by SwingUtilities.invokeLater to make it thread safe
}
});

}

public Main() { //Main's constructor

frame = new JFrame(); //Create JFrame
frame.setTitle("Test Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

init((JPanel)frame.getContentPane()); //'init' frame's JPanel
setFrameSizeAndPos(frame); //Set the frame's size

frame.setVisible(true);
}

private void setFrameSizeAndPos(JFrame frame) {

//Set JFrame size here! Eg:
frame.pack(); //Set the frame size, you could change this to set it in a different way.
frame.setLocationRelativeTo(null); //Place frame in the center of the screen
}

private void init(JPanel panel) {
//Setup your GUI here...
JButton button1 = new JButton("Click me!"); //Create button
button1.addActionListener(new ActionListener(){ //add an ActionListener to the button, passing in an Anonymous Class

@Override
public void actionPerformed(ActionEvent e) {
setFrameSizeAndPos(frame); //This will be called then the button is pressed
}
});

panel.add(button1);

}
}

关于java - 使用按钮更改 Jframe 的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40777551/

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