2017-04-04 1 views
0

사용자 정의 JLabel의 인스턴스가 있고 모든 프레임에서 텍스트를 변경하려고하지만 텍스트가 마지막으로 열린 프레임에서만 변경됩니다. 내가 이걸 얻을 수있는 방법이 있니? 여기 모든 프레임에서 사용자 정의 JLabel 업데이트

발생 내용은 다음과 같습니다 enter image description here

그리고 내 코드 :

App.java

package test; 

import javax.swing.JFrame; 

public class App extends JFrame { 

    protected static App app; 

    private String loggedUser; 
    private MyCustomLabel myCustomLabel; 

    public App() { 
     loggedUser = "User One"; 
     myCustomLabel = new MyCustomLabel(loggedUser); 
    } 

    public static App getApp() { 
     return app; 
    } 

    public MyCustomLabel getMyCustomLabel() { 
     return myCustomLabel; 
    } 

    public String getLoggedUser() { 
     return loggedUser; 
    } 

    public void setLoggedUser(String loggedUser) { 
     this.loggedUser = loggedUser; 
    } 

} 

FrmApp.java

package test; 

import java.awt.FlowLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 

/** 
* 
* @author Marco 
*/ 
public class FrmApp extends App { 

    public FrmApp() { 
     app = new App(); 
     initComponents(); 
    } 

    private void initComponents() { 
     setLayout(new FlowLayout()); 
     setSize(300, 200); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setLocationRelativeTo(null); 

     btnFrmOne = new JButton("Open frmOne"); 
     btnFrmOne.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       FrmOne frmOne = new FrmOne(); 
       frmOne.setVisible(true); 
      } 
     }); 
     add(btnFrmOne); 

     btnFrmTwo = new JButton("Open frmTwo"); 
     btnFrmTwo.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       FrmTwo frmTwo = new FrmTwo(); 
       frmTwo.setVisible(true); 
      } 
     }); 
     add(btnFrmTwo); 

     btnChangeUser = new JButton("Change user"); 
     btnChangeUser.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       if (App.getApp().getLoggedUser().equals("User One")) { 
        App.getApp().setLoggedUser("User Two"); 
       } else { 
        App.getApp().setLoggedUser("User One"); 
       } 

       App.getApp().getMyCustomLabel().refresh(); 
      } 
     }); 
     add(btnChangeUser); 
    } 

    private JButton btnFrmOne; 
    private JButton btnFrmTwo; 
    private JButton btnChangeUser; 

    public static void main(String args[]) { 
     try { 
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
     } catch (ClassNotFoundException ex) { 
      Logger.getLogger(FrmApp.class.getName()).log(Level.SEVERE, null, ex); 
     } catch (InstantiationException ex) { 
      Logger.getLogger(FrmApp.class.getName()).log(Level.SEVERE, null, ex); 
     } catch (IllegalAccessException ex) { 
      Logger.getLogger(FrmApp.class.getName()).log(Level.SEVERE, null, ex); 
     } catch (UnsupportedLookAndFeelException ex) { 
      Logger.getLogger(FrmApp.class.getName()).log(Level.SEVERE, null, ex); 
     } 

     java.awt.EventQueue.invokeLater(new Runnable() { 
      public void run() { 
       new FrmApp().setVisible(true); 
      } 
     }); 
    } 

} 

에게

FrmOne.java을 617,451,515,
package test; 

import java.awt.FlowLayout; 
import javax.swing.JFrame; 

public class FrmOne extends JFrame { 

    public FrmOne() { 
     initComponents(); 
    } 

    private void initComponents() { 
     setLayout(new FlowLayout()); 
     setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
     setSize(150, 100); 

     add(App.getApp().getMyCustomLabel()); 
    } 

} 

FrmTwo.java

package test; 

import java.awt.FlowLayout; 
import javax.swing.JFrame; 

public class FrmTwo extends JFrame { 

    public FrmTwo() { 
     initComponents(); 
    } 

    private void initComponents() { 
     setLayout(new FlowLayout()); 
     setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
     setSize(150, 100); 

     add(App.getApp().getMyCustomLabel()); 
    } 

} 

MyCustomLabel.java

package test; 

import javax.swing.JLabel; 

public class MyCustomLabel extends JLabel { 

    public MyCustomLabel(String loggedUser) { 
     initComponents(loggedUser); 
    } 

    private void initComponents(String loggedUser) { 
     setText(loggedUser); 
    } 

    public void refresh() { 
     setText(App.getApp().getLoggedUser()); 
    } 

} 

업데이트

이 메신저 내가 원하는 것을 할 지금하고있는 것입니다.

App.java

public class App extends JFrame { 

    public App() { 
     User user = new User(1, "User One"); 
     LoggedUser.getInstance().setUser(user); 

     initComponents(); 
    } 

    public static void main(String[] args) { 
     new App().setVisible(true); 
    } 

