This example code is a short version of my actual program:
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);
}
}
How do I get it to work for that clicking a row when it's corresponding infoIntFrame is already open doesn't create another instance of infoIntframe? (note: The infoIntFrames have to be created at runtime)
there are two areas:
1) JInternalFrame tableIntFrame = new JInternalFrame("TableIntFrame");
lost Focus
2) you have to check if exist in array that returns desktopPane.getAllFrames() before creating new another JInternalFrame, add InternalFrameListener, because (AFAIK) method desktopPane.getAllFrames() returns only visible JInternalFrame