Example usage for java.awt Container setLayout

List of usage examples for java.awt Container setLayout

Introduction

In this page you can find the example usage for java.awt Container setLayout.

Prototype

public void setLayout(LayoutManager mgr) 

Source Link

Document

Sets the layout manager for this container.

Usage

From source file:br.org.acessobrasil.ases.ferramentas_de_reparo.vista.objeto.PainelObjeto.java

private void initComponentsEscalavel(

        ArrayList<FerramentaDescricaoModel> erros) {
    Ferramenta_Objetos.carregaTexto(TokenLang.LANG);
    JPanel regraFonteBtn = new JPanel();
    regraFonteBtn.setLayout(new BorderLayout());

    scrollPaneDescricao = new G_TextAreaSourceCode();
    scrollPaneDescricao.setTipoHTML();/*from w  ww  . ja v a 2  s .  co  m*/
    new OnChange(scrollPaneDescricao, this);
    //parentFrame.setJMenuBar(this.criaMenuBar());

    // parentFrame.setTitle("Associador de rtulos");
    tableLinCod = new TabelaDescricao(erros);
    arTextPainelCorrecao = new ArTextPainelCorrecao();

    // scrollPaneCorrecaoLabel = new ConteudoCorrecaoLabel();

    salvar = new JButton();
    abrir = new JButton();
    cancelar = new JButton();
    strConteudoalt = new String();
    // panelLegenda = new JPanel();

    pnRegra = new JPanel();
    lbRegras1 = new JLabel();
    lbRegras2 = new JLabel();
    pnSetaDescricao = new JPanel();
    pnSetaDescricao.setLayout(new BorderLayout());
    spTextoDescricao = new JScrollPane();
    tArParticipRotulo = new TArParticipRotulo();
    conteudoDoAlt = new JTextArea();
    pnListaErros = new JPanel();
    scrollPanetabLinCod = new JScrollPane();
    lbTemp = new JLabel();
    pnBotoes = new JPanel();
    btnSalvar = new JMenuItem(GERAL.BTN_SALVAR);

    adicionar = new JButton();
    conteudoParticRotulo = new ArrayList<String>();
    // setJMenuBar(this.criaMenuBar());
    // ======== this ========
    // setTitle("Associe explicitamente os r\u00f3tulos aos respectivos
    // controles:");
    salvar.setEnabled(false);
    salvaAlteracoes = TxtBuffer.getInstanciaSalvaAlteracoes(scrollPaneDescricao.getTextPane(), salvar,
            new JMenuItem(), parentFrame);
    setBackground(CoresDefault.getCorPaineis());
    Container contentPane = this;// ??
    contentPane.setLayout(new GridLayout(2, 1));

    // ======== pnRegra ========
    {
        pnRegra.setBorder(criaBorda(Ferramenta_Objetos.TITULO_REGRA));
        pnRegra.setLayout(new GridLayout(2, 1));
        pnRegra.add(lbRegras1);
        lbRegras1.setText(Ferramenta_Objetos.REGRAP1);
        lbRegras2.setText(Ferramenta_Objetos.REGRAP2);
        lbRegras1.setHorizontalAlignment(SwingConstants.CENTER);

        lbRegras2.setHorizontalAlignment(SwingConstants.CENTER);
        pnRegra.add(lbRegras1);
        pnRegra.add(lbRegras2);
        pnRegra.setPreferredSize(new Dimension(700, 60));
    }

    // G_URLIcon.setIcon(lbTemp,
    // "http://pitecos.blogs.sapo.pt/arquivo/pai%20natal%20o5.%20jpg.jpg");

    // ======== pnDescricao ========

    // ---- Salvar ----
    salvar.setText(Ferramenta_Objetos.BTN_SALVAR);
    salvar.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            salvarActionPerformed(e);
        }
    });

    salvar.setToolTipText(Ferramenta_Objetos.DICA_SALVAR);
    salvar.getAccessibleContext().setAccessibleDescription(Ferramenta_Objetos.DICA_SALVAR);
    salvar.getAccessibleContext().setAccessibleName(Ferramenta_Objetos.DICA_SALVAR);
    salvar.setBounds(10, 0, 150, 25);

    abrir.setText(Ferramenta_Objetos.BTN_ABRIR);
    abrir.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            AbrirActionPerformed(e);
        }
    });

    abrir.setToolTipText(Ferramenta_Objetos.DICA_ABRIR);
    abrir.getAccessibleContext().setAccessibleDescription(Ferramenta_Objetos.DICA_ABRIR_HTML);
    abrir.getAccessibleContext().setAccessibleName(Ferramenta_Objetos.DICA_ABRIR_HTML);
    abrir.setBounds(165, 0, 150, 25);

    cancelar.setText(Ferramenta_Objetos.TELA_ANTERIOR);
    cancelar.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            CancelarActionPerformed(e);
        }
    });

    cancelar.setToolTipText(Ferramenta_Objetos.DICA_TELA_ANTERIOR);
    cancelar.getAccessibleContext().setAccessibleDescription(Ferramenta_Objetos.DICA_TELA_ANTERIOR);
    cancelar.getAccessibleContext().setAccessibleName(Ferramenta_Objetos.DICA_TELA_ANTERIOR);
    cancelar.setBounds(320, 0, 150, 25);

    // ======== pnParticRotulo ========

    // pnSetaDescricao.setBorder(criaBorda(Ferramenta_Imagens.TITULO_DIGITE_O_ALT));

    // ======== spParticRotulo ========
    {
        // spTextoDescricao.setViewportView(conteudoDoAlt);
    }

    // lbRegras1.setText(Reparo_Imagens.REGRAP2);
    // lbRegras1.setHorizontalAlignment(SwingConstants.CENTER);

    // pnRegra.add(lbRegras1);

    JScrollPane sp = new JScrollPane();

    sp.setViewportView(conteudoDoAlt);
    sp.setPreferredSize(new Dimension(500, 300));
    sp.setBorder(criaBorda(Ferramenta_Objetos.CONTEUDO_ALTER));
    // pnSetaDescricao.add(spTextoDescricao,cons);

    pnSetaDescricao.setPreferredSize(new Dimension(400, 60));

    // ======== pnListaErros ========
    {

        pnListaErros.setBorder(criaBorda(Ferramenta_Objetos.LISTA_ERROS));
        pnListaErros.setLayout(new BorderLayout());
        // ======== scrollPanetabLinCod ========
        {
            scrollPanetabLinCod.setViewportView(tableLinCod);
        }
        pnListaErros.add(scrollPanetabLinCod, BorderLayout.CENTER);
    }
    // ======== pnBotoes ========
    {

        // pnBotoes.setBorder(criaBorda(""));

        pnBotoes.setLayout(null);
        // ---- adicionar ----
        adicionar.setText(Ferramenta_Objetos.BTN_ADICIONAR);
        adicionar.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                adicionarActionPerformed(e);
            }
        });
    }

    /*
     * Colocar os controles
     */
    pnRegra.setBackground(CoresDefault.getCorPaineis());
    regraFonteBtn.add(pnRegra, BorderLayout.NORTH);
    scrollPaneDescricao.setBorder(criaBorda(""));
    scrollPaneDescricao.setBackground(CoresDefault.getCorPaineis());

    JSplitPane splitPane = null;

    Dimension minimumSize = new Dimension(0, 0);
    // JScrollPane ajudaScrollPane = new
    // JScrollPane(ajuda,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

    sp.setMinimumSize(minimumSize);
    sp.setPreferredSize(new Dimension(150, 90));
    splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, sp, scrollPaneDescricao);
    splitPane.setOneTouchExpandable(true);
    // splitPane.set
    // splitPane.setDividerLocation(0.95);
    int w = parentFrame.getWidth();
    int s = w / 4;
    splitPane.setDividerLocation(s);

    // regraFonteBtn.add(scrollPaneCorrecaoLabel, BorderLayout.CENTER);
    regraFonteBtn.add(splitPane, BorderLayout.CENTER);
    pnBotoes.setPreferredSize(new Dimension(600, 35));
    pnBotoes.setBackground(CoresDefault.getCorPaineis());
    // regraFonteBtn.add(pnBotoes, BorderLayout.SOUTH);
    regraFonteBtn.setBackground(CoresDefault.getCorPaineis());
    contentPane.add(regraFonteBtn);

    JPanel textoErrosBtn = new JPanel();
    textoErrosBtn.setLayout(new BorderLayout());
    pnSetaDescricao.setBackground(CoresDefault.getCorPaineis());
    pnSetaDescricao.add(pnBotoes);
    aplicar = new JButton();
    aplicar.setBounds(3, 3, 120, 30);
    pnBotoes.add(aplicar);

    // ---- aplicarRotulo ----
    aplicar.setEnabled(false);
    aplicar.setText(Ferramenta_Objetos.BTN_APLICAR);
    aplicar.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            aplicarRotuloActionPerformed(e);
        }
    });

    aplicar.setToolTipText(Ferramenta_Objetos.DICA_APLICAR);
    aplicar.getAccessibleContext().setAccessibleDescription(Ferramenta_Objetos.DICA_APLICAR);
    aplicar.getAccessibleContext().setAccessibleName(Ferramenta_Objetos.DICA_APLICAR);
    textoErrosBtn.add(pnSetaDescricao, BorderLayout.NORTH);

    textoErrosBtn.add(pnListaErros, BorderLayout.CENTER);
    JPanel pnSalvarCancelar = new JPanel();
    pnSalvarCancelar.setLayout(null);
    pnSalvarCancelar.setPreferredSize(new Dimension(600, 35));
    pnSalvarCancelar.add(salvar);
    pnSalvarCancelar.add(abrir);
    pnSalvarCancelar.add(cancelar);

    if (!original) {
        reverter = new JButton("Reverter");
        reverter.setText(TradPainelRelatorio.REVERTER);
        reverter.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                setVisible(false);
                TxtBuffer.setContent(TxtBuffer.getContentOriginal());
                parentFrame.showPainelFerramentaDescricaoObjetosPArq(TxtBuffer.getContentOriginal());
                setVisible(true);
            }

        });
        //reverter.setActionCommand("Reverter");
        reverter.setToolTipText(TradPainelRelatorio.DICA_REVERTER);
        reverter.getAccessibleContext().setAccessibleDescription(TradPainelRelatorio.DICA_REVERTER);
        reverter.getAccessibleContext().setAccessibleName(TradPainelRelatorio.DICA_REVERTER);
        reverter.setBounds(485, 0, 150, 25);
        pnSalvarCancelar.add(reverter);
    }

    pnSalvarCancelar.setBackground(CoresDefault.getCorPaineis());
    textoErrosBtn.add(pnSalvarCancelar, BorderLayout.SOUTH);
    pnListaErros.setBackground(CoresDefault.getCorPaineis());
    textoErrosBtn.add(pnListaErros, BorderLayout.CENTER);
    contentPane.setBackground(CoresDefault.getCorPaineis());
    contentPane.add(textoErrosBtn);
    if (tableLinCod.getRowCount() == 0)
        tableLinCod.addLinha(0, 0, GERAL.DOC_SEM_ERROS);
    this.setVisible(true);

}

