【发布时间】:2017-05-06 19:53:48
【问题描述】:
我最近开始学习 Java 课程来熟悉编程。很抱歉,如果这似乎是一个愚蠢的问题。我要做的是在单击按钮时调整窗口大小。
代码说的比文字多:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GrowShrink extends JFrame implements ActionListener {
public GrowShrink(String title) throws HeadlessException {
super(title);
setLayout(new GridBagLayout());
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
JButton buttonGrow = new JButton("Grow");
JButton buttonShrink = new JButton("Shrink");
buttonGrow.addActionListener(this);
buttonShrink.addActionListener(this);
add(buttonGrow);
add(buttonShrink);
pack();
setSize(300, 300);
setLocationRelativeTo(null);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Grow")) {
getContentPane().setSize(600, 600);
getContentPane().doLayout();
// getContentPane().repaint();
} else if (e.getActionCommand().equals("Shrink")) {
getContentPane().setSize(200, 200);
// getContentPane().revalidate();
repaint();
}
}
public static void main(String[] args) {
GrowShrink growShrink = new GrowShrink("Grow and Shrink the frame");
}
}
当我跟踪 IntelliJ 的调试器时,我可以清楚地看到,在单击按钮 Grow 后检查 hight 和 width 时,大小已变为 600x600。但是,这似乎对窗口没有任何作用。
我在这里遗漏了什么吗?我试过repaint()、doLayout()和revalidate(),但没有成功。
【问题讨论】:
-
在
if和else块内,你应该调用GrowShrink.this.setSize(...);GrowShrink.this.repaint();
标签: java swing intellij-idea jframe