我刚刚开始了解 Java Swing。我想快速编写一些代码来理解事件处理并编写了以下代码。如您所见,事件处理可以作为“内部 mouseclicked 方法!” 消息被打印到控制台,但我无法“看到”添加到框架的标签,在这种情况下,标签是我在文本框中输入的任何内容,我输入的字符串不可见,直到我通过拉动框架的角来调整框架的大小!作为初学者,这对我来说有点奇怪。有人可以解释发生了什么吗?
这是代码:
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
}
}