如何将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来说几乎是全新的,所以仍然非常学习所以非常感谢任何帮助。
答案 0 :(得分:0)
要回答有关使用布局管理器的原始问题,您可以尝试阅读Java教程:Swing Group Layout
以下是一些简单的入门代码,可帮助您基本了解如何在一行中水平重新排列组件:
...
/*
when you add components to the layout, it will
automatically add them to your mainPanel, so the following is unnecessary.
mainPanel.add(application1);
mainPanel.add(application2);
mainPanel.add(application3);
*/
frame.add(mainPanel);
GroupLayout layout = new GroupLayout(mainPanel);
mainPanel.setLayout(layout);
//set margins around components by default
layout.setAutoCreateContainerGaps(true);
layout.setAutoCreateGaps(true);
layout.setHorizontalGroup(layout.createSequentialGroup()
.addComponent(application1)
.addComponent(application2)
.addComponent(application3));
layout.setVerticalGroup(layout.createParallelGroup()
.addComponent(application1)
.addComponent(application2)
.addComponent(application3));
上面的链接有图片,可以更好地显示布局管理器如何解释水平和垂直组。