2016-10-29 1 views
0

사용자가 만든 데이터베이스로 JComboBox를 가져 와서 채우는 로그인 프레임에서 작업하고 있으며 JComboBox에서 선택한 Item에 따라 JLabel Text를 설정합니다. JComboBox에서 항목을 선택할 때 JLabel에서 '연결 중 ...'이라는 텍스트를 표시하고 싶습니다.하지만 항목을 선택하면 GUI가 멈추고 5 초 후에 '연결됨'이 표시됩니다. '연결 중'이 건너 뜁니다. .. 'JLabel.JCombobox를 선택한 경우 GUI가 정지되었습니다. Swing Application에서 timer를 사용하여 actionListener에 조건문을 사용하는 방법은 무엇입니까?

미리 감사드립니다. 리스너 실행

package com.softoak.dba; 

import java.awt.Color; 
import java.awt.EventQueue; 

import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JOptionPane; 

import java.awt.Font; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.ResultSet; 
import java.sql.Statement; 
import java.util.ArrayList; 
import java.util.concurrent.TimeUnit; 

import javax.swing.JComboBox; 

public class Login{ 

private JFrame frame; 
static ArrayList<String> dbcom = new ArrayList<String>(); 
static String[] usecom; 
JLabel status = new JLabel("•"); 
JLabel lblNotConnected; 

/** 
* Launch the application. 
*/ 
public static void main(String[] args) throws Exception{ 
    Connection m_Connection = DriverManager.getConnection("jdbc:sqlserver://localhost;integratedSecurity=true"); 

    String dbs = "SELECT * FROM sys.databases WHERE owner_sid != 1"; 

    Statement st = m_Connection.createStatement(); 

    ResultSet m_ResultSet = st.executeQuery(dbs); 
    dbcom.add("-None-"); 

    while(m_ResultSet.next()){ 
     dbcom.add(m_ResultSet.getString(1)); 
    } 
    usecom = new String[dbcom.size()]; 
    usecom = dbcom.toArray(usecom); 

    EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      try { 
       Login window = new Login(); 
       window.frame.setVisible(true); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
    }); 
} 

/** 
* Create the application. 
*/ 
public Login() { 
    initialize(); 
} 

/** 
* Initialize the contents of the frame. 
*/ 

private void initialize() { 
    frame = new JFrame(); 
    frame.setBounds(100, 100, 450, 300); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.getContentPane().setLayout(null); 

    status.setBounds(385, 235, 10, 10); 
    status.setForeground(Color.red); 
    frame.getContentPane().add(status); 

    JLabel lblLoginApplication = new JLabel("Login Application"); 
    lblLoginApplication.setFont(new Font("Lucida Calligraphy", Font.BOLD, 20)); 
    lblLoginApplication.setBounds(120, 25, 220, 30); 
    frame.getContentPane().add(lblLoginApplication); 

    JComboBox comboBox = new JComboBox(usecom); 
    comboBox.setBounds(230, 80, 110, 30); 
    comboBox.addActionListener(new ActionListener(){ 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       if (comboBox.getSelectedIndex() == 1 || comboBox.getSelectedIndex() == 2) { 
        lblNotConnected.setText("Connecting..."); 
        try{ 
         Thread.sleep(5000); 
        }catch(InterruptedException ex){ 
         JOptionPane.showMessageDialog(null,ex.getMessage()); 
        } 
        status.setForeground(Color.green); 
        lblNotConnected.setText("Connected"); 
        JOptionPane.showMessageDialog(null, "Connected"); 
       } 
        else{ 
         status.setForeground(Color.red); 
         lblNotConnected.setText("Not Connected"); 
        } 
       } 
     }); 
    frame.getContentPane().add(comboBox); 

    JLabel lblSelectDatabase = new JLabel("Select Database"); 
    lblSelectDatabase.setFont(new Font("Microsoft Sans Serif", Font.BOLD, 14)); 
    lblSelectDatabase.setBounds(91, 79, 129, 30); 
    frame.getContentPane().add(lblSelectDatabase); 

    lblNotConnected = new JLabel("Not Connected"); 
    lblNotConnected.setFont(new Font("Elephant", Font.PLAIN, 12)); 
    lblNotConnected.setBounds(280, 230, 110, 20); 
    frame.getContentPane().add(lblNotConnected); 
} 

}

답변

2

코드는 Event Dispatch Thread(EDT)에 행한다. Thread.sleep()을 사용하면 EDT가 잠자기 상태가되어 GUI에서 다시 그릴 수 없습니다. 자세한 내용은 Concurrency에있는 스윙 튜토리얼의 섹션을 읽어보십시오.

위의 이유로 인해 잠재적으로 장기 실행중인 작업은 EDT에서 실행해서는 안됩니다. 대신 별도의 스레드를 사용해야합니다. 위의 자습서에서 SwingWorker을 확인하십시오. 거기에 Thread.sleep()을 사용하고 원하는 값을 게시하여 게시 할 수 있습니다.

그러나 사용자가 5 초를 기다리는 이유는 무엇입니까? 나는 좌절 할 것이라는 것을 안다.

어쩌면 ProgressMonitor을 사용하여 장기 실행 작업을 수행하고 있음을 사용자에게 알릴 수 있습니다. 자세한 내용과 작업 예제는 How to Use Progress Bars에있는 스윙 튜토리얼의 섹션을 읽어보십시오.

+0

감사합니다. 나는 지연이 약간의 재미를 가지기를 원한다. 그렇지 않으면 완벽하게 작동한다. 또한 GUI에서 초보자이므로 EDT (Event Dispatch Thread) 용어를 이해할 수 없습니다. –

+0

누구나 올바른 방식으로 올바른 코드를 제공 할 수 있습니까? –

+0

나는 이미 당신에게 두 가지 가능성을주었습니다. 그것은 자습서 링크가있는 것입니다. 올바른 방법으로 코드를 제공합니다. 튜토리얼을 읽으십시오. 예제를 다운로드하고 함께 플레이하십시오. 우리는 당신을 위해 코드를 작성하지 않았습니다. – camickr

관련 문제