From source file:br.org.acessobrasil.ases.ferramentas_de_reparo.vista.label.PainelLabel.java

private void initComponentsEscalavel(ArrayList<FerramentaLabelModel> erros) {

    LabelPanel.carregaTexto(TokenLang.LANG);
    JPanel regraFonteBtn = new JPanel();
    regraFonteBtn.setLayout(new BorderLayout());

    textAreaSourceCode = new G_TextAreaSourceCode();
    textAreaSourceCode.setTipoHTML();/*  w  ww. j a va  2  s . c  om*/

    //parentFrame.setJMenuBar(this.criaMenuBar());

    // parentFrame.setTitle("Associador de rtulos");
    tableLinCod = new TabelaCorrecaoLabel(erros);
    arTextPainelCorrecao = new ArTextPainelCorrecao();

    salvar = new JButton();
    salvar.setEnabled(false);
    //btnSalvar.setEnabled(false);
    abrir = new JButton();
    cancelar = new JButton();
    // panelLegenda = new JPanel();
    salvaAlteracoes = TxtBuffer.getInstanciaSalvaAlteracoes(textAreaSourceCode.getTextPane(), salvar,
            new JMenuItem(), parentFrame);
    new OnChange(textAreaSourceCode, this);

    pnRegra = new JPanel();
    lbRegras1 = new JLabel();
    lbRegras2 = new JLabel();
    pnParticRotulo = new JPanel();
    spParticRotulo = new JScrollPane();
    tArParticipRotulo = new TArParticipRotulo();

    pnListaErros = new JPanel();
    scrollPanetabLinCod = new JScrollPane();

    pnBotoes = new JPanel();

    adicionar = new JButton();
    aplicarRotulo = new JButton();
    conteudoParticRotulo = new ArrayList<String>();
    // setJMenuBar(this.criaMenuBar());
    // ======== this ========
    // setTitle("Associe explicitamente os r\u00f3tulos aos respectivos
    // controles:");

    setBackground(CoresDefault.getCorPaineis());
    Container contentPane = this;// ??
    contentPane.setLayout(new GridLayout(2, 1));

    // ======== pnRegra ========
    {
        pnRegra.setBorder(criaBorda(LabelPanel.TITULO_REGRA));
        pnRegra.setLayout(new GridLayout(2, 1));
        pnRegra.add(lbRegras1);
        lbRegras1.setText(LabelPanel.REGRAP1);
        lbRegras2.setText(LabelPanel.REGRAP2);
        lbRegras1.setHorizontalAlignment(SwingConstants.CENTER);
        lbRegras2.setHorizontalAlignment(SwingConstants.CENTER);
        pnRegra.add(lbRegras1);
        pnRegra.add(lbRegras2);
        pnRegra.setPreferredSize(new Dimension(700, 60));
    }

    // ======== pnDescricao ========
    {
        // ---- Salvar ----
        salvar.setText(GERAL.BTN_SALVAR);
        salvar.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("btn_salvar.actionPerformed()");
                salvarActionPerformed(e);
            }
        });

        salvar.setToolTipText(GERAL.DICA_SALVAR);
        salvar.getAccessibleContext().setAccessibleDescription(GERAL.DICA_SALVAR);
        salvar.getAccessibleContext().setAccessibleName(GERAL.DICA_SALVAR);
        salvar.setBounds(10, 0, 150, 25);

        abrir.setText(GERAL.BTN_ABRIR);
        abrir.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                AbrirActionPerformed(e);
            }
        });

        abrir.setToolTipText(LabelPanel.DICA_ABRIR);
        abrir.getAccessibleContext().setAccessibleDescription(LabelPanel.DICA_ABRIR);
        abrir.getAccessibleContext().setAccessibleName(LabelPanel.DICA_ABRIR);
        abrir.setBounds(165, 0, 150, 25);

        cancelar.setText(LabelPanel.TELA_ANTERIOR);
        cancelar.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                CancelarActionPerformed(e);
            }
        });

        cancelar.setToolTipText(LabelPanel.DICA_TELA_ANTERIOR);
        cancelar.getAccessibleContext().setAccessibleDescription(LabelPanel.DICA_TELA_ANTERIOR);
        cancelar.getAccessibleContext().setAccessibleName(LabelPanel.DICA_TELA_ANTERIOR);
        cancelar.setBounds(320, 0, 150, 25);

        // ======== pnParticRotulo ========
        {
            pnParticRotulo.setBorder(criaBorda(LabelPanel.TITULO_PARTCP_DO_ROTULO));
            pnParticRotulo.setLayout(new BorderLayout());

            // ======== spParticRotulo ========
            {
                spParticRotulo.setViewportView(tArParticipRotulo);
            }
            pnParticRotulo.add(spParticRotulo, BorderLayout.CENTER);
            pnParticRotulo.setPreferredSize(new Dimension(780, 80));
        }
        // ======== pnListaErros ========
        {

            pnListaErros.setBorder(criaBorda(LabelPanel.TITULO_TABELA));
            pnListaErros.setLayout(new BorderLayout());
            // ======== scrollPanetabLinCod ========
            {
                scrollPanetabLinCod.setViewportView(tableLinCod);
            }
            pnListaErros.add(scrollPanetabLinCod, BorderLayout.CENTER);
        }
        // ======== pnBotoes ========
        {

            // pnBotoes.setBorder(criaBorda(""));

            pnBotoes.setLayout(null);
            // ---- adicionar ----
            adicionar.setText(GERAL.BTN_ADICIONAR);
            adicionar.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {

                    adicionarActionPerformed(e);
                }
            });

            adicionar.setToolTipText(LabelPanel.BTN_ADICIONAR_TOOLTIP);
            adicionar.getAccessibleContext().setAccessibleDescription(LabelPanel.BTN_ADICIONAR_TOOLTIP);
            adicionar.getAccessibleContext().setAccessibleName(LabelPanel.BTN_ADICIONAR_TOOLTIP);
            adicionar.setBounds(10, 5, 150, 25);
            pnBotoes.add(adicionar);

            // ---- aplicarRotulo ----
            aplicarRotulo.setEnabled(false);
            aplicarRotulo.setText(LabelPanel.BTN_APLICAR_ROTULO);
            aplicarRotulo.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    aplicarRotuloActionPerformed(e);
                }
            });

            aplicarRotulo.setToolTipText(LabelPanel.BTN_APLICAR_ROTULO_TOOLTIP);
            aplicarRotulo.getAccessibleContext()
                    .setAccessibleDescription(LabelPanel.BTN_APLICAR_ROTULO_TOOLTIP);
            aplicarRotulo.getAccessibleContext().setAccessibleName(LabelPanel.BTN_APLICAR_ROTULO_TOOLTIP);
            aplicarRotulo.setBounds(165, 5, 150, 25);
            pnBotoes.add(aplicarRotulo);
        }
    }
    /*
     * Colocar os controles
     */
    pnRegra.setBackground(CoresDefault.getCorPaineis());
    regraFonteBtn.add(pnRegra, BorderLayout.NORTH);
    textAreaSourceCode.setBorder(criaBorda(""));
    textAreaSourceCode.setBackground(CoresDefault.getCorPaineis());
    regraFonteBtn.add(textAreaSourceCode, BorderLayout.CENTER);
    pnBotoes.setPreferredSize(new Dimension(600, 35));
    pnBotoes.setBackground(CoresDefault.getCorPaineis());
    regraFonteBtn.add(pnBotoes, BorderLayout.SOUTH);
    regraFonteBtn.setBackground(CoresDefault.getCorPaineis());
    contentPane.add(regraFonteBtn);

    JPanel textoErrosBtn = new JPanel();
    textoErrosBtn.setLayout(new BorderLayout());
    pnParticRotulo.setBackground(CoresDefault.getCorPaineis());
    textoErrosBtn.add(pnParticRotulo, BorderLayout.NORTH);
    textoErrosBtn.add(pnListaErros, BorderLayout.CENTER);
    JPanel pnSalvarCancelar = new JPanel();
    pnSalvarCancelar.setLayout(null);
    pnSalvarCancelar.setPreferredSize(new Dimension(600, 35));
    pnSalvarCancelar.add(salvar);
    pnSalvarCancelar.add(abrir);
    pnSalvarCancelar.add(cancelar);
    pnSalvarCancelar.setBackground(CoresDefault.getCorPaineis());
    if (!original) {
        reverter = new JButton("Reverter");
        reverter.setText(TradPainelRelatorio.REVERTER);
        reverter.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                setVisible(false);
                TxtBuffer.setContent(TxtBuffer.getContentOriginal());
                parentFrame.showPainelFerramentaLabelPArq(TxtBuffer.getContentOriginal());
                setVisible(true);
            }
        });
        //reverter.setActionCommand("Reverter");
        reverter.setToolTipText(TradPainelRelatorio.DICA_REVERTER);
        reverter.getAccessibleContext().setAccessibleDescription(TradPainelRelatorio.DICA_REVERTER);
        reverter.getAccessibleContext().setAccessibleName(TradPainelRelatorio.DICA_REVERTER);
        reverter.setBounds(485, 0, 150, 25);
        pnSalvarCancelar.add(reverter);
    }

    textoErrosBtn.add(pnSalvarCancelar, BorderLayout.SOUTH);
    pnListaErros.setBackground(CoresDefault.getCorPaineis());
    if (tableLinCod.getRowCount() == 0)
        tableLinCod.addLinha(0, 0, GERAL.DOC_SEM_ERROS);
    textoErrosBtn.add(pnListaErros, BorderLayout.CENTER);
    contentPane.setBackground(CoresDefault.getCorPaineis());
    contentPane.add(textoErrosBtn);

    this.setVisible(true);

}

