我有以下代码创建一个带有两个按钮的简单窗口,而这两个按钮又假设每个都打开一个窗口 - 主窗口打开就好了但是当你点击按钮时没有任何反应......
package presentation;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ShowInventory extends JFrame {
/**
*
*/
private static final long serialVersionUID = 7479750059244371227L;
private JPanel contentPane;
private JButton catBtn = new JButton ("Display inventory by category");
private JButton allBtn = new JButton ("Display all inventory");
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ShowInventory frame = new ShowInventory();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
System.out.println("Exception - Sorry");
}
}
});
}
/**
* Default - details to be added
*/
public ShowInventory() { // title bar name
// layout here
Container container = getContentPane();
FlowLayout layout = new FlowLayout();
container.setLayout(layout);
layout.setAlignment(FlowLayout.CENTER);
container.add(new JButton("Display inventory by category"));
container.add(new JButton("Display all inventory"));
catBtn.addActionListener (new ActionListener() {
public void actionPerformed (ActionEvent event) {
// controller code
ShowByCategory frame = new ShowByCategory();
frame.setVisible(true);
}
});
allBtn.addActionListener (new ActionListener() {
public void actionPerformed (ActionEvent event) {
// controller code
ShowAllInventory frame = new ShowAllInventory();
frame.setVisible(true);
}
});
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
}
答案 0 :(得分:4)
您可能需要更换这些行(创建全新的按钮):
container.add(new JButton("Display inventory by category"));
container.add(new JButton("Display all inventory"));
由此(使用您的类的按钮,然后添加监听器):
container.add(catBtn);
container.add(allBtn);