我刚刚开始理解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
}
}
答案 0 :(得分:1)
将组件添加到可见GUI时,代码应为:
panel.add(...);
panel.revalidate();
panel.repaint();
revalidate()确保调用布局管理器,以便为新组件设置大小/位置。 repaint()确保在面板上重新绘制所有组件。