Sha*_*dan 1 java swing jframe jtextarea
我创建了一个框架,里面有一个面板,面板里面有一个textarea.现在我创建了一个构造函数,使框架可见一段时间后,它被设置为不可见.它可见的时间显示了一些消息.
当我在outputDisplay类的main方法中运行构造函数代码时,它会显示文本按钮
但是当我通过使用new outputDisplay(String ip,int time)在其他类中调用它时,只有框架出现但内部没有文本.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class OutputDisplay {
JFrame frame;
JPanel panel;
JTextArea area;
Font font;
OutputDisplay(String ip,int time) throws InterruptedException{
frame = new JFrame("Warning");
frame.setLocation(400, 220);
panel = new JPanel();
area = new JTextArea();
font = new Font("Aharoni", Font.BOLD, 16);
area.setFont(font);
area.setForeground(Color.RED);
area.setSize(200, 200);
int j=0;
String[] t = {ip};
for(int i=0;i<t.length;i++){
area.append(t[i]+"\n");
}//for
//area.setText(ip);
panel.add(area);
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.pack();
frame.setSize(600, 200);
frame.setVisible(true);
Thread.sleep(time);
j++;
if(j==1){
frame.setVisible(false);
}//if
frame.setResizable(false);
}//constructor
}//Class
Run Code Online (Sandbox Code Playgroud)
Thread.sleep(time);
不要这样做(你阻止了EDT).使用Swing Timer
Timer timer = new Timer(time, new ActionListener(){
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
}
});
timer.start();
Run Code Online (Sandbox Code Playgroud)
看到
"当我在outputDisplay类的main方法中运行构造函数代码时,它会显示文本按钮"
你可能正在做
public static void main (String[] args) {
new OutputDisplay();
}
Run Code Online (Sandbox Code Playgroud)
这不是在Event Dispatch Thread上运行的,(但是错误的).如果你在EDT上运行它,就像你应该的那样(参见初始线程,它将不起作用
public static void main (String[] args) {
SwingUtilities.invokeLater(new Runnable(){
new OutputDisplay(); <==== Create on EDT
}); WON'T WORK!!
}
Run Code Online (Sandbox Code Playgroud)
"但是当我通过使用新的outputDisplay(String ip,int time)在其他类中调用它时,只有框架出现但内部没有文本."
JBUtton button = new JButton("Button");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
new OurputDisplay(); <===== Created on EDT!!
}
});
Run Code Online (Sandbox Code Playgroud)
无论您是否在Event线程上启动应用程序,所有组件事件都在此线程上进行调度,因此当您按下按钮尝试打开新帧时,这将在EDT上创建帧.同样的问题在运行时作为OutputDisplay
与自身SwingUtilities.invokeLater