1
我剛開始理解Java Swing。我想快速編寫一些代碼來理解事件處理並編寫下面的代碼。正如你所看到的,事件處理工作正常,因爲「內部鼠標點擊的方法!」消息被打印到控制檯,但我無法'看到'添加到框架的標籤,這種情況下的標籤是我在文本框中輸入的任何內容,我輸入的字符串不可見,除非通過拉動它的角來調整框架大小!作爲初學者,這對我來說有點奇怪。有人可以解釋發生了什麼嗎?學習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
}
}