I don't know why but I get an error everythime I run this code.
The error is: Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method setLayout(LayoutManager) in the type JFrame is not applicable for the arguments (FlowLayout) at gui.FlowLayout.main(FlowLayout.java:14)
I'm learning Java and I'm a beginner so I don't really know what to do. Please help me.
package gui;
import java.awt.LayoutManager;
import javax.swing.JButton;
import javax.swing.JFrame;
public class FlowLayout {
public static void main(String[] args) {
JFrame frame = new JFrame(); //cerates frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //exit out of application
frame.setSize(500, 500); //sets x-dimesion, and y-dimension of frame
frame.setLayout(new FlowLayout());
frame.add(new JButton("1"));
frame.setVisible(true);
}
}
CodePudding user response:
There is a potential conflict between the class you created gui.FlowLayout
and java.awt.FlowLayout
, the layout you have to give to your frame.
The error is due to the fact the JFrame.setLayout()
method expects a java.awt.FlowLayout
and not a gui.FlowLayout
which is the only FlowLayout available in your code.
To fix that, I'd do the following
- Remove the ambiguity by renaming the class you created (to
FlowLayoutExample
for example). - Import the
java.awt.FlowLayout
you actually need.
The code should become:
package gui;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.FlowLayout;
public class FlowLayoutExample {
public static void main(String[] args) {
JFrame frame = new JFrame(); //cerates frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //exit out of application
frame.setSize(500, 500); //sets x-dimesion, and y-dimension of frame
frame.setLayout(new FlowLayout());
frame.add(new JButton("1"));
frame.setVisible(true);
}
}
Note: there is also another possibility: you can skip the import and directly mention the complete class name (with the package):
frame.setLayout(new java.awt.FlowLayout());
I tend to prefer the first solution because:
- The name
FlowLayout
doesn't reflect what your class does whileFlowLayoutExample
is IMHO more explicit. - Always using complete class names makes your code more verbose and thus less readable.
CodePudding user response:
Just add the library: import java.awt.FlowLayout