2014-11-09 4 views
2

Я упаковал рамку, в которой есть панель внутри, а панель имеет внутри нее текстовое поле. Теперь я создал конструктор, который делает кадр видимым в течение некоторого времени, и после этого он устанавливается как невидимый. Время, за которое видно, показывает некоторый массаж.Получение null/empty JtextArea

Когда я запускаю код конструктора внутри основного метода класса outputDisplay показывает текст массаж

Get this output when runs inside the same method

Getting a empty frame when run it from other class by using new keyword

import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.Font; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.BoxLayout; 
import javax.swing.JFrame; 
import javax.swing.JOptionPane; 
import javax.swing.JPanel; 
import javax.swing.JTextArea; 
import javax.swing.Timer; 
public class OutputDisplay { 

static JFrame frame; 
JPanel panel; 
JTextArea area; 
Font font; 

    public void timer(int time){ 
     Timer timer = new Timer(time, new ActionListener(){ 
      public void actionPerformed(ActionEvent e){ 
       frame.setVisible(false); 
      } 
     }); 
     timer.start(); 
     timer.setRepeats(false); 
    } 

    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 
    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 

    OutputDisplay(String dialogue,String path,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.MAGENTA); 
    area.setSize(200, 200); 
    int j=0; 
    String[] t = {dialogue}; 
    for(int i=0;i<t.length;i++){ 
     area.append(t[i]+"\n"); 
    }//for 
    panel.add(area); 
    panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS)); 
    frame.getContentPane().add(BorderLayout.CENTER, panel); 
    frame.pack(); 
    frame.setSize(500, 200); 
    frame.setVisible(true); 
    Thread.sleep(time); 
    j++; 
    if(j==1){ 
     frame.setVisible(false); 
    }//if 
    frame.setResizable(false); 
    }//constructor 

    OutputDisplay(String dialogue) throws InterruptedException{ 
    frame = new JFrame("Report"); 
    frame.setLocation(400, 220); 
    panel = new JPanel(); 
    area = new JTextArea(); 
    font = new Font("Aharoni", Font.BOLD, 16); 
    area.setFont(font); 
    area.setForeground(Color.BLUE); 
    area.setSize(200, 200); 
    String[] t = {dialogue}; 
    for(int i=0;i<t.length;i++){ 
     area.append(t[i]+"\n"); 
    }//for 
    panel.add(area); 
    panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS)); 
    frame.getContentPane().add(BorderLayout.CENTER, panel); 
    frame.pack(); 
    frame.setSize(600, 600); 
    frame.setVisible(true); 
    frame.setResizable(false); 
    }//constructor 

    public OutputDisplay() { 
    }//no arg 

public void dialogue (String massage) throws InterruptedException{ 
     frame = new JFrame("Massage"); 
     frame.setLocation(400, 220); 
     JPanel panel = new JPanel(); 
     JTextArea area = new JTextArea(); 
     Font font = new Font("Aharoni", Font.BOLD, 16); 
     area.setFont(font); 
     area.setForeground(Color.GREEN); 
     area.setSize(200, 200); 
     int j=0; 
     String[] t = {massage}; 
     for(int i=0;i<t.length;i++){ 
      area.append(t[i]+"\n"); 
     }//for 
     panel.add(area); 
     panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS)); 
     frame.getContentPane().add(BorderLayout.CENTER, panel); 
     frame.pack(); 
     frame.setSize(400, 100); 
     frame.setVisible(true); 
     Thread.sleep(8*1000); 
     j++; 
     if(j==1){ 
      frame.setVisible(false); 
     }//if 
     frame.setResizable(false); 
    }//dialogue 

    static void warningPopUp (String massage){ 
     JOptionPane.showMessageDialog(null, massage); 
    }//dialogue 

    public static void main(String[] args){ 
    new OutputDisplay("We are checking for account validation"+"\n" 
       + "If user id and password matches then we will goto websites for updation. " +"\n" 
      + "You will get a complete report once we are done", 4*1000); 


    }//main 
}//OutputDisplay 

ответ

