Java 单击按钮时未打开的窗口
我有下面的代码,它创建了一个带有两个按钮的简单窗口,每个按钮依次打开一个窗口-主窗口打开得很好,但是当你点击按钮时,什么都没有发生Java 单击按钮时未打开的窗口,java,swing,Java,Swing,我有下面的代码,它创建了一个带有两个按钮的简单窗口,每个按钮依次打开一个窗口-主窗口打开得很好,但是当你点击按钮时,什么都没有发生 package presentation; import java.awt.Container; import java.awt.EventQueue; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; impo
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);
}
}
您可能需要替换这些行(创建全新按钮): 通过此操作(使用类的按钮,然后在其上添加侦听器):
您可能需要替换这些行(创建全新按钮): 通过此操作(使用类的按钮,然后在其上添加侦听器):
现在就可以了。。。一旦它允许我,我将接受答案。你能告诉我为什么这样做吗?
container.add中的按钮(newjbutton(“按类别显示库存”)
与catBtn
无关,它是一个新对象。@JosephVodary,它之所以有效,是因为现在您正在添加正确的JButton
实例,而不是全新的实例。上帝啊,你们这些人都很有帮助,我喜欢这个网站。现在它就可以工作了。。。一旦它允许我,我将接受答案。你能告诉我为什么这样做吗?container.add中的按钮(newjbutton(“按类别显示库存”)
与catBtn
无关,它是一个新对象。@JosephVodary,它之所以有效,是因为现在您正在添加正确的JButton
实例,而不是全新的实例。天哪,你们这些人都很有帮助,我喜欢这个网站。请参阅
container.add(new JButton("Display inventory by category"));
container.add(new JButton("Display all inventory"));
container.add(catBtn);
container.add(allBtn);