From source file:org.languagetool.gui.Main.java

private void createGUI() {
    loadRecentFiles();/*from  www.ja v a 2s . com*/
    frame = new JFrame("LanguageTool " + JLanguageTool.VERSION);

    setLookAndFeel();
    openAction = new OpenAction();
    saveAction = new SaveAction();
    saveAsAction = new SaveAsAction();
    checkAction = new CheckAction();
    autoCheckAction = new AutoCheckAction(true);
    showResultAction = new ShowResultAction(true);

    frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
    frame.addWindowListener(new CloseListener());
    URL iconUrl = JLanguageTool.getDataBroker().getFromResourceDirAsUrl(TRAY_ICON);
    frame.setIconImage(new ImageIcon(iconUrl).getImage());

    textArea = new JTextArea();
    textArea.setLineWrap(true);
    textArea.setWrapStyleWord(true);
    textArea.addKeyListener(new ControlReturnTextCheckingListener());

    textLineNumber = new TextLineNumber(textArea, 2);
    numberedTextAreaPane = new JScrollPane(textArea);
    numberedTextAreaPane.setRowHeaderView(textLineNumber);

    resultArea = new JTextPane();
    undoRedo = new UndoRedoSupport(this.textArea, messages);
    frame.setJMenuBar(createMenuBar());

    GridBagConstraints buttonCons = new GridBagConstraints();

    JPanel insidePanel = new JPanel();
    insidePanel.setOpaque(false);
    insidePanel.setLayout(new GridBagLayout());

    buttonCons.gridx = 0;
    buttonCons.gridy = 0;
    buttonCons.anchor = GridBagConstraints.LINE_START;
    insidePanel.add(new JLabel(messages.getString("textLanguage") + " "), buttonCons);

    //create a ComboBox with flags, do not include hidden languages
    languageBox = LanguageComboBox.create(messages, EXTERNAL_LANGUAGE_SUFFIX, true, false);
    buttonCons.gridx = 1;
    buttonCons.gridy = 0;
    buttonCons.anchor = GridBagConstraints.LINE_START;
    insidePanel.add(languageBox, buttonCons);

    JCheckBox autoDetectBox = new JCheckBox(messages.getString("atd"));
    buttonCons.gridx = 2;
    buttonCons.gridy = 0;
    buttonCons.gridwidth = GridBagConstraints.REMAINDER;
    buttonCons.anchor = GridBagConstraints.LINE_START;
    insidePanel.add(autoDetectBox, buttonCons);

    buttonCons.gridx = 0;
    buttonCons.gridy = 1;
    buttonCons.gridwidth = GridBagConstraints.REMAINDER;
    buttonCons.fill = GridBagConstraints.HORIZONTAL;
    buttonCons.anchor = GridBagConstraints.LINE_END;
    buttonCons.weightx = 1.0;
    insidePanel.add(statusLabel, buttonCons);

    Container contentPane = frame.getContentPane();
    GridBagLayout gridLayout = new GridBagLayout();
    contentPane.setLayout(gridLayout);
    GridBagConstraints cons = new GridBagConstraints();

    cons.gridx = 0;
    cons.gridy = 1;
    cons.fill = GridBagConstraints.HORIZONTAL;
    cons.anchor = GridBagConstraints.FIRST_LINE_START;
    JToolBar toolbar = new JToolBar("Toolbar", JToolBar.HORIZONTAL);
    toolbar.setFloatable(false);
    contentPane.add(toolbar, cons);

    JButton openButton = new JButton(openAction);
    openButton.setHideActionText(true);
    openButton.setFocusable(false);
    toolbar.add(openButton);

    JButton saveButton = new JButton(saveAction);
    saveButton.setHideActionText(true);
    saveButton.setFocusable(false);
    toolbar.add(saveButton);

    JButton saveAsButton = new JButton(saveAsAction);
    saveAsButton.setHideActionText(true);
    saveAsButton.setFocusable(false);
    toolbar.add(saveAsButton);

    JButton spellButton = new JButton(this.checkAction);
    spellButton.setHideActionText(true);
    spellButton.setFocusable(false);
    toolbar.add(spellButton);

    JToggleButton autoSpellButton = new JToggleButton(autoCheckAction);
    autoSpellButton.setHideActionText(true);
    autoSpellButton.setFocusable(false);
    toolbar.add(autoSpellButton);

    JButton clearTextButton = new JButton(new ClearTextAction());
    clearTextButton.setHideActionText(true);
    clearTextButton.setFocusable(false);
    toolbar.add(clearTextButton);

    cons.insets = new Insets(5, 5, 5, 5);
    cons.fill = GridBagConstraints.BOTH;
    cons.weightx = 10.0f;
    cons.weighty = 10.0f;
    cons.gridx = 0;
    cons.gridy = 2;
    cons.weighty = 5.0f;
    splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, numberedTextAreaPane, new JScrollPane(resultArea));
    mainPanel.setLayout(new GridLayout(0, 1));
    contentPane.add(mainPanel, cons);
    mainPanel.add(splitPane);

    cons.fill = GridBagConstraints.HORIZONTAL;
    cons.gridx = 0;
    cons.gridy = 3;
    cons.weightx = 1.0f;
    cons.weighty = 0.0f;
    cons.insets = new Insets(4, 12, 4, 12);
    contentPane.add(insidePanel, cons);

    ltSupport = new LanguageToolSupport(this.frame, this.textArea, this.undoRedo);
    ResultAreaHelper.install(messages, ltSupport, resultArea);
    languageBox.selectLanguage(ltSupport.getLanguage());
    languageBox.setEnabled(!ltSupport.getConfig().getAutoDetect());
    autoDetectBox.setSelected(ltSupport.getConfig().getAutoDetect());
    taggerShowsDisambigLog = ltSupport.getConfig().getTaggerShowsDisambigLog();

    languageBox.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                // we cannot re-use the existing LT object anymore
                frame.applyComponentOrientation(ComponentOrientation.getOrientation(Locale.getDefault()));
                Language lang = languageBox.getSelectedLanguage();
                ComponentOrientation componentOrientation = ComponentOrientation
                        .getOrientation(lang.getLocale());
                textArea.applyComponentOrientation(componentOrientation);
                resultArea.applyComponentOrientation(componentOrientation);
                ltSupport.setLanguage(lang);
            }
        }
    });
    autoDetectBox.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            boolean selected = e.getStateChange() == ItemEvent.SELECTED;
            languageBox.setEnabled(!selected);
            ltSupport.getConfig().setAutoDetect(selected);
            if (selected) {
                Language detected = ltSupport.autoDetectLanguage(textArea.getText());
                languageBox.selectLanguage(detected);
            }
        }
    });
    ltSupport.addLanguageToolListener(new LanguageToolListener() {
        @Override
        public void languageToolEventOccurred(LanguageToolEvent event) {
            if (event.getType() == LanguageToolEvent.Type.CHECKING_STARTED) {
                String msg = org.languagetool.tools.Tools.i18n(messages, "checkStart");
                statusLabel.setText(msg);
                if (event.getCaller() == getFrame()) {
                    setWaitCursor();
                    checkAction.setEnabled(false);
                }
            } else if (event.getType() == LanguageToolEvent.Type.CHECKING_FINISHED) {
                if (event.getCaller() == getFrame()) {
                    checkAction.setEnabled(true);
                    unsetWaitCursor();
                }
                String msg = org.languagetool.tools.Tools.i18n(messages, "checkDone",
                        event.getSource().getMatches().size(), event.getElapsedTime());
                statusLabel.setText(msg);
            } else if (event.getType() == LanguageToolEvent.Type.LANGUAGE_CHANGED) {
                languageBox.selectLanguage(ltSupport.getLanguage());
            } else if (event.getType() == LanguageToolEvent.Type.RULE_ENABLED) {
                //this will trigger a check and the result will be updated by
                //the CHECKING_FINISHED event
            } else if (event.getType() == LanguageToolEvent.Type.RULE_DISABLED) {
                String msg = org.languagetool.tools.Tools.i18n(messages, "checkDoneNoTime",
                        event.getSource().getMatches().size());
                statusLabel.setText(msg);
            }
        }
    });
    frame.applyComponentOrientation(ComponentOrientation.getOrientation(Locale.getDefault()));
    Language lang = ltSupport.getLanguage();
    ComponentOrientation componentOrientation = ComponentOrientation.getOrientation(lang.getLocale());
    textArea.applyComponentOrientation(componentOrientation);
    resultArea.applyComponentOrientation(componentOrientation);

    ResourceBundle textLanguageMessageBundle = JLanguageTool.getMessageBundle(ltSupport.getLanguage());
    textArea.setText(textLanguageMessageBundle.getString("guiDemoText"));

    Configuration config = ltSupport.getConfig();
    if (config.getFontName() != null || config.getFontStyle() != Configuration.FONT_STYLE_INVALID
            || config.getFontSize() != Configuration.FONT_SIZE_INVALID) {
        String fontName = config.getFontName();
        if (fontName == null) {
            fontName = textArea.getFont().getFamily();
        }
        int fontSize = config.getFontSize();
        if (fontSize == Configuration.FONT_SIZE_INVALID) {
            fontSize = textArea.getFont().getSize();
        }
        Font font = new Font(fontName, config.getFontStyle(), fontSize);
        textArea.setFont(font);
    }

    frame.pack();
    frame.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
    frame.setLocationByPlatform(true);
    splitPane.setDividerLocation(200);
    MainWindowStateBean state = localStorage.loadProperty("gui.state", MainWindowStateBean.class);
    if (state != null) {
        if (state.getBounds() != null) {
            frame.setBounds(state.getBounds());
            ResizeComponentListener.setBoundsProperty(frame, state.getBounds());
        }
        if (state.getDividerLocation() != null) {
            splitPane.setDividerLocation(state.getDividerLocation());
        }
        if (state.getState() != null) {
            frame.setExtendedState(state.getState());
        }
    }
    ResizeComponentListener.attachToWindow(frame);
    maybeStartServer();
}

