我正在創建一個動態的按鈕數量和原因,我不能爲每個按鈕命名,因爲我想要的每個按鈕內的文本也必須是空的,所以我也不能使用它。在另一方面,我需要通過一個整數(甚至是兩個整數)是否可以將一個Interger簽名分配給一個JButton對象?
在下面,你有我的具體類的代碼來識別每個按鈕:
package view;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import javax.swing.JButton;
import javax.swing.JFrame;
import view.Nodes.Node;
public class AdjacencyMatrixWindow {
public JFrame frame;
int index;
LinkedList<Node> nodes;
int rowNumber=1;
Iterator<Node> nodeIter;
JButton btn;
public AdjacencyMatrixWindow(int index,LinkedList<Node> nodes) {
this.index=index;
this.nodes=nodes;
sortNodes();
for (Node node : nodes)
sortConnecteds(node.isConnectedToNodes);
nodeIter = nodes.iterator();
initialize();
apply();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 358, 297);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().setLayout(new GridLayout(nodes.size()+1, nodes.size()+1));
}
public void insertFirstRowLabels()
{
for (int i=0;i<=nodes.size();i++)
{
if (i==0)
{
Label lbl = new Label(" ");
lbl.setBackground(new Color(240,240,240));
frame.getContentPane().add(lbl);
}
else
{
Label lbl = new Label(String.valueOf(i));
frame.getContentPane().add(lbl);
}
}
}
public void insertRow(Node node)
{
for (int i=0;i<=nodes.size();i++)
{
if (i==0)
{
Label lbl = new Label(String.valueOf(rowNumber));
frame.getContentPane().add(lbl);
rowNumber++;
}
else
{
if (node.isConnectedToNodes.contains(node.getNodeByID(i)))
{
btn = new JButton("T");
frame.getContentPane().add(btn);
}
else
{
btn = new JButton(" ");
frame.getContentPane().add(btn);
}
}
}
}
public int columnNumbers()
{
if (nodeIter.hasNext())
return Integer.parseInt(nodeIter.next().getNodeID());
return -1;
}
public void apply()
{
insertFirstRowLabels();
for (int i=0;i<=nodes.size()-1;i++)
{
insertRow(nodes.get(columnNumbers()-1));
}
}
public void sortNodes()
{
Collections.sort(nodes, new Nodes.IDComperator());
}
public void sortConnecteds(LinkedList<Node> node)
{
Collections.sort(node, new Nodes.IDComperator());
}
Runnable selectAndDraw = new Runnable()
{
public void run()
{
btn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent b) {
}});
}
};
}
遺憾的代碼是不是很乾淨寫入。
你能給我寫個例子嗎? (如何在我的ActionListener中使用這個actionCommand)@camickr –
是的,我知道如何使用parseInt和String.valueOf ...但我的問題是,我從來沒有見過「String actionCommand = event.getActionCommand();」所以如果你不介意讓我或鏈接一個例子來了解這將是完美的 –
,當我把它寫爲u在底部看到我有nullpointexception –