2013-05-24 32 views
16

私はSQLデータベースを持っており、レコードの追加/削除/修正を可能にするプログラムに取り組んでいます。編集/削除を行っているレコードを既に追加しています。jTable右クリックポップアップメニュー

テーブルに既存のレコードを表示して、jTableを使用したいとします。私はいくつかのコードをオンラインで見つけ、レコードをプルしてjtableに表示するように修正しましたが、右クリックをコーディングしてポップアップメニューを表示する方法はわかりません。

このポップアップメニューでは、レコードの削除やレコードの変更などのオプションを表示したいと考えています。

private void menuDeleteAuthorActionPerformed(java.awt.event.ActionEvent evt) {             
    TableFromDatabase deleteAuthor = new TableFromDatabase(); 
    deleteAuthor.pack(); 
    deleteAuthor.setVisible(true); 

    Vector columnNames = new Vector(); 
    Vector data = new Vector(); 

    try 
    { 

     Connection connection = DriverManager.getConnection(url, user, password); 

     // Read data from a table 

     String sql = "SELECT * FROM Authors"; 
     Statement stmt = connection.createStatement(); 
     ResultSet rs = stmt.executeQuery(sql); 
     ResultSetMetaData md = rs.getMetaData(); 
     int columns = md.getColumnCount(); 

     // Get column names 

     for (int i = 1; i <= columns; i++) 
     { 
      columnNames.addElement(md.getColumnName(i)); 
     } 

     // Get row data 

     while (rs.next()) 
     { 
      Vector row = new Vector(columns); 

      for (int i = 1; i <= columns; i++) 
      { 
       row.addElement(rs.getObject(i)); 
      } 

      data.addElement(row); 
     } 

     rs.close(); 
     stmt.close(); 
     connection.close(); 
    } 
    catch(Exception e) 
    { 
     System.out.println(e); 
    } 

    // Create table with database data 

    JTable table = new JTable(data, columnNames) 
    { 
     public Class getColumnClass(int column) 
     { 
      for (int row = 0; row < getRowCount(); row++) 
      { 
       Object o = getValueAt(row, column); 

       if (o != null) 
       { 
        return o.getClass(); 
       } 
      } 

      return Object.class; 
     } 
    }; 

    JScrollPane scrollPane = new JScrollPane(table); 
    getContentPane().add(scrollPane); 

    JPanel buttonPanel = new JPanel(); 
    getContentPane().add(buttonPanel, BorderLayout.SOUTH); 
} 

私は、Javaに新しいですので、あなたの回答に親切にしてください。

これは私がJTableのを作成し、データを表示する使用していたコードです。ご協力いただきありがとうございます。

+0

に応じて、[JComponentの#setComponentPopup](http://docs.oracle.com/javase/7/docs/api/javax/swing/JComponent.html#setComponentPopupMenu(javaxのを見てみましょう.swing.JPopupMenu)) – MadProgrammer

+0

この解決策(ここではまだリンクされていない同様の質問)は、 me:http://stackoverflow.com/a/17316876/411282 –

答えて

28

これを行う方法の例を以下に示します。これを達成する最も簡単な方法は、JPopupMenuをJTableに直接設定することです。あなたは自動的に右クリックが行われた行を選択したい場合には

import java.awt.BorderLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.util.Arrays; 
import java.util.Vector; 

import javax.swing.JFrame; 
import javax.swing.JMenuItem; 
import javax.swing.JOptionPane; 
import javax.swing.JPopupMenu; 
import javax.swing.JScrollPane; 
import javax.swing.JTable; 
import javax.swing.SwingUtilities; 

public class TestTableRightClick { 

    protected void initUI() { 
     final JFrame frame = new JFrame(TestTableRightClick.class.getSimpleName()); 
     Vector<String> columns = new Vector<String>(Arrays.asList("Name", "Age")); 
     Vector<Vector<String>> data = new Vector<Vector<String>>(); 
     for (int i = 0; i < 50; i++) { 
      Vector<String> row = new Vector<String>(); 
      for (int j = 0; j < columns.size(); j++) { 
       row.add("Cell " + (i + 1) + "," + (j + 1)); 
      } 
      data.add(row); 
     } 
     final JTable table = new JTable(data, columns); 
     final JPopupMenu popupMenu = new JPopupMenu(); 
     JMenuItem deleteItem = new JMenuItem("Delete"); 
     deleteItem.addActionListener(new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent e) { 
       JOptionPane.showMessageDialog(frame, "Right-click performed on table and choose DELETE"); 
      } 
     }); 
     popupMenu.add(deleteItem); 
     table.setComponentPopupMenu(popupMenu); 
     frame.add(new JScrollPane(table), BorderLayout.CENTER); 
     frame.pack(); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       new TestTableRightClick().initUI(); 
      } 
     }); 
    } 
} 