From source file:org.sikuli.ide.SikuliIDE.java

private void initSikuliIDE(String[] args) {
    prefs = PreferencesUser.getInstance();
    if (prefs.getUserType() < 0) {
        prefs.setUserType(PreferencesUser.NEWBEE);
        prefs.setIdeSession("");
        prefs.setDefaults(prefs.getUserType());
    }/* w w w  . j av  a 2  s  . c  om*/

    ResourceLoader.get().check(Settings.SIKULI_LIB);

    _windowSize = prefs.getIdeSize();
    _windowLocation = prefs.getIdeLocation();
    Screen m = (Screen) (new Location(_windowLocation)).getScreen();
    if (m == null) {
        String em = "Remembered window not valid.\nGoing to primary screen";
        log(-1, em);
        Sikulix.popError(em, "IDE has problems ...");
        m = Screen.getPrimaryScreen();
        _windowSize.width = 0;
    }
    Rectangle s = m.getBounds();
    if (_windowSize.width == 0 || _windowSize.width > s.width || _windowSize.height > s.height) {
        if (s.width < 1025) {
            _windowSize = new Dimension(1024, 700);
            _windowLocation = new Point(0, 0);
        } else {
            _windowSize = new Dimension(s.width - 150, s.height - 100);
            _windowLocation = new Point(75, 0);
        }
    }
    setSize(_windowSize);
    setLocation(_windowLocation);

    Debug.log(3, "IDE: Adding components to window");
    initMenuBars(this);
    final Container c = getContentPane();
    c.setLayout(new BorderLayout());
    Debug.log(3, "IDE: creating tabbed editor");
    initTabPane();
    Debug.log(3, "IDE: creating message area");
    initMsgPane(prefs.getPrefMoreMessage() == PreferencesUser.HORIZONTAL);
    // RaiMan not used      initSidePane(); // IDE UnitTest

    Debug.log(3, "IDE: creating combined work window");
    JPanel codeAndUnitPane = new JPanel(new BorderLayout(10, 10));
    codeAndUnitPane.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 0));
    codeAndUnitPane.add(tabPane, BorderLayout.CENTER);
    // RaiMan not used      codeAndUnitPane.add(_sidePane, BorderLayout.EAST);
    if (prefs.getPrefMoreMessage() == PreferencesUser.VERTICAL) {
        _mainSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, codeAndUnitPane, msgPane);
    } else {
        _mainSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, codeAndUnitPane, msgPane);
    }
    _mainSplitPane.setResizeWeight(0.6);
    _mainSplitPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));

    Debug.log(3, "IDE: Putting all together");
    JPanel editPane = new JPanel(new BorderLayout(0, 0));

    JComponent cp = createCommandPane();

    if (PreferencesUser.getInstance().getPrefMoreCommandBar()) {
        editPane.add(cp, BorderLayout.WEST);
    }

    editPane.add(_mainSplitPane, BorderLayout.CENTER);
    c.add(editPane, BorderLayout.CENTER);

    JToolBar tb = initToolbar();
    c.add(tb, BorderLayout.NORTH); // the buttons

    c.add(initStatusbar(), BorderLayout.SOUTH);
    c.doLayout();

    initShortcutKeys();
    initHotkeys();
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    initWindowListener();
    initTooltip();

    autoCheckUpdate();

    _inited = true;
    try {
        getCurrentCodePane().requestFocus();
    } catch (Exception e) {
    }

    restoreSession(0);
    if (tabPane.getTabCount() == 0) {
        (new FileAction()).doNew(null);
    }
    tabPane.setSelectedIndex(0);

    Debug.log(3, "Sikuli-IDE startup: " + ((new Date()).getTime() - start));
    setVisible(true);
    _mainSplitPane.setDividerLocation(0.6);
    return; // as breakpoint
}

