我正在尝试使用FlowLayout将JPanel添加到JFrame,但继续获得此异常:“线程中的异常”AWT-EventQueue-0“java.lang.IllegalArgumentException:非法组件位置”。我希望能够在不久的将来实现一个带有几个按钮的JPanel,所以请让我知道我能做些什么来实现这一点。
package textadv;
import java.awt.FlowLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Label;
import java.awt.event.KeyEvent;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TextAdv {
private JFrame frame = new JFrame("Text Adventure");
private JPanel mainPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
private JButton b1 = new JButton("Left");
public TextAdv() {
mainPanel.setBackground(Color.RED);
int FRAME_WIDTH = 400;
int FRAME_HEIGHT = 400;
b1.setEnabled(true);
b1.setVisible(true);
b1.setPreferredSize(new Dimension(40, 40));
mainPanel.setVisible(true);
mainPanel.setPreferredSize(new Dimension (50, 50));
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
frame.setVisible(true);
mainPanel.add(b1, FlowLayout.CENTER);
frame.add(mainPanel);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
TextAdv fS = new TextAdv();
}
});
}
答案 0 :(得分:4)
您无法为Container的add方法指定FlowLayout选项。这解析为接受Component的add()重载和int索引。其他布局允许您使用add(Component,Object)重载,如GridBagLayout及其GridBagConstraints。对于FlowLayout,您只能为布局的构造函数指定选项。
替换此
mainPanel.add(b1, FlowLayout.CENTER);
用这个
mainPanel.add(b1);
请考虑在此重新访问教程:http://docs.oracle.com/javase/tutorial/uiswing/layout/flow.html
请参阅此处的容器:http://docs.oracle.com/javase/7/docs/api/java/awt/Container.html#add%28java.awt.Component,%20int%29