、次のスニペットを追加:JTableのに問題が右クリックが変化しないということである

popupMenu.addPopupMenuListener(new PopupMenuListener() { 

      @Override 
      public void popupMenuWillBecomeVisible(PopupMenuEvent e) { 
       SwingUtilities.invokeLater(new Runnable() { 
        @Override 
        public void run() { 
         int rowAtPoint = table.rowAtPoint(SwingUtilities.convertPoint(popupMenu, new Point(0, 0), table)); 
         if (rowAtPoint > -1) { 
          table.setRowSelectionInterval(rowAtPoint, rowAtPoint); 
         } 
        } 
       }); 
      } 

      @Override 
      public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { 
       // TODO Auto-generated method stub 

      } 

      @Override 
      public void popupMenuCanceled(PopupMenuEvent e) { 
       // TODO Auto-generated method stub 

      } 
     }); 
+1

+1、setComponentPopupMenu()を使用しているため、MouseListenerの作成について心配する必要はありません。 – camickr

+0

この実装では、ユーザーが右クリックしたレコードに関する情報が失われているため、この問題は解決されません。 (どちらを削除/修正しますか?テーブルのどこに追加しますか?) –

+0

@JoshuaGoldbergこれで何をしたいのかはあなた次第です。通常、私は削除が選択された行で発生し、おそらく現在選択されている行の後に挿入されると推測します。右クリックが必ずしもJTableの行を選択しないという事実は、L&F依存である。必要に応じて、右クリックで行選択を変更するMouseListenerを追加することで、強制することもできます。この実装は問題の問題を解決します。 –

14

を行の選択。したがって、特定の行で動作するアクションがある場合は、右クリックしてポップアップメニューを表示させる前に行を最初に左クリックする必要があります。

その後、あなたは次のようなコードを使用することができますどこ右クリックし、[行を選択したい場合:

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class TableRightClick extends JFrame implements ActionListener 
{ 
    JPopupMenu popup; 

    public TableRightClick() 
    { 
     popup = new JPopupMenu(); 
     popup.add(new JMenuItem("Do Something1")); 
     popup.add(new JMenuItem("Do Something2")); 
     popup.add(new JMenuItem("Do Something3")); 
     JMenuItem menuItem = new JMenuItem("ActionPerformed"); 
     menuItem.addActionListener(this); 
     popup.add(menuItem); 

     JTable table = new JTable(50, 5); 
     table.addMouseListener(new MouseAdapter() 
     { 
      public void mousePressed(MouseEvent e) 
      { 
       System.out.println("pressed"); 
      } 

      public void mouseReleased(MouseEvent e) 
      { 
       if (e.isPopupTrigger()) 
       { 
        JTable source = (JTable)e.getSource(); 
        int row = source.rowAtPoint(e.getPoint()); 
        int column = source.columnAtPoint(e.getPoint()); 

        if (! source.isRowSelected(row)) 
         source.changeSelection(row, column, false, false); 

        popup.show(e.getComponent(), e.getX(), e.getY()); 
       } 
      } 
     }); 
     table.setPreferredScrollableViewportSize(table.getPreferredSize()); 
     getContentPane().add(new JScrollPane(table)); 
    } 

    public void actionPerformed(ActionEvent e) 
    { 
     Component c = (Component)e.getSource(); 
     JPopupMenu popup = (JPopupMenu)c.getParent(); 
     JTable table = (JTable)popup.getInvoker(); 
     System.out.println(table.getSelectedRow() + " : " + table.getSelectedColumn()); 
    } 

    public static void main(String[] args) 
    { 
     TableRightClick frame = new TableRightClick(); 
     frame.setDefaultCloseOperation(EXIT_ON_CLOSE); 
     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 
} 
0

別の問題は、コンテキストメニューがダイナミクスあり、あなたのソリューションは、メニューの変更に対処していないということですクリックされた行

popupMenu.addPopupMenuListener(new PopupMenuListener() 
    { 
     @Override 
     public void popupMenuWillBecomeVisible(PopupMenuEvent e) // juste pour selectionner la row quant on right click, putain de swing de merde 
     { 
      int rowAtPoint = table.rowAtPoint(SwingUtilities.convertPoint(popupMenu, new Point(0, 0), table)); 
      generateTablePopupMenu(rowAtPoint); <<<<<<<<<<<< here 
      SwingUtilities.invokeLater(new Runnable() 
      ...