From source file:uk.ac.ebi.pride.tools.converter.gui.dialogs.SimplePTMDialog.java

private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
        // Generated using JFormDesigner non-commercial license
        cancelButton = new JButton();
        okButton = new JButton();
        scrollPane1 = new JScrollPane();
        ptmList = new JList();
        label1 = new JLabel();
        label2 = new JLabel();
        massDeltaTextField = new JTextField();
        ptmLabelTextField = new JTextField();
        label3 = new JLabel();
        olsButton = new JButton();

        //======== this ========
        setTitle("PTM Assignment");
        Container contentPane = getContentPane();

        //---- cancelButton ----
        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new ActionListener() {
            @Override/*  ww  w  .  ja  v a 2s . c  o  m*/
            public void actionPerformed(ActionEvent e) {
                cancelButtonActionPerformed();
            }
        });

        //---- okButton ----
        okButton.setText("OK");
        okButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                okButtonActionPerformed();
            }
        });

        //======== scrollPane1 ========
        {

            //---- ptmList ----
            ptmList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            ptmList.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    ptmListMouseClicked(e);
                }
            });
            scrollPane1.setViewportView(ptmList);
        }

        //---- label1 ----
        label1.setText("Label");

        //---- label2 ----
        label2.setText("Mass Delta");

        //---- massDeltaTextField ----
        massDeltaTextField.setEditable(false);

        //---- ptmLabelTextField ----
        ptmLabelTextField.setEditable(false);

        //---- label3 ----
        label3.setText("Suggested PTMs:");

        //---- olsButton ----
        olsButton.setText("Search OLS");
        olsButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                olsButtonActionPerformed();
            }
        });

        GroupLayout contentPaneLayout = new GroupLayout(contentPane);
        contentPane.setLayout(contentPaneLayout);
        contentPaneLayout.setHorizontalGroup(contentPaneLayout.createParallelGroup().addGroup(
                GroupLayout.Alignment.TRAILING,
                contentPaneLayout.createSequentialGroup().addContainerGap().addGroup(contentPaneLayout
                        .createParallelGroup(GroupLayout.Alignment.TRAILING)
                        .addComponent(scrollPane1, GroupLayout.Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 376,
                                Short.MAX_VALUE)
                        .addGroup(contentPaneLayout.createSequentialGroup().addComponent(olsButton)
                                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED, 94, Short.MAX_VALUE)
                                .addComponent(okButton, GroupLayout.PREFERRED_SIZE, 80, GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED).addComponent(cancelButton))
                        .addGroup(GroupLayout.Alignment.LEADING, contentPaneLayout.createSequentialGroup()
                                .addGroup(contentPaneLayout.createParallelGroup(GroupLayout.Alignment.TRAILING)
                                        .addComponent(label1).addComponent(label2))
                                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(contentPaneLayout.createParallelGroup()
                                        .addComponent(ptmLabelTextField, GroupLayout.DEFAULT_SIZE, 291,
                                                Short.MAX_VALUE)
                                        .addComponent(massDeltaTextField, GroupLayout.DEFAULT_SIZE, 291,
                                                Short.MAX_VALUE)))
                        .addComponent(label3, GroupLayout.Alignment.LEADING)).addContainerGap()));
        contentPaneLayout.setVerticalGroup(contentPaneLayout.createParallelGroup().addGroup(
                GroupLayout.Alignment.TRAILING,
                contentPaneLayout.createSequentialGroup().addContainerGap()
                        .addGroup(contentPaneLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                .addComponent(ptmLabelTextField, GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                                .addComponent(label1))
                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(contentPaneLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                .addComponent(label2).addComponent(massDeltaTextField, GroupLayout.PREFERRED_SIZE,
                                        GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED).addComponent(label3)
                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(scrollPane1, GroupLayout.DEFAULT_SIZE, 148, Short.MAX_VALUE)
                        .addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(contentPaneLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                                .addComponent(cancelButton).addComponent(okButton).addComponent(olsButton))
                        .addContainerGap()));
        pack();
        setLocationRelativeTo(getOwner());
        // JFormDesigner - End of component initialization  //GEN-END:initComponents
    }

From source file:com.maxl.java.amikodesk.AMiKoDesk.java

private static void createAndShowLightGUI() {
    // Create and setup window
    final JFrame jframe = new JFrame(Constants.APP_NAME);
    int min_width = CML_OPT_WIDTH;
    int min_height = CML_OPT_HEIGHT;

    jframe.setPreferredSize(new Dimension(min_width, min_height));
    jframe.setMinimumSize(new Dimension(min_width, min_height));
    Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (screen.width - min_width) / 2;
    int y = (screen.height - min_height) / 2;
    jframe.setBounds(x, y, min_width, min_height);

    // Action listeners
    jframe.addWindowListener(new WindowListener() {
        // Use WindowAdapter!
        @Override//from ww  w  . ja v a  2  s. co m
        public void windowOpened(WindowEvent e) {
        }

        @Override
        public void windowClosed(WindowEvent e) {
            m_web_panel.dispose();
            Runtime.getRuntime().exit(0);
        }

        @Override
        public void windowClosing(WindowEvent e) {
        }

        @Override
        public void windowIconified(WindowEvent e) {
        }

        @Override
        public void windowDeiconified(WindowEvent e) {
        }

        @Override
        public void windowActivated(WindowEvent e) {
        }

        @Override
        public void windowDeactivated(WindowEvent e) {
        }
    });

    // Container
    final Container container = jframe.getContentPane();
    container.setBackground(Color.WHITE);
    container.setLayout(new BorderLayout());

    // ==== Light panel ====
    JPanel light_panel = new JPanel();
    light_panel.setBackground(Color.WHITE);
    light_panel.setLayout(new GridBagLayout());

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.fill = GridBagConstraints.BOTH;
    gbc.anchor = GridBagConstraints.CENTER;
    gbc.insets = new Insets(2, 2, 2, 2);

    // ---- Section titles ----
    m_section_titles = null;
    if (Utilities.appLanguage().equals("de")) {
        m_section_titles = new IndexPanel(SectionTitle_DE);
    } else if (Utilities.appLanguage().equals("fr")) {
        m_section_titles = new IndexPanel(SectionTitle_FR);
    }
    gbc.fill = GridBagConstraints.BOTH;
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.gridwidth = 1;
    gbc.gridheight = 8;
    gbc.weightx = gbc.weighty = 0.0;
    // --> container.add(m_section_titles, gbc);
    if (m_section_titles != null)
        light_panel.add(m_section_titles, gbc);

    // ---- Fachinformation ----
    m_web_panel = new WebPanel2();
    gbc.fill = GridBagConstraints.BOTH;
    gbc.gridx = 1;
    gbc.gridy = 0;
    gbc.gridwidth = 3;
    gbc.gridheight = 20;
    gbc.weightx = 2.0;
    gbc.weighty = 1.0;
    gbc.anchor = GridBagConstraints.EAST;
    // --> container.add(m_web_panel, gbc);
    light_panel.add(m_web_panel, gbc);

    // ---- Add panel to main container ----
    container.add(light_panel, BorderLayout.CENTER);

    // Display window
    jframe.pack();
    // jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    jframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    // jframe.setAlwaysOnTop(true);
    jframe.setVisible(true);

    // If command line options are provided start app with a particular
    // title or eancode
    if (commandLineOptionsProvided()) {
        final JToggleButton but_dummy = new JToggleButton("dummy_button");
        if (!CML_OPT_TITLE.isEmpty())
            startAppWithTitle(but_dummy);
        else if (!CML_OPT_EANCODE.isEmpty())
            startAppWithEancode(but_dummy);
        else if (!CML_OPT_REGNR.isEmpty())
            startAppWithRegnr(but_dummy);
        else if (CML_OPT_SERVER == true) {
            // Start thread that reads data from TCP server
            Thread server_thread = new Thread() {
                public void run() {
                    while (true) {
                        String tcpServerInput = "";
                        // Wait until new data is available from input stream
                        // Note: the TCP client defines the update rate!
                        // System.out.print("Waiting for input...");
                        while ((tcpServerInput = mTcpServer.getInput()).isEmpty())
                            ;
                        /*
                         * Important note: we use invokeLater to post a "job" to Swing, which will then be run on the
                         * event dispatch thread at Swing's next convenience. Failing to do so will freeze the main thread.
                         */

                        // Detect type of search (t=title, e=eancode, r=regnr)
                        char typeOfSearch = tcpServerInput.charAt(0);
                        if (typeOfSearch == 't') {
                            // Extract title from received string
                            CML_OPT_TITLE = tcpServerInput.substring(2);
                            // System.out.println(" title -> " +
                            // CML_OPT_TITLE);
                            // Post a "job" to Swing, which will be run on
                            // the event dispatch thread
                            // at its next convenience.
                            SwingUtilities.invokeLater(new Runnable() {
                                public void run() {
                                    startAppWithTitle(but_dummy);
                                }
                            });
                        } else if (typeOfSearch == 'e') {
                            // Extract ean code from received string
                            CML_OPT_EANCODE = tcpServerInput.substring(2);
                            // System.out.println(" eancode -> " +
                            // CML_OPT_EANCODE);
                            // Post a "job" to Swing, which will be run on
                            // the event dispatch thread
                            // at its next convenience.
                            SwingUtilities.invokeLater(new Runnable() {
                                public void run() {
                                    startAppWithEancode(but_dummy);
                                }
                            });
                        } else if (typeOfSearch == 'r') {
                            // Extract registration number from received
                            // string
                            CML_OPT_REGNR = tcpServerInput.substring(2);
                            // System.out.println(" regnr -> " +
                            // CML_OPT_REGNR);
                            // Post a "job" to Swing, which will be run on
                            // the event dispatch thread
                            // at its next convenience.
                            SwingUtilities.invokeLater(new Runnable() {
                                public void run() {
                                    startAppWithRegnr(but_dummy);
                                }
                            });
                        }
                    }
                }
            };
            server_thread.start();
        }
    }
}

From source file:ffx.ui.MainPanel.java

/**
 * <p>/*from   w  w  w . ja  v a2s . co m*/
 * about</p>
 */
public void about() {
    if (aboutDialog == null) {
        aboutDialog = new JDialog(frame, "About... ", true);
        URL ffxURL = getClass().getClassLoader().getResource("ffx/ui/icons/splash.png");
        ImageIcon logoIcon = new ImageIcon(ffxURL);
        JLabel logoLabel = new JLabel(logoIcon);
        logoLabel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
        Container contentpane = aboutDialog.getContentPane();
        contentpane.setLayout(new BorderLayout());
        initAbout();
        contentpane.add(aboutTextArea, BorderLayout.SOUTH);
        contentpane.add(logoLabel, BorderLayout.CENTER);
        aboutDialog.pack();
        Dimension dim = getToolkit().getScreenSize();
        Dimension ddim = aboutDialog.getSize();
        aboutDialog.setLocation((dim.width - ddim.width) / 2, (dim.height - ddim.height) / 2);
        aboutDialog.setResizable(false);
    }
    aboutDialog.setVisible(true);
}

From source file:org.openmicroscopy.shoola.agents.imviewer.view.ImViewerUI.java

/** 
 * Re-attaches the viewer. /*w ww . j a  v  a 2 s  .  c om*/
 * This method should only be invoked when the image has been embedded
 * and detached.
 */
void rebuild() {
    if (component == null)
        return;
    //component.add(mainComponent, BorderLayout.CENTER);
    component.add(statusBar, BorderLayout.SOUTH);
    Container c = getContentPane();
    toolBar.setSeparateWindow();
    c.setLayout(new BorderLayout(0, 0));
    c.add(component, BorderLayout.CENTER);

}

From source file:org.apache.log4j.chainsaw.LogUI.java

/**
 * Activates itself as a viewer by configuring Size, and location of itself,
 * and configures the default Tabbed Pane elements with the correct layout,
 * table columns, and sets itself viewable.
 *//*ww w.j  a v a2s .com*/
public void activateViewer() {
    LoggerRepository repo = LogManager.getLoggerRepository();
    if (repo instanceof LoggerRepositoryEx) {
        this.pluginRegistry = ((LoggerRepositoryEx) repo).getPluginRegistry();
    }
    initGUI();

    initPrefModelListeners();

    /**
     * We add a simple appender to the MessageCenter logger
     * so that each message is displayed in the Status bar
     */
    MessageCenter.getInstance().getLogger().addAppender(new AppenderSkeleton() {
        protected void append(LoggingEvent event) {
            getStatusBar().setMessage(event.getMessage().toString());
        }

        public void close() {
        }

        public boolean requiresLayout() {
            return false;
        }
    });

    initSocketConnectionListener();

    if (pluginRegistry.getPlugins(Receiver.class).size() == 0) {
        noReceiversDefined = true;
    }

    getFilterableColumns().add(ChainsawConstants.LEVEL_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.LOGGER_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.THREAD_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.NDC_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.PROPERTIES_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.CLASS_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.METHOD_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.FILE_COL_NAME);
    getFilterableColumns().add(ChainsawConstants.NONE_COL_NAME);

    JPanel panePanel = new JPanel();
    panePanel.setLayout(new BorderLayout(2, 2));

    getContentPane().setLayout(new BorderLayout());

    getTabbedPane().addChangeListener(getToolBarAndMenus());
    getTabbedPane().addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            LogPanel thisLogPanel = getCurrentLogPanel();
            if (thisLogPanel != null) {
                thisLogPanel.updateStatusBar();
            }
        }
    });

    KeyStroke ksRight = KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,
            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());
    KeyStroke ksLeft = KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,
            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());
    KeyStroke ksGotoLine = KeyStroke.getKeyStroke(KeyEvent.VK_G,
            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask());

    getTabbedPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ksRight, "MoveRight");
    getTabbedPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ksLeft, "MoveLeft");
    getTabbedPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ksGotoLine, "GotoLine");

    Action moveRight = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            int temp = getTabbedPane().getSelectedIndex();
            ++temp;

            if (temp != getTabbedPane().getTabCount()) {
                getTabbedPane().setSelectedTab(temp);
            }
        }
    };

    Action moveLeft = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            int temp = getTabbedPane().getSelectedIndex();
            --temp;

            if (temp > -1) {
                getTabbedPane().setSelectedTab(temp);
            }
        }
    };

    Action gotoLine = new AbstractAction() {
        public void actionPerformed(ActionEvent e) {
            String inputLine = JOptionPane.showInputDialog(LogUI.this, "Enter the line number to go:",
                    "Goto Line", -1);
            try {
                int lineNumber = Integer.parseInt(inputLine);
                int row = getCurrentLogPanel().setSelectedEvent(lineNumber);
                if (row == -1) {
                    JOptionPane.showMessageDialog(LogUI.this, "You have entered an invalid line number",
                            "Error", 0);
                }
            } catch (NumberFormatException nfe) {
                JOptionPane.showMessageDialog(LogUI.this, "You have entered an invalid line number", "Error",
                        0);
            }
        }
    };

    getTabbedPane().getActionMap().put("MoveRight", moveRight);
    getTabbedPane().getActionMap().put("MoveLeft", moveLeft);
    getTabbedPane().getActionMap().put("GotoLine", gotoLine);

    /**
         * We listen for double clicks, and auto-undock currently selected Tab if
         * the mouse event location matches the currently selected tab
         */
    getTabbedPane().addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            super.mouseClicked(e);

            if ((e.getClickCount() > 1) && ((e.getModifiers() & InputEvent.BUTTON1_MASK) > 0)) {
                int tabIndex = getTabbedPane().getSelectedIndex();

                if ((tabIndex != -1) && (tabIndex == getTabbedPane().getSelectedIndex())) {
                    LogPanel logPanel = getCurrentLogPanel();

                    if (logPanel != null) {
                        logPanel.undock();
                    }
                }
            }
        }
    });

    panePanel.add(getTabbedPane());
    addWelcomePanel();

    getContentPane().add(toolbar, BorderLayout.NORTH);
    getContentPane().add(statusBar, BorderLayout.SOUTH);

    mainReceiverSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, panePanel, receiversPanel);
    dividerSize = mainReceiverSplitPane.getDividerSize();
    mainReceiverSplitPane.setDividerLocation(-1);

    getContentPane().add(mainReceiverSplitPane, BorderLayout.CENTER);

    /**
     * We need to make sure that all the internal GUI components have been added to the
     * JFrame so that any plugns that get activated during initPlugins(...) method
     * have access to inject menus  
     */
    initPlugins(pluginRegistry);

    mainReceiverSplitPane.setResizeWeight(1.0);
    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent event) {
            exit();
        }
    });
    preferencesFrame.setTitle("'Application-wide Preferences");
    preferencesFrame.setIconImage(((ImageIcon) ChainsawIcons.ICON_PREFERENCES).getImage());
    preferencesFrame.getContentPane().add(applicationPreferenceModelPanel);

    preferencesFrame.setSize(750, 520);

    Dimension screenDimension = Toolkit.getDefaultToolkit().getScreenSize();
    preferencesFrame.setLocation(new Point((screenDimension.width / 2) - (preferencesFrame.getSize().width / 2),
            (screenDimension.height / 2) - (preferencesFrame.getSize().height / 2)));

    pack();

    final JPopupMenu tabPopup = new JPopupMenu();
    final Action hideCurrentTabAction = new AbstractAction("Hide") {
        public void actionPerformed(ActionEvent e) {
            Component selectedComp = getTabbedPane().getSelectedComponent();
            if (selectedComp instanceof LogPanel) {
                displayPanel(getCurrentLogPanel().getIdentifier(), false);
                tbms.stateChange();
            } else {
                getTabbedPane().remove(selectedComp);
            }
        }
    };

    final Action hideOtherTabsAction = new AbstractAction("Hide Others") {
        public void actionPerformed(ActionEvent e) {
            Component selectedComp = getTabbedPane().getSelectedComponent();
            String currentName;
            if (selectedComp instanceof LogPanel) {
                currentName = getCurrentLogPanel().getIdentifier();
            } else if (selectedComp instanceof WelcomePanel) {
                currentName = ChainsawTabbedPane.WELCOME_TAB;
            } else {
                currentName = ChainsawTabbedPane.ZEROCONF;
            }

            int count = getTabbedPane().getTabCount();
            int index = 0;

            for (int i = 0; i < count; i++) {
                String name = getTabbedPane().getTitleAt(index);

                if (getPanelMap().keySet().contains(name) && !name.equals(currentName)) {
                    displayPanel(name, false);
                    tbms.stateChange();
                } else {
                    index++;
                }
            }
        }
    };

    Action showHiddenTabsAction = new AbstractAction("Show All Hidden") {
        public void actionPerformed(ActionEvent e) {
            for (Iterator iter = getPanels().entrySet().iterator(); iter.hasNext();) {
                Map.Entry entry = (Map.Entry) iter.next();
                Boolean docked = (Boolean) entry.getValue();
                if (docked.booleanValue()) {
                    String identifier = (String) entry.getKey();
                    int count = getTabbedPane().getTabCount();
                    boolean found = false;

                    for (int i = 0; i < count; i++) {
                        String name = getTabbedPane().getTitleAt(i);

                        if (name.equals(identifier)) {
                            found = true;

                            break;
                        }
                    }

                    if (!found) {
                        displayPanel(identifier, true);
                        tbms.stateChange();
                    }
                }
            }
        }
    };

    tabPopup.add(hideCurrentTabAction);
    tabPopup.add(hideOtherTabsAction);
    tabPopup.addSeparator();
    tabPopup.add(showHiddenTabsAction);

    final PopupListener tabPopupListener = new PopupListener(tabPopup);
    getTabbedPane().addMouseListener(tabPopupListener);

    this.handler.addPropertyChangeListener("dataRate", new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            double dataRate = ((Double) evt.getNewValue()).doubleValue();
            statusBar.setDataRate(dataRate);
        }
    });

    getSettingsManager().addSettingsListener(this);
    getSettingsManager().addSettingsListener(MRUFileListPreferenceSaver.getInstance());
    getSettingsManager().addSettingsListener(receiversPanel);
    try {
        //if an uncaught exception is thrown, allow the UI to continue to load
        getSettingsManager().loadSettings();
    } catch (Exception e) {
        e.printStackTrace();
    }
    //app preferences have already been loaded (and configuration url possibly set to blank if being overridden)
    //but we need a listener so the settings will be saved on exit (added after loadsettings was called)
    getSettingsManager().addSettingsListener(new ApplicationPreferenceModelSaver(applicationPreferenceModel));

    setVisible(true);

    if (applicationPreferenceModel.isReceivers()) {
        showReceiverPanel();
    } else {
        hideReceiverPanel();
    }

    removeSplash();

    synchronized (initializationLock) {
        isGUIFullyInitialized = true;
        initializationLock.notifyAll();
    }

    if (noReceiversDefined && applicationPreferenceModel.isShowNoReceiverWarning()) {
        SwingHelper.invokeOnEDT(new Runnable() {
            public void run() {
                showReceiverConfigurationPanel();
            }
        });
    }

    Container container = tutorialFrame.getContentPane();
    final JEditorPane tutorialArea = new JEditorPane();
    tutorialArea.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
    tutorialArea.setEditable(false);
    container.setLayout(new BorderLayout());

    try {
        tutorialArea.setPage(ChainsawConstants.TUTORIAL_URL);
        JTextComponentFormatter.applySystemFontAndSize(tutorialArea);

        container.add(new JScrollPane(tutorialArea), BorderLayout.CENTER);
    } catch (Exception e) {
        MessageCenter.getInstance().getLogger().error("Error occurred loading the Tutorial", e);
    }

    tutorialFrame.setIconImage(new ImageIcon(ChainsawIcons.HELP).getImage());
    tutorialFrame.setSize(new Dimension(640, 480));

    final Action startTutorial = new AbstractAction("Start Tutorial",
            new ImageIcon(ChainsawIcons.ICON_RESUME_RECEIVER)) {
        public void actionPerformed(ActionEvent e) {
            if (JOptionPane.showConfirmDialog(null,
                    "This will start 3 \"Generator\" receivers for use in the Tutorial.  Is that ok?",
                    "Confirm", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                new Thread(new Tutorial()).start();
                putValue("TutorialStarted", Boolean.TRUE);
            } else {
                putValue("TutorialStarted", Boolean.FALSE);
            }
        }
    };

    final Action stopTutorial = new AbstractAction("Stop Tutorial",
            new ImageIcon(ChainsawIcons.ICON_STOP_RECEIVER)) {
        public void actionPerformed(ActionEvent e) {
            if (JOptionPane.showConfirmDialog(null,
                    "This will stop all of the \"Generator\" receivers used in the Tutorial, but leave any other Receiver untouched.  Is that ok?",
                    "Confirm", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                new Thread(new Runnable() {
                    public void run() {
                        LoggerRepository repo = LogManager.getLoggerRepository();
                        if (repo instanceof LoggerRepositoryEx) {
                            PluginRegistry pluginRegistry = ((LoggerRepositoryEx) repo).getPluginRegistry();
                            List list = pluginRegistry.getPlugins(Generator.class);

                            for (Iterator iter = list.iterator(); iter.hasNext();) {
                                Plugin plugin = (Plugin) iter.next();
                                pluginRegistry.stopPlugin(plugin.getName());
                            }
                        }
                    }
                }).start();
                setEnabled(false);
                startTutorial.putValue("TutorialStarted", Boolean.FALSE);
            }
        }
    };

    stopTutorial.putValue(Action.SHORT_DESCRIPTION,
            "Removes all of the Tutorials Generator Receivers, leaving all other Receivers untouched");
    startTutorial.putValue(Action.SHORT_DESCRIPTION,
            "Begins the Tutorial, starting up some Generator Receivers so you can see Chainsaw in action");
    stopTutorial.setEnabled(false);

    final SmallToggleButton startButton = new SmallToggleButton(startTutorial);
    PropertyChangeListener pcl = new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            stopTutorial.setEnabled(((Boolean) startTutorial.getValue("TutorialStarted")).equals(Boolean.TRUE));
            startButton.setSelected(stopTutorial.isEnabled());
        }
    };

    startTutorial.addPropertyChangeListener(pcl);
    stopTutorial.addPropertyChangeListener(pcl);

    pluginRegistry.addPluginListener(new PluginListener() {
        public void pluginStarted(PluginEvent e) {
        }

        public void pluginStopped(PluginEvent e) {
            List list = pluginRegistry.getPlugins(Generator.class);

            if (list.size() == 0) {
                startTutorial.putValue("TutorialStarted", Boolean.FALSE);
            }
        }
    });

    final SmallButton stopButton = new SmallButton(stopTutorial);

    final JToolBar tutorialToolbar = new JToolBar();
    tutorialToolbar.setFloatable(false);
    tutorialToolbar.add(startButton);
    tutorialToolbar.add(stopButton);
    container.add(tutorialToolbar, BorderLayout.NORTH);
    tutorialArea.addHyperlinkListener(new HyperlinkListener() {
        public void hyperlinkUpdate(HyperlinkEvent e) {
            if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
                if (e.getDescription().equals("StartTutorial")) {
                    startTutorial.actionPerformed(null);
                } else if (e.getDescription().equals("StopTutorial")) {
                    stopTutorial.actionPerformed(null);
                } else {
                    try {
                        tutorialArea.setPage(e.getURL());
                    } catch (IOException e1) {
                        MessageCenter.getInstance().getLogger()
                                .error("Failed to change the URL for the Tutorial", e1);
                    }
                }
            }
        }
    });

    /**
     * loads the saved tab settings and if there are hidden tabs,
     * hide those tabs out of currently loaded tabs..
     */

    if (!getTabbedPane().tabSetting.isWelcome()) {
        displayPanel(ChainsawTabbedPane.WELCOME_TAB, false);
    }
    if (!getTabbedPane().tabSetting.isZeroconf()) {
        displayPanel(ChainsawTabbedPane.ZEROCONF, false);
    }
    tbms.stateChange();

}