    private void initComponents() { 
     setSize(200, 200); 
     setLocation(400, 200); 
     setLayout(new FlowLayout()); 
     setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 

     JButton btn1 = new JButton("dlgOne"); 
     btn1.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       DlgOne dlgOne = new DlgOne(App.this, false); 
       dlgOne.setVisible(true); 
      } 
     }); 

     JButton btn2 = new JButton("dlgTwo"); 
     btn2.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       DlgTwo dlgTwo = new DlgTwo(App.this, false); 
       dlgTwo.setVisible(true); 
      } 
     }); 

     JButton btn3 = new JButton("change user"); 
     btn3.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       if (LoggedUser.getInstance().getUser().getId() == 1) { 
        User user = new User(2, "User Two"); 
        LoggedUser.getInstance().setUser(user); 
       } else { 
        User user = new User(1, "User One"); 
        LoggedUser.getInstance().setUser(user); 
       } 
      } 
     }); 

     add(btn1); 
     add(btn2); 
     add(btn3); 
    } 
} 

MyCustomPanel.java

public class MyCustomPanel extends JPanel implements Observer { 

    private JLabel label; 

    public MyCustomPanel() { 
     initComponents(); 
    } 

    @Override 
    public void update(Observable o, Object arg) { 
     //LoggedUser u = (LoggedUser) o; 
     //System.out.println(u.getUser().getId()); 

     SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       label.setText(LoggedUser.getInstance().getUser().getName()); 
      } 

     }); 
    } 

    private void initComponents() { 
     LoggedUser.getInstance().addObserver(this); 

     label = new JLabel(LoggedUser.getInstance().getUser().getName()); 
     add(label); 
    } 

} 

User.java

public class User { 

    private int id; 
    private String name; 

    public User(int id, String name) { 
     this.id = id; 
     this.name = name; 
    } 

    public int getId() { 
     return id; 
    } 

    public void setId(int id) { 
     this.id = id; 
    } 

    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

} 

DlgOne.java

public class DlgOne extends JDialog { 

    public DlgOne(Frame owner, boolean modal) { 
     super(owner, modal); 
     initComponents(); 
    } 

    private void initComponents() { 
     setTitle("dlgOne"); 
     setSize(200, 200); 
     setLocation(600, 200); 
     setLayout(new FlowLayout()); 
     setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); 
     add(new MyCustomPanel()); 
    } 

} 
,691,363 (210)

DlgTwo.java

public class DlgTwo extends JDialog { 

    public DlgTwo(Frame owner, boolean modal) { 
     super(owner, modal); 
     initComponents(); 
    } 

    private void initComponents() { 
     setTitle("dlgTwo"); 
     setSize(200, 200); 
     setLocation(800, 200); 
     setLayout(new FlowLayout()); 
     setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); 
     add(new MyCustomPanel()); 
    } 

} 

LoggedUser.java

public class LoggedUser extends Observable { 

    private static LoggedUser instance; 

    public static LoggedUser getInstance() { 
     if (instance == null) { 
      instance = new LoggedUser(); 
     } 

     return instance; 
    } 

    private User user; 

    public User getUser() { 
     return user; 
    } 

    public void setUser(User user) { 
     this.user = user; 
     setChanged(); 
     notifyObservers(); 
    } 

} 
+0

당신은 관찰자 디자인 패턴을 사용하여 가지를 연결하려면, 그래서를 할 때 사용자의 변경, 여기에 등록 된 모든 리스너 (두 창 - 어느해야 대화 상자가 아니라 JFrames - 변경). M-V-C 또는 Model-View-Controller를 전체적인 방식으로 구조화하고 이에 따라 프로그램을 재구성하는 가장 좋은 방법을 찾으십시오. –

+0

[여러 JFrames 사용, 좋음/나쁜 관행?] (http://stackoverflow.com/q/9554636/418556) –

+0

@HovercraftFullOfEels 저는 옵저버를 사용하여 이제 원하는 것을 할 수 있습니다. Btw, 내가 코드를 업데이트하는 중. –

답변

1

나는 정의의 JLabel의 인스턴스를 가지고 난에 모든 프레임의 텍스트를 변경하려면,

스윙 구성 요소에는 단일 상위 항목 만있을 수 있습니다. 실제로 사용자 정의 레이블의 인스턴스가 두 개 있습니다. 따라서 한 레이블의 텍스트를 업데이트해도 다른 레이블에는 영향을주지 않습니다.

여러 JTextField에서 공유 할 텍스트를 포함하도록 PlainDocument을 만들면됩니다. 그런 다음 텍스트가 문서가 변경되면 모든 텍스트 필드가 업데이트됩니다.

private PlainDocument sharedDocument = new PlainDocument(); 

을 당신은 Document에 액세스하는 방법을 만들 것입니다 :

그래서 App 클래스에서, 당신은 것입니다. 어쩌면 getSharedDocument()과 같은 것일 수 있습니다.

다음 폼 클래스에 당신은 같은 것을 할 것 :

//add(App.getApp().getMyCustomLabel()); 
JTextField textField = new JTextField(App.getApp().getSharedDocument()); 
// customize text field to look like a label 
textField.setBorder(null); 
textField.setEditable(false); 
add(textField); 
관련 문제