Click a row in a JTable and display the function implementation of corresponding content in another JPanel.

Source: Internet
Author: User
Tags rows count

Click a row in a JTable and display the function implementation of corresponding content in another JPanel.

For example, the goal is to display the last int data of the selected row in the yellow box of the GUI when I click a JTable row (the JTable content comes from the file on the left.

I would like to briefly explain why I wrote this article: I encountered a lot of meaningful difficulties in the function implementation process, which was not mentioned by the teacher in the class. I will list them one by one.

Problem 1: the first problem I encountered was that I was not familiar with the ListSelectionListener usage, but did not know the ListSelectionModel usage. I thought the ListSelectionModel was a dispensable choice (I am sorry to say it is still mentioned ).

Here we will talk about the setting method of ListSelectionModel. First, we will dig out the selectionMode from the table, add the ListSelectionListener to the selectionMode, and then set it. (In my own version, only one choice is allowed:

selectionMode = table.getSelectionModel();selectionMode.addListSelectionListener(this);selectionMode.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

Problem 2: After solving the first problem, my code looks like this:

Public class Main_panel extends JPanel {
Private Research_and_InfoPanel research_and_infoPanel; private JScrollPane scrollpane; private ListSelectionModel listSelectionModel; Main_panel () {super (); BoxLayout main_layout = new BoxLayout (this, BoxLayout. x_AXIS); setLayout (main_layout); // creation panels research_and_infoPanel = new Research_and_InfoPanel (); // database for TablePanel Vector <String> column_names = new Vector <String> (); column_names.add ("Title"); column_names.add ("Author"); column_names.add ("Year"); column_names.add ("Path "); vector <Object> data = new Vector <Object> (); data = proof_main.libreria.merge_table_elements (); // define JTable table = new JTable (data, column_names ); // define Jscrollpane that contain the table scrollpane = new JScrollPane (table, ScrollPaneConstants. VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants. HORIZONTAL_SCROLLBAR_AS_NEEDED); listSelectionModel = table. getSelectionModel (); listSelectionModel. addListSelectionListener (new SelectionListener (); scrollpane. setPreferredSize (new Dimension (450,550); research_and_infoPanel.setPreferredSize (new Dimension (250,550); add (scrollpane); add (research_and_infoPanel );} class SelectionListener implements ListSelectionListener {public void valueChanged (ListSelectionEvent e) {// TODO Auto-generated method stub int selectedRow = table. getSelectedRow (); String title = (String) table. getValueAt (selectedRow, 1); // research_and_infoPanel.displayInfo (selectedRow, title); <-- this is the function I want to call in the future. It belongs to research_and_infoPanel, which is a yellow box }}}

  

As you can see, my JTable, JScrollPanel, ListSelectionListener, and their valueChanged functions are all in Main_Panel, which is a bit confusing. Therefore, I want to separate Main_Panel and other elements, A new JScrollPanel subclass is created, and a new page is displayed. The effect is as follows:

public class myScrollPane extends JScrollPane implements ListSelectionListener {  private JTable table;  private ListSelectionModel selectionMode;  myScrollPane(){    super();    //database for table    Vector<String> column_names = new Vector<String>();    column_names.add("Title");    column_names.add("Author");    column_names.add("Year");    column_names.add("Path");    Vector<Object> data = new Vector<Object>();    data = proof_main.libreria.merge_table_elements();    //define JTable and add it in scrollpane    table = new JTable(data,column_names);    setViewportView(table);    //set scrollpane    setVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_ALWAYS);    setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_AS_NEEDED);    //set selectionMode and add Listener 
    selectionMode = table.getSelectionModel();    selectionMode.addListSelectionListener(this);    selectionMode.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);}public void valueChanged(ListSelectionEvent e) {  //rows count from zero  int selectedRow = table.getSelectedRow();  selectedRow++;  Main_panel.research_and_infoPanel.displayInfo(selectedRow);  }}

I remember a problem that I wasted a lot of time due to ignorance, that is, 16 rows. I naively thought that as long as I use add (table), The result Table cannot be displayed, after reading the manual carefully, we found that setViewportview (table) is required ).

OK. In general, the research_and_infoPanel.displayInfo (selectedRow) function is much refreshed and more neat. Next, let's take a look at how this function works.

Public class Research_and_InfoPanel extends JPanel {private JPanel research_panel, info_panel; private JLabel label1; Research_and_InfoPanel () {research_panel = new JPanel (); info_panel = new JPanel (); research_panel.setMaximumSize (new Dimension (250,500); info_panel.setMaximumSize (new Dimension (250,500); research_panel.setBackground (Color. gray); info_panel.setBackground (Color. yellow); BoxLayout secondary_layout = new BoxLayout (this, BoxLayout. y_AXIS); setLayout (secondary_layout); label1 = new JLabel (); info_panel.add (label1); add (research_panel); add (info_panel);} public void displayInfo (int numberRow) {char filetype = numeric (numberRow); Vector <Object> extra_info = proof_main.libreria.get_info (filetype, numberRow); switch (filetype) {case 'E': {label1.setText (extra_info.get (0 ). toString ();} break; case 'M': {label1.setText (extra_info.get (0 ). toString ();} break; case 'V': {label1.setText (extra_info.get (0 ). toString () ;}break ;}// The following is libreria. get_info (filetype, numberRow) function content public Vector <Object> get_info (char filetype, int number) {Vector <Object> extra_info = new Vector <Object> (); extra_info.clear (); int bound_E = record_E.media_files.size (); int bound_M = bound_E + record_M.media_files.size (); switch (filetype) {case 'E': {extra_info.addElement (limit (number-1 ). get_n_pages ();} break; case 'M': {number = number-bound_E; extra_info.addElement (record_M.media_files.get (number-1 ). get_duration (); extra_info.addElement (record_M.media_files.get (number-1 ). get_sample_rate ();} break; case 'V': {number = number-bound_M; extra_info.addElement (record_V.media_files.get (number-1 ). get_duration ();} break;} return extra_info ;}

The above code is divided into two parts. The first part is the Research_and_InfoPanel class, which has a JLabel. Therefore, the name has two panels, but this is not our focus. The key is the code in displayInfo, this is because the number is dug out.
We can see that the extracted data is provided by proof_main.libreria.get_info (filetype, numberRow). Here we mention that I have three different types of files, E, V, and M. Readers can ignore this. NumberRow is the row selected by the mouse or keyboard. In the previous example, we used table. getSelectedRow to dig out the row and pass it to libreria. get_info ().
In this article, I will not provide any other codes without any important contact, but I need to explain that the load () function is responsible for reading numbers from the file and loading them into record_E.media_files, record_M.media_files, and record_V.media_files, as you can imagine, rows 60, 62, and 68 correspond to numbers (in the first image, the corresponding number is 30 ).



I will give the load () function in the future.
 

Display jtable in jpanel

// Write a complete small example for you ~~ Check it out

Import java. awt. BorderLayout;
Import java. awt. event. ActionEvent;
Import java. awt. event. ActionListener;
Import javax. swing .*;
Import javax. swing. table. DefaultTableModel;

Public class TableTest implements ActionListener {

JFrame frame = new JFrame ("JTable Test ");
JButton button = new JButton ("add ");
JTextField fname = new JTextField (20 );
JTextField lname = new JTextField (20 );
JPanel north = new JPanel ();
JLabel l1 = new JLabel ("name ");
JLabel l2 = new JLabel ("contact information ");
DefaultTableModel dtm = new DefaultTableModel (0, 2 );
JTable table = new JTable (dtm );
JScrollPane jsp = new JScrollPane (table );
String [] temp = new String [2];

Public void init (){
Frame. setBounds (200,200,640,480 );
Frame. setLayout (new BorderLayout ());
Frame. setdefaclocloseoperation (JFrame. EXIT_ON_CLOSE );
Frame. setResizable (false );
North. add (l1 );
North. add (fname );
North. add (l2 );
North. add (lname );
Button. addActionListener (this );
North. add (button );
Dtm. setColumnIdentifiers (new String [] {"name", "Contact Info "});
Frame. add (north, BorderLayout. NORTH );
Frame. add (jsp, BorderLayout. CENTER );
Frame. setVisible (true );
}

Public static void main (String [] args ){
TableTest tt = new TableTest ();
Tt. init ();
}

Public void actionreceivmed (ActionEvent e ){
Temp [0] = fname. getText ();
Temp [1] = lname. getText ();
Dtm. insertRow (dtm. getRowCount (), temp );
}

}... Remaining full text>

Place the JPanel component in the JTable cell in Swing Development

// First send QQ: 7706189
// Editor. I have JTextField and JButton on JPanel.
Public class TextCellEditor extends javax. swing. AbstractCellEditor implements
Javax. swing. table. TableCellEditor {
Private JDialog parent;
Private JPanel editPanel;
Private JTextField editText;
Private JButton editButton;
Public TextCellEditor (JDialog d ){
This. parent = d;
EditPanel = new javax. swing. JPanel ();
EditButton = new javax. swing. JButton ();
EditText = new javax. swing. JTextField ();
EditButton. setText ("*");
EditButton. addActionListener (new ActionListener (){
Public void actionreceivmed (ActionEvent e ){
New GlossarySortDialog (parent, editText). setVisible (true );

}
});
EditPanel. setLayout (new BorderLayout ());
EditPanel. add (editText, BorderLayout. CENTER );
EditPanel. add (editButton, BorderLayout. EAST );
}
Public Object getCellEditorValue (){
Return editText. getText ();
}
// Important: This method returns the JPanel Editor (including other controls on the JPanel)
Public java. awt. Component getTableCellEditorComponent (
Javax. swing. JTable table, Object value, boolean isSelected,
Int row, int column ){
If (value = null)
EditText. setText ("");
Else
EditText. set... the remaining full text>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.