Java 如何增加/减少点击事件窗口的大小?

Java 如何增加/减少点击事件窗口的大小?,java,swing,Java,Swing,我正在开发一个简单的swing应用程序,其中有一个带有三个按钮的主窗口。当我点击第一个按钮时,它会打开(200200)尺寸的新窗口。当我点击第二个按钮时,新打开的窗口的高度应该增加,当我点击第三个按钮时,高度应该减少。你能帮我写代码吗 提前感谢。您可以在新打开的要调整大小的窗口上执行以下操作: JFrame fr=getNewlyOpenendWindowReference(); // get a reference to the JFrame fr.setSize(fr.getSize().g

我正在开发一个简单的swing应用程序,其中有一个带有三个按钮的主窗口。当我点击第一个按钮时,它会打开(200200)尺寸的新窗口。当我点击第二个按钮时,新打开的窗口的高度应该增加,当我点击第三个按钮时,高度应该减少。你能帮我写代码吗


提前感谢。

您可以在新打开的要调整大小的窗口上执行以下操作:

JFrame fr=getNewlyOpenendWindowReference(); // get a reference to the JFrame
fr.setSize(fr.getSize().getWidth() + 10,fr.getSize().getHeight() + 10);
fr.repaint();

这将使JFrame的长度和宽度每调用增加10像素。

创建一个控制器类来处理操作事件。

定义一个
框架面板扩展JPanel
,并向其中添加按钮。使用动作事件值在类中设置常量,并在按钮上设置它们。然后,您可以实例化这个
FrameController
,并使用
JButton.addActionListener()
将其添加为这些按钮的侦听器。或者,您可以在
FrameController
类的构造函数中执行此操作

public class FrameController implements ActionListener { private JFrame openedFrame; public static final int MINIMUM_HEIGHT = 200; public FrameController(FramePanel panel) { this.panel.getOpenFrameButton().addActionListener(this); this.panel.getIncreaseHeightButton().addActionListener(this); this.panel.getDecreaseHeightButton().addActionListener(this); } @Override public void actionPerformed(ActionEvent e) { String action = e.getActionCommand(); if (action.equals(FramePanel.ACTION_OPEN_FRAME)) { this.openedFrame = new JFrame(); // set it up how you want it } else if (action.equals(FramePanel.ACTION_INCREASE_HEIGHT)) { this.openedFrame.setSize(this.openedFrame.getWidth(), this.openedFrame.getHeight() + 10); } else if (action.equals(FramePanel.ACTION_INCREASE_HEIGHT)) { int newHeight = this.openedFrame.getHeight() - 10; if (newHeight < FrameController.MINIMUM_HEIGHT) newHeight = FrameController.MINIMUM_HEIGHT; this.openedFrame.setSize(this.openedFrame.getWidth(), newHeight); } } } 公共类FrameController实现ActionListener{ 私有JFrame-openedFrame; 公共静态最终内部最小高度=200; 公共框架控制器(框架面板){ this.panel.getOpenFrameButton().addActionListener(this); this.panel.getIncreaseHeightButton().addActionListener(this); this.panel.getDecreaseHeightButton().addActionListener(this); } @凌驾 已执行的公共无效操作(操作事件e){ String action=e.getActionCommand(); if(action.equals(FramePanel.action\u OPEN\u FRAME)){ this.openedFrame=newjframe(); //按你想要的方式设置 }else if(action.equals(FramePanel.action_增加_高度)){ this.openedFrame.setSize(this.openedFrame.getWidth()、this.openedFrame.getHeight()+10); }else if(action.equals(FramePanel.action_增加_高度)){ int newHeight=this.openedFrame.getHeight()-10; if(新高度如果您希望增长不总是在帧的右侧和底部,请使用
setBounds
。您好,这听起来不错,但我遇到了错误。“使用动作事件值在类中设置常量,并在按钮上设置它们”。我不了解此部分。请告诉我详细信息。声明
公共静态最终字符串动作\u打开\u帧=FramePanel类中的“OpenFrame”
。然后,在按钮上调用
this.openFrameButton.setActionCommand(FramePanel.ACTION\u OPEN\u FRAME);
这将确保在按下按钮时将命令发送给侦听器,以便侦听器知道按下了哪个按钮。