gpt4 book ai didi

java - 如何使用 Java 中的 JButton 操作调整 JWindow 的宽度和高度?

转载 作者:行者123 更新时间:2023-11-30 06:32:40 24 4
gpt4 key购买 nike

如何通过 JButton 操作调整 JWindow 的高度(我尝试了 setSize 和 repaint 但它不起作用)?

public class Gui extends JWindow implements KeyListener
{
public static Gui mystatic;
private static JPanel panelBgImg;
private final Dimension screen;
public static int w = 0;
public static int h = 0;

public void paintComponent(Graphics g)
{
}

public Dimension getPreferredSize()
{
return new Dimension(100, h);
}

public Gui()
{
....

/* Button 1 */
JButton jb2 = new JButton("")
{
public Dimension getPreferredSize()
{
return new Dimension(50,50);
}
};
jb2.setOpaque(false);
jb2.setContentAreaFilled(false);
jb2.setBorderPainted(false);

jb2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
h = 100;
/* HERE i am trying to resize the JWindow itself but not working
return new Dimension(100, h); */
mystatic.setSize(screen.width, 100);
mystatic.repaint();
}
});

...

}

最佳答案

例如

请不要在 EDT 期间使用 Thread.sleep(int),如本代码示例所示,它用于关闭当前 JVM 实例,否则该实例永远不会从 PC 的 RAM 中消失

import java.util.logging.*;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.event.*;

public class SSCCE {

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
createAndShowGUI();
}
});
}

private static void createAndShowGUI() {
final JWindow window = new JWindow();
final JPanel windowContents = new JPanel();
JLabel label = new JLabel("A window that is pushed into view..........");
windowContents.add(label);
window.add(windowContents);
window.pack();
window.setLocationRelativeTo(null);
final int desiredWidth = window.getWidth();
window.getContentPane().setLayout(null);
window.setSize(0, window.getHeight());
window.setVisible(true);
Timer timer = new Timer(15, new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
int newWidth = Math.min(window.getWidth() + 1, desiredWidth);
window.setSize(newWidth, window.getHeight());
windowContents.setLocation(newWidth - desiredWidth, 0);
if (newWidth >= desiredWidth) {
((Timer) e.getSource()).stop();
//restore original layout
window.getContentPane().setLayout(new BorderLayout());
window.validate();
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Logger.getLogger(SSCCE.class.getName()).log(Level.SEVERE, null, ex);
}
System.exit(0);
}
}
});
timer.start();
}

private SSCCE() {
}
}

关于java - 如何使用 Java 中的 JButton 操作调整 JWindow 的宽度和高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8653678/

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