我刚刚开始了解Java Swing。我想快速编写一些代码来理解事件处理,并编写了以下代码。如您所见,事件处理工作正常,因为"内部鼠标单击方法!"消息已打印到控制台,但我无法"看到"添加到框架中的标签,在这种情况下,标签是我在文本框中键入的任何内容,我输入的字符串是不可见的,直到我通过拉动它的角来调整框架的大小!对于初学者来说,这有点奇怪。有人可以解释一下发生了什么吗?
这是代码:
package com.learning.java.gui;
import java.awt.FlowLayout;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.event.MouseInputListener;
public class FirstGUIFrame extends JFrame{
private static FirstGUIFrame firstgui=null;
FirstGUIFrame(){
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
setSize(600,400);
}
public static FirstGUIFrame getFrameObj(){
return firstgui;
}
public static void main(String ar[]){
firstgui = new FirstGUIFrame();
JLabel name = new JLabel("UserName:");
TextField textfield = new TextField("enter you name here", 15);
JButton jbutton = new JButton("Enter");
jbutton.addMouseListener(new buttonListener());
firstgui.add(name);
firstgui.add(textfield);
firstgui.getContentPane().add(jbutton);
}
}
class buttonListener implements MouseInputListener{
@Override
public void mouseClicked(MouseEvent e) {
FirstGUIFrame frame = FirstGUIFrame.getFrameObj();
System.out.println("inside mouseclicked method!");
frame.getContentPane().add(new JLabel("Clicked!!"));
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
}
将组件添加到可见 GUI 时,代码应为:
panel.add(...);
panel.revalidate();
panel.repaint();
revalidate() 确保调用布局管理器,以便为新组件设置大小/位置。repaint() 确保所有组件都重新绘制在面板上。