5
  • Не называйте Thread.sleep(...) на свинг EDT так как это просто заставляет весь ваш графический интерфейс спать.
  • Вместо этого используйте Swing Timer.
  • У Google и поиск этого сайта по аналогичным вопросам.
  • Пожалуйста, ознакомьтесь с Lesson: Concurrency in Swing
  • Также проверьте Swing Tutorials

Редактировать
Вы все еще используете Thread.sleep, опять же, вы не должны использовать его, но вместо этого следует использовать таймер. Кроме того, никогда не устанавливайте размер или предпочтительный размер JTextArea. Сделайте это, и полосы прокрутки вашего JScrollPane не будут работать. Вместо этого задайте его строки и столбцы.

import java.awt.Color; 
import java.awt.Font; 
import java.awt.Dialog.ModalityType; 
import java.awt.Window; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 

import javax.swing.*; 

public class TimeLimitedDialogTester { 
    private static final int EB_GAP = 25; 
    private JPanel mainPanel = new JPanel(); 

    public TimeLimitedDialogTester() { 
     mainPanel.add(new JButton(new ShowDialogAction("Show Dialog"))); 
     mainPanel.setBorder(BorderFactory.createEmptyBorder(EB_GAP, 2 * EB_GAP, 2 * EB_GAP, 2 * EB_GAP)); 
    } 

    public JPanel getMainPanel() { 
     return mainPanel; 
    } 

    @SuppressWarnings("serial") 
    private class ShowDialogAction extends AbstractAction { 
     public ShowDialogAction(String name) { 
     super(name); 
     int mnemonic = (int) name.charAt(0); 
     putValue(MNEMONIC_KEY, mnemonic); 
     } 

     @Override 
     public void actionPerformed(ActionEvent e) { 
     Window mainWin = SwingUtilities.getWindowAncestor(mainPanel); 
     int seconds = 5; 
     String dialogTitle = "WARNING"; 
     String text = "We are checking for account validation. If user id and password matches then we" 
       + " will go to websites for updating. You will get a complete report once we are done."; 
     TimeLimitedDialog timeLimitedDialog = new TimeLimitedDialog(mainWin, seconds, dialogTitle, text); 
     timeLimitedDialog.dialogShow();   
     } 
    } 

    private static void createAndShowGui() { 
     TimeLimitedDialogTester timeLimitedDialog = new TimeLimitedDialogTester(); 

     JFrame frame = new JFrame("TimeLimitedDialog"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.getContentPane().add(timeLimitedDialog.getMainPanel()); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
      createAndShowGui(); 
     } 
     }); 
    } 
} 

class TimeLimitedDialog { 
    private static final int ROWS = 6; 
    private static final int COLS = 30; 
    private static final Color FG = Color.green.darker().darker(); 
    private JDialog dialog; 
    private JTextArea displayArea = new JTextArea(ROWS, COLS); 
    private int seconds; 

    public TimeLimitedDialog(Window mainWin, int seconds, String dialogTitle, String text) { 
     displayArea.setWrapStyleWord(true); 
     displayArea.setLineWrap(true); 
     displayArea.setFocusable(false); 
     displayArea.setText(text); 
     displayArea.setForeground(FG); 
     displayArea.setFont(displayArea.getFont().deriveFont(Font.BOLD)); 

     this.seconds = seconds; 
     dialog = new JDialog(mainWin, dialogTitle, ModalityType.APPLICATION_MODAL); 
     dialog.add(new JScrollPane(displayArea)); 
     dialog.pack(); 
     dialog.setLocationRelativeTo(mainWin); 
    } 

    public void dialogShow() { 
     new Timer(seconds * 1000, new TimerListener()).start(); 
     dialog.setVisible(true); 
    } 

    private class TimerListener implements ActionListener { 
     @Override 
     public void actionPerformed(ActionEvent e) { 
     if (dialog != null && dialog.isVisible()) { 
      dialog.dispose(); 
     } 
     ((Timer) e.getSource()).stop(); 
     } 
    } 
} 
+0

Сэр, пожалуйста, дайте мне пример кода, который поможет мне, как это сделать. Я попробовал это самостоятельно, но не смог этого сделать. –

+0

@SwetaSingh: Я попытался создать пример с использованием вашего кода, но ваш код не имеет основного метода и не запускается. Пожалуйста, исправьте это. –

+0

Я вложил в него основной метод. –

Смежные вопросы