我正在尝试制作一个gridbaglayout,只是将标签放在垂直窗口中textview顶部的文本框顶部,但我遇到了异常
Exception in thread "main" java.lang.IllegalArgumentException: cannot add to layout: constraints must be a GridBagConstraint
at java.awt.GridBagLayout.addLayoutComponent(GridBagLayout.java:685)
at java.awt.Container.addImpl(Container.java:1072)
at java.awt.Container.add(Container.java:957)
at javax.swing.JFrame.addImpl(JFrame.java:540)
at java.awt.Container.add(Container.java:925)
at guiprojj.gui.main(gui.java:31)
任何人都可以帮助我解决这个异常,也许我误解了 gridbaglayout 的工作原理,如果是这样,如果你能指出我正确的方向,那就太棒了。感谢您的帮助。
package guiprojj;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;
import javax.swing.*;
import com.eclipsesource.json.JsonObject;
import com.google.gson.JsonParser;
import com.json.parsers.JSONParser;
import com.json.parsers.JsonParserFactory;
public class gui {
public static void main(String[] args)
{
JFrame maingui = new JFrame("Gui");
maingui.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
JButton enter = new JButton("Enter");
final JTextArea movieinfo = new JTextArea(5,20);
final JTextField movietext = new JTextField(16);
c.gridx = 1;
c.gridy = 0;
maingui.add(movietext, maingui);
final JScrollPane scrolll = new JScrollPane(movieinfo);
final JLabel titlee = new JLabel("Enter movie name here:");
maingui.setResizable(false);
maingui.setVisible(true);
movieinfo.setLineWrap(true);
movieinfo.setWrapStyleWord(true);
movieinfo.setEditable(false);
scrolll.getPreferredSize();
//pangui.setPreferredSize(new Dimension(300, 150));
//pangui.add(scrolll, BorderLayout.CENTER);
//movieinfo.add(scrolll);
maingui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
maingui.pack();
enter.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.out.println(Test.getMovieInfo(movietext.getText()));
JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonData=parser.parseJson(Test.getMovieInfo(movietext.getText()));
String Title = (String)jsonData.get("Title");
String Year = (String)jsonData.get("Year");
String Plot = (String)jsonData.get("Plot");
movieinfo.setText("Title: "+Title+"\nYear: "+ Year +"\nPlot: "+Plot);
}
});
}
}