From source file:org.openmicroscopy.shoola.agents.imviewer.view.ImViewerUI.java

/** Builds and lays out the GUI. */
private void buildGUI() {
    Browser browser = model.getBrowser();
    int sizeX = model.getTiledImageSizeX();
    int sizeY = model.getTiledImageSizeY();

    browser.setComponentsSize(sizeX, sizeY);
    tabs = new ClosableTabbedPane(JTabbedPane.TOP, JTabbedPane.WRAP_TAB_LAYOUT);
    tabs.setAlignmentX(LEFT_ALIGNMENT);/*w  w w  .ja v a 2  s  .c  o m*/

    viewPanel = new ClosableTabbedPaneComponent(ImViewer.VIEW_INDEX, browser.getTitle(), browser.getIcon(), "");
    viewPanel.setClosable(false);
    double[][] tl = { { TableLayout.PREFERRED, TableLayout.FILL },
            { TableLayout.FILL, TableLayout.PREFERRED, TableLayout.PREFERRED } };
    viewPanel.setLayout(new TableLayout(tl));
    viewPanel.add(controlPane, "0, 0");
    viewPanel.add(browser.getUI(), "1, 0");
    viewPanel.add(controlPane.getTimeSliderPane(ImViewer.VIEW_INDEX), "1, 1");
    if (model.isLifetimeImage()) {
        viewPanel.add(controlPane.getLifetimeSliderPane(ImViewer.VIEW_INDEX), "1, 2");
    }
    tabbedIconHeight = browser.getIcon().getIconHeight() + ICON_EXTRA;

    tabs.insertTab(browser.getTitle(), browser.getIcon(), viewPanel, "", ImViewer.VIEW_INDEX);
    gridViewPanel = new ClosableTabbedPaneComponent(ImViewer.GRID_INDEX, browser.getGridViewTitle(),
            browser.getGridViewIcon(), "");
    gridViewPanel.setLayout(new TableLayout(tl));

    gridViewPanel.add(controlPane.buildGridComponent(), "0, 0");
    gridViewPanel.add(browser.getGridView(), "1, 0");
    gridViewPanel.add(controlPane.getTimeSliderPane(ImViewer.GRID_INDEX), "1, 1");
    if (model.isLifetimeImage()) {
        gridViewPanel.add(controlPane.getLifetimeSliderPane(ImViewer.GRID_INDEX), "1, 2");
    }
    if (model.allowSplitView() && !model.isBigImage()) {
        tabs.insertTab(browser.getGridViewTitle(), browser.getGridViewIcon(), gridViewPanel, "",
                ImViewer.GRID_INDEX);
    }

    double[][] tl2 = { { TableLayout.PREFERRED, TableLayout.FILL },
            { TableLayout.PREFERRED, TableLayout.FILL, TableLayout.PREFERRED } };

    projectionViewPanel = new ClosableTabbedPaneComponent(ImViewer.PROJECTION_INDEX,
            browser.getProjectionViewTitle(), browser.getProjectionViewIcon(), "");

    projectionViewPanel.setLayout(new TableLayout(tl2));
    projectionViewPanel.add(controlPane.buildProjectionToolBar(), "0, 0, 1, 0");
    projectionViewPanel.add(controlPane.buildProjectionComponent(), "0, 1");
    projectionViewPanel.add(browser.getProjectionView(), "1, 1");
    projectionViewPanel.add(controlPane.getTimeSliderPane(ImViewer.PROJECTION_INDEX), "1, 2");
    if (model.getMaxZ() > 0 && !model.isBigImage()) {
        tabs.insertTab(browser.getProjectionViewTitle(), browser.getProjectionViewIcon(), projectionViewPanel,
                "", ImViewer.PROJECTION_INDEX);
    }

    tabs.addChangeListener(controller);

    //mainComponent = tabs;
    rendererSplit.setLeftComponent(tabs);
    mainComponent = rendererSplit;

    Container container = getContentPane();
    container.setLayout(new BorderLayout(0, 0));
    container.add(toolBar, BorderLayout.NORTH);
    container.add(mainComponent, BorderLayout.CENTER);
    container.add(statusBar, BorderLayout.SOUTH);

    //attach listener to the frame border
    boundsAdapter = new HierarchyBoundsAdapter() {

        /**
         * Stores the size of the tab pane when the frame is resized.
         * @see HierarchyBoundsListener#ancestorResized(HierarchyEvent)
         */
        public void ancestorResized(HierarchyEvent e) {
            if (tabs != null)
                restoreSize = tabs.getSize();
        }
    };
    container.addHierarchyBoundsListener(boundsAdapter);
    //restoreSize = new Dimension(0, 0);
    //layoutComponents(false);
}