如何区分两个同名的JButton

时间:2015-08-19 15:31:42

标签: java swing awt

我正在开发一个swing应用程序,我需要删除按钮。单击每个删除按钮最终将根据单击的按钮从不同的文件中删除行。问题是我无法通过名称区分这两个按钮,因为它们都具有相同的名称和#34;删除"。我不想以不同的方式命名它们,因为我可能有很多这样的删除按钮。是否有其他属性,如ID或我可以分配给他们的东西?

3 个答案:

答案 0 :(得分:2)

避免使用“switchboard”侦听器,而是为每个JButton提供自己的Action对象,一个通过重写AbstractAction创建。 AbstractAction甚至可以是同一个类的对象,但它也引用了感兴趣的文件或字符串集合,以便对正确的项目执行删除操作。

另一种选择是通过wpRow.addDeleteListener(new DeleteAction(container, wpRow)); 将按钮与需要对其进行操作的对象相关联。

以下两个示例合并为一个程序。右边的JPanel包含多个单词对和一个删除JButton,JButton与包含单词对的JLabel密切相关,因为它们都保存在一个公共对象WordPairRow中。每个删除JButton都会添加一个ActionListener类,但会传递唯一的WordPairRow和容纳所有组件的容器JPanel:

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.*;
import java.io.InputStream;
import java.util.Scanner;
import java.util.Vector;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

@SuppressWarnings("serial")
public class WordPairTest extends JPanel {
    private static final String DATA_FILE_NAME = "WordPair.txt";
    private JPanel wordListPanel = new JPanel(new GridBagLayout());
    private WordPairTableModel tableModel = new WordPairTableModel();
    private JTable table = new JTable(tableModel);

    public WordPairTest(Scanner scanner) {
        int rowNumber = 0;
        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            String[] tokens = line.split("\\s*,\\s*");
            if (tokens.length == 2) {
                WordPairRow wpRow = new WordPairRow(tokens[0], tokens[1]);
                addRowToList(rowNumber, wordListPanel, wpRow);
                rowNumber++;

                tableModel.addRow(tokens[0], tokens[1]);
            }
        }

        JPanel btnPanel = new JPanel();
        btnPanel.add(new JButton(new DeleteCheckedRowsAction(tableModel)));

        JPanel tablePanel = new JPanel(new BorderLayout());
        tablePanel.add(new JScrollPane(table));
        tablePanel.add(btnPanel, BorderLayout.PAGE_END);

        setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
        add(wordListPanel);
        add(tablePanel);
    }

    private void addRowToList(int row, JPanel container, WordPairRow wpRow) {
        container.add(wpRow.getFirstWord(), createGbc(0, row));
        container.add(wpRow.getSecondWord(), createGbc(1, row));
        container.add(wpRow.getDeleteBtn(), createGbc(2, row));

        wpRow.addDeleteListener(new DeleteAction(container, wpRow));
    }

    private GridBagConstraints createGbc(int x, int y) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        gbc.fill = GridBagConstraints.HORIZONTAL;

        return gbc;
    }

    private static void createAndShowGui() {
        InputStream resource = WordPairTest.class
                .getResourceAsStream(DATA_FILE_NAME);
        Scanner scanner = new Scanner(resource);

        JFrame frame = new JFrame("WordPairTest");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new WordPairTest(scanner));
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        scanner.close();
    }

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

class WordPairRow {
    private JLabel firstWord = new JLabel("");
    private JLabel secondWord = new JLabel("");
    private JButton deleteBtn = new JButton("Delete");

    public WordPairRow(String word1, String word2) {
        firstWord.setText(word1);
        secondWord.setText(word2);
    }

    public JLabel getFirstWord() {
        return firstWord;
    }

    public JLabel getSecondWord() {
        return secondWord;
    }

    public JButton getDeleteBtn() {
        return deleteBtn;
    }

    public void addDeleteListener(ActionListener listener) {
        deleteBtn.addActionListener(listener);
    }
}

class DeleteAction implements ActionListener {
    private JPanel container;
    private WordPairRow wpRow;

    public DeleteAction(JPanel container, WordPairRow wpRow) {
        this.container = container;
        this.wpRow = wpRow;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        container.remove(wpRow.getFirstWord());
        container.remove(wpRow.getSecondWord());
        container.remove(wpRow.getDeleteBtn());
        container.revalidate();
        container.repaint();
    }
}

@SuppressWarnings("serial")
class WordPairTableModel extends DefaultTableModel {
    private static final String[] COLUMNS = { "First Word", "Second Word", "" };

    public WordPairTableModel() {
        super(COLUMNS, 0);
    }

    public void addRow(String word1, String word2) {
        Vector<Object> rowData = new Vector<>();
        rowData.add(word1);
        rowData.add(word2);
        rowData.add(Boolean.FALSE);
        super.addRow(rowData);
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        if (getRowCount() > 0) {
            Object item = getValueAt(0, columnIndex);
            if (item != null) {
                return item.getClass();
            }
        }
        return super.getColumnClass(columnIndex);
    }

    @Override
    public boolean isCellEditable(int row, int column) {
        return column == 2;
    }
}

@SuppressWarnings("serial")
class DeleteCheckedRowsAction extends AbstractAction {
    private WordPairTableModel tableModel;

    public DeleteCheckedRowsAction(WordPairTableModel tableModel) {
        super("Delete Checked Rows");
        this.tableModel = tableModel;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        for (int row = tableModel.getRowCount() - 1; row >= 0; row--) {
            Boolean check = (Boolean) tableModel.getValueAt(row, 2);
            if (check) {
                tableModel.removeRow(row);
            }
        }
    }
}

如果按下任何删除按钮,则从容器中删除该行单词和按钮。

或许更好的解决方案是使用自定义表模型在JTable中显示单词对。在这个模型中,第3列布尔值显示为复选框。当选中JTable下面的“删除已检查的行”JButton时,将从JTable中删除所有已检查的行。稍后,当您想要提取更改的列表时,只需遍历表模型,提取剩余的单词。

hello, goodbye
hola, adiós
shalom, shalom
bonjour, au revoir 
buongiorno, arrivederci 
hyvaa paivaa, nakemiin 
tere, nagemist 
kuei, niaut 
konnichiwa, sayonara 
privet, dosvidanya 
ahoj, cau
cześć, do widzenia
merhaba, elveda
hallo, vaarwel
saluton, adiaŭ

数据文件:

grunt dist

GUI外观:

enter image description here

答案 1 :(得分:0)

如果你坚持使用单个actionListener,那么只需存储对按钮的引用,以便引用在动作监听器中可用:

 JButton button1 = new JButton("Delete");
 JButton button2 = new JButton("Delete");

然后在动作监听器中:

   Object src = event.getSource();
   if ( src == button1 ) {
      // perform the action for button1
   } else if ( scr ==  button2 ) {
     // perform the action for button2
   }

答案 2 :(得分:0)

可以通过为按钮设置ActionCommand来解决问题。默认情况下,如果我们不设置ActionCommand,则将按钮的名称设置为action命令。我做了以下事情:

JButton delete = new JButton("Delete");
 delete.setActionCommand("action1");'

然后在ActionListener中,我可以检查是否

event.getAactionCommand.equlas("action1")