我创建了一个框架,里面有一个面板,面板里面有一个文本区域。现在我创建了一个构造函数,它使框架在一段时间内可见,然后将其设置为不可见。它可见的时间会显示一些消息。
当我在 outputDisplay 类的主要方法中运行构造函数代码时,它显示文本消息 但是当我通过使用 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
最佳答案
Thread.sleep(time);
不要这样做(你正在阻止 EDT)。 Use a Swing Timer
Timer timer = new Timer(time, new ActionListener(){
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
}
});
timer.start();
查看
"When i run the constructor code inside the main method of outputDisplay class it shows the text massage "
你可能正在做
public static void main (String[] args) {
new OutputDisplay();
}
这不是在事件调度线程上运行,(但是错误)。如果你在 EDT 上运行它,就像你应该的那样(参见 Initial Threads ,它不会工作
public static void main (String[] args) {
SwingUtilities.invokeLater(new Runnable(){
new OutputDisplay(); <==== Create on EDT
}); WON'T WORK!!
}
"but when i call it inside other class by using new outputDisplay(String ip, int time) then only the frame appers but with no text inside it."
JBUtton button = new JButton("Button");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
new OurputDisplay(); <===== Created on EDT!!
}
});
无论您是否在事件线程上启动应用程序,所有组件事件都在此线程上调度,因此当您按下按钮尝试打开新框架时,这就是在 EDT 上创建框架。与使用 SwingUtilities.invokeLater
OutputDisplay
时的问题相同
关于java - 使用 new 关键字从同一包内的类外部调用它时在框架内获取空文本区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26785916/