[英]Unable to add action listener in gridbaglayout
這是我的代碼,如何添加動作偵聽器我已經嘗試過我知道的方法,但由於靜態方法,我無法添加它。Netbeans IDE 建議在程序中使用動作偵聽器,但我無法使用它,有人可以建議更多聲明動作偵聽器的簡單方法。
公共類計算{
public static void addComponentsToPane(Container pane) {
pane.setLayout(new GridBagLayout());
GridBagConstraints gBC = new GridBagConstraints();
gBC.ipady = 40;
gBC.ipadx = 40;
JTextField JTextField = new JTextField("Hello");
gBC.fill = GridBagConstraints.HORIZONTAL;
gBC.gridx = 0;
gBC.gridy = 0;
gBC.gridwidth = 4;
JTextField.setEditable(false);
pane.add(JTextField, gBC);
//JButton jbnButton;
gBC.gridwidth = 1;
JButton b7 = new JButton("7");
gBC.gridx = 0;
gBC.gridy = 1;
pane.add(b7, gBC);
// more calculator buttons declared here
//這里是如何建議actionlistner的
b0.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
b0ActionPerformed(evt);
}
private void b0ActionPerformed(ActionEvent evt) }
`
});
b0.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
b0ActionPerformed(evt);
}
private void b0ActionPerformed(Actionenter Event evt) {}
});}
private static void createAndShowGUI() {}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
我為你試試這個。 您可以在 addComponentsToPane 方法中為您聲明的每個組件添加動作偵聽器。 此外,您忘記傳遞框架,因此您可以像我一樣在 main 方法中傳遞它。
public class Calc {
public static void addComponentsToPane(Container pane) {
pane.setLayout(new GridBagLayout());
GridBagConstraints gBC = new GridBagConstraints();
gBC.ipady = 40;
gBC.ipadx = 40;
JTextField JTextField = new JTextField("Hello");
gBC.fill = GridBagConstraints.HORIZONTAL;
gBC.gridx = 0;
gBC.gridy = 0;
gBC.gridwidth = 4;
JTextField.setEditable(false);
pane.add(JTextField, gBC);
//JButton jbnButton;
gBC.gridwidth = 1;
JButton b7 = new JButton("7");
gBC.gridx = 0;
gBC.gridy = 1;
pane.add(b7, gBC);
// more calculator buttons declared here
b7.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Write your action here
}
});
}
private static void createAndShowGUI(JFrame pane) {
addComponentsToPane(pane);
pane.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI(new JFrame());
}
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.