Как отслеживать мои внутренние кадры?

Этот пример кода является короткой версией моей реальной программы:

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.*;


public class Example extends JFrame {

private JPanel contentPane;
private JTable table;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                Example frame = new Example();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public Example() {
    //what to do @ close
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 792, 585);

    //content pane
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    contentPane.setLayout(new BorderLayout(0, 0));
    setContentPane(contentPane);

    //create desktop pane add it to content pane
    final JDesktopPane desktopPane = new JDesktopPane();
    contentPane.add(desktopPane, BorderLayout.CENTER);

    //create Int Frame with table
    JInternalFrame tableIntFrame = new JInternalFrame("TableIntFrame");
    tableIntFrame.setBounds(31, 29, 300, 205);
    desktopPane.add(tableIntFrame);

    //create the table
    table = new JTable();

    table.setFillsViewportHeight(true);
    table.setModel(new DefaultTableModel(
        new Object[][] {
            {"Row 0 (click for more info)"},
            {"Row 1 (click for more info)"},
        },
        new String[] {
            "Collumn 0"
        }
    ));

    //add the table to a ScrollPane
    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setViewportView(table);
    //add Scrollpane to table       
    tableIntFrame.getContentPane().add(scrollPane, BorderLayout.CENTER);
    tableIntFrame.setVisible(true);

    //Listen for events on selection
    table.getSelectionModel().addListSelectionListener(new
            ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e) {

            // only fires ones
            if (! e.getValueIsAdjusting())
            { 
                //create info frame with title set to selectedrow index
                createFrame(desktopPane, table.getSelectedRow()+"");

            }

        }
    });
    // Allow only one row to be selected.
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);



}

//Creates an int frame with the title set to the row
private void createFrame(JDesktopPane desktopPane, String selectedRow){

    JInternalFrame InfoIntFrame = new JInternalFrame("Info Row "+selectedRow);
    InfoIntFrame.setBounds(425, 44, 183, 72);
    //add to desktop
    desktopPane.add(InfoIntFrame);
    //set visible
    InfoIntFrame.setVisible(true);
    }
}

Как мне заставить его работать, чтобы щелчок по строке, когда соответствующий infoIntFrame уже открыт, не создавал другой экземпляр infoIntframe? (примечание: infoIntFrames должны быть созданы во время выполнения)


person Arjhun    schedule 09.02.2012    source источник
comment
Вы не будете создавать новый FrameListIntFrame после первого, потому что вы проверяете, чтобы убедиться, что он не равен нулю. Похоже, вы вводите это выражение if только один раз.   -  person Dodd10x    schedule 10.02.2012
comment
это может быть хороший вопрос, отредактируйте свое сообщение, указав sscce.org.   -  person mKorbel    schedule 10.02.2012
comment
В этом ответе приводится пример, в котором Action используется для отслеживания нескольких внутренних фреймов.   -  person trashgod    schedule 10.02.2012
comment
@mKorbel Я отредактировал свой вопрос. Я добавил простой пример проблемы. Надеюсь это поможет!   -  person Arjhun    schedule 10.02.2012


Ответы (1)


есть две области:

1) JInternalFrame tableIntFrame = new JInternalFrame("TableIntFrame"); потерял Фокус

2) вы должны проверить, существует ли массив, который возвращает desktopPane.getAllFrames() перед созданием нового JInternalFrame, добавьте InternalFrameListener, потому что (насколько я знаю ) метод desktopPane.getAllFrames() возвращает только видимые JInternalFrame

person mKorbel    schedule 10.02.2012