简体   繁体   English

组件未按预期添加到框架中

[英]component not getting added into the frame as expected

i was studying event handling and performed the following: 我正在研究事件处理并执行以下操作:

  • Created a JFrame without any component in it 创建了一个没有任何组件的JFrame

  • i overridden the keyPressed() method in such a way that whenever a key is pressed from the keyboard,A button should appear in the frame(by using add() and then calling repaint()). 我重写了keyPressed()方法,每当从键盘按下一个键时,一个按钮应该出现在框架中(通过使用add()然后调用repaint())。 Now the thing i want to ask is that at the time of key press from the keyboard,nothing was being added to the frame,however after pressing the key when i resized the frame WINDOW,the button came out from nowhere in the frame.... what's happening? 现在我要问的是,在键盘按键的时候,没有任何东西被添加到框架中,但是当我调整框架窗口大小时按下按键后,按钮在框架中无处出现。 ..发生了什么事?

      import java.awt.*; import java.awt.event.*; import javax.swing.*; class MyFrame extends JFrame implements KeyListener { private JButton bt=new JButton(); MyFrame() { addKeyListener(this); } public void keyPressed(KeyEvent ke) { this.add(bt); repaint(); } public void keyTyped(KeyEvent ke) { } public void keyReleased(KeyEvent ke) { } } public class MyClass /*class containing the main method*/ { public static void main(String args[]) { MyFrame frm=new MyFrame(); frm.setVisible(true); frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } 

You need to call revalidate after adding a component to the JFrame 将组件添加到JFrame后,需要调用revalidate

this.add(bt);
revalidate();
repaint();

revalidate revalidates the component hierarchy to account for any new components that may have been added. revalidate验证组件层次结构以考虑可能已添加的任何新组件。


KeyListeners don't work well for Swing applications as KeyEvents require focus to work. KeyListeners不适用于Swing应用程序,因为KeyEvents需要焦点才能工作。 This is why in Swing it is better to use Key Bindings which allow you to map an Action to a KeyStroke even when a component doesn't have focus. 这就是为什么在Swing中最好使用Key Bindings ,它允许你将Action映射到KeyStroke,即使组件没有焦点也是如此。

,nothing was being added to the frame, ,没有任何东西被添加到框架,

The component was added to the frame. 该组件被添加到框架中。 The problem is it has a size of (0, 0) so there is nothing to paint 问题是它的大小为(0,0),所以没有什么可以画的

however after pressing the key when i resized the frame WINDOW,the button came out from nowwhere in the frame 然而,当我调整框架WINDOW的大小按下键后,按钮从框架中的任何位置出来

The layout manager gets invoked and the component is given a size and location based on the rules of the layout manager. 调用布局管理器,并根据布局管理器的规则为组件指定大小和位置。 So now you see the component. 所以现在你看到了组件。

When you add a component to a visible GUI the code is: 将组件添加到可见GUI时,代码为:

panel.add(...);
panel.revalidate();
panel.repaint();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM