【发布时间】:2014-06-28 07:20:54
【问题描述】:
如何并排放置同一类的 3 个相同实例?在下面的代码中,这 3 个是相互重叠的 - 我如何修改它以使它们并排?
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class RestaurantBillCalculatorMain {
public static void main(String[] args) {
if (args.length != 2) {
JOptionPane.showMessageDialog(null,
"Correct arguments not provided.\nPlease enter database username and password on the command line.\nProgram will now exit.");
} else {
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
mainPanel.setSize(1200, 600);
mainPanel.setVisible(true);
RestaurantBillCalculator application1 = new RestaurantBillCalculator(
"jdbc:mysql://localhost:3306/restaurant", args[0], args[
application1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application1.setSize(400, 600);
application1.setVisible(true);
RestaurantBillCalculator application2 = new RestaurantBillCalculator(
"jdbc:mysql://localhost:3306/restaurant", args[0], args[1]);
application2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application2.setSize(400, 600);
application2.setVisible(true);
RestaurantBillCalculator application3 = new RestaurantBillCalculator(
"jdbc:mysql://localhost:3306/restaurant", args[0], args[1]);
application3.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application3.setSize(400, 600);
application3.setVisible(true);
mainPanel.add(application1);
mainPanel.add(application2);
mainPanel.add(application3);
frame.add(mainPanel);
}
} // end method main
}
我在代码中也遇到错误:“线程“主”java.lang.IllegalArgumentException 中的异常:将窗口添加到容器中”。这是什么原因造成的?
部分构造函数如下,我怀疑是不是跟这个有关?
Container contentPane = getContentPane();
contentPane.setLayout( null );
我大多是 Java 新手,所以还在学习。
【问题讨论】:
-
我们被要求在每个实例中使用绝对定位,我可以使用布局管理器来定位每个实例吗?
-
是的,布局管理器会很好用,而且比绝对定位灵活得多。
-
您的错误正在发生,因为您将 JFrame 添加到 JPanel。这就像试图将汽车放入人体内一样——疯了。解决方案:不要这样做。我可以根据经验告诉你,猜测这些东西是行不通的,所以请阅读教程,不要将 JFrames 放入 JFrames 中,而是将 JPanels 放入 JFrames 中。