遇到个问题,就是当点击一个按钮时,促发监听器,在一个JPanel中添加一个JTextArea,但为啥文本区不能立马显示呢?而是要改变下窗口大小,或是被其他窗口覆盖后重新显示时才显示文本区?请问其中的原因是什么呢?并给出解决方法,即点击按钮时,就立马显示文本区。谢谢!例如下面程序代码:(其中原理请尽可能说明白)
//filename:TestDisplay.java
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class TestDisplay extends JFrame implements ActionListener{
JTextArea ta = new JTextArea("Welcome to Java!");
JButton bt = new JButton("clicked here");
public static void main(String[] args) {
TestDisplay frame = new TestDisplay();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100,100,600,600);
frame.setVisible(true);
}
TestDisplay() {
bt.addActionListener(this);
this.getContentPane().add(bt,BorderLayout.NORTH);
}
public void actionPerformed(ActionEvent e) {
this.add(ta,BorderLayout.CENTER);
//this.repaint();//在此重画也不行;
}
}
LZ调用容器的另外一个方法就好了updateUI();
不太喜欢LZ那种风格代码~ :lol:
[code="java"]
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class fran extends JFrame
{
private JPanel me = null;
public static void main(String[] args)
{
new fran();
}
public fran()
{
initial();
}
private void initial()
{
this.setVisible(true);
this.add(getContent());
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.pack();
}
private JPanel getContent()
{
if(me == null)
{
me = new JPanel();
me.add(getBut());
}
return me;
}
private JButton getBut()
{
JButton but = new JButton("click");
but.addActionListener(new Butli());
return but;
}
class Butli implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
me.add(new JTextField("some word"));
me.updateUI();
}
}
}
[/code]