Right after I create a new Frame object to attach future JPanels to, the references to the object "j" aren't recognized.
package engine;
import javax.swing.*;
public class GamePanel extends JFrame{
final int HEIGHT=700, WIDTH=500;
JFrame j= new JFrame("LittleRPG");
j.setSize(HEIGHT, WIDTH);
}
the j.setSize(); isn't accepted and an error appears (this applies to all object references after the initial construction of them). I need help identifying why; fresh eyes always help. -Thank you
You dont need to create separate object of JFrame to set size because you already extended the GamePanel Class From JFrame. So, You can directly set it in the constructor GamePanel as your code look like:
package engine;
import javax.swing.*;
public class GamePanel extends JFrame
{
final int HEIGHT=700, WIDTH=500;
GamePanel ()
{
setSize(HEIGHT, WIDTH);
}
}
Your setSize(HEIGHT, WIDTH); method has to be inside of a constructor or another method. Like #Vikas Suryawanshi said, you could just call the methods of JFrame, you dont need to create a new Object of it.
The answers of #Tupfer and #Vikas are correct.
Still you want to do it using the object of Jframe then
package engine;
import javax.swing.*;
import java.awt.Color;
public class GamePanel extends JPanel{
final int HEIGHT=700, WIDTH=500;
public static void main(String[] args){
JFrame j= new JFrame("LittleRPG");
j.setSize(HEIGHT, WIDTH);
j.getContentPane().add(new GamePanel());
j.setVisible(true);
j.setLocationRelativeTo(null);
j.setBackground(Color.BLUE);
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Also you do not need to extend JFrame
Related
I want to have a JPanel respond to a MouseEvent, such as, mousePressed(), but not others.
I can do it via the following code added to the JPanel object:
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
//Some action here
}
});
However, the anonymous function requires that I use final variables inside there. And my program specifications do not allow me to that.
I can also define the MouseEvents not as an inner class, but outside, but then I have to provide implementations for all the functions in the MouseListener interface, such as mouseClicked(), mouseEntered(), mouseExited(), etc.
Is there any other way of achieving what I'm trying to do, i.e. define the mousePressed() function without having to use final variables inside it, and also without having to define the other functions in the interface ?
Thanks a lot !
EDIT: I realize that the code I have provided runs without error because the inner class is creating an object of MouseAdapter which is an abstract class.
However, my question still remains : if I dont want to define all methods of the abstract class, and also not have to use inner classes, is there any way of doing so ?
One of the examples:
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainClass extends JPanel {
public MainClass() {
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
System.out.println(me);
}
});
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new MainClass());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
}
}
Also, you can use official tutorial here.
I've got two classes. My QuizatMainClass class and a class called window. I'm trying to create a window from the Quizat class with a set size but it won't compile. I've set the parameter to (x and y) e.g (1080 and 720). But it does'nt like that. I'm new to Java and don't really understand why I can't do this. The way the IDE fixes it is with something about superclass stuff. If someone could explain what this means to me or a more simple way to do what I'm trying to run I'd appreciate it. Layman's terms please.
QuizatMainClass:
package Quizat;
public class QuizatMainClass extends Window{
public static void main(String[] args) {
Window QuizatHomeScreen = new Window(1080, 20);
}
}
Window Class:
package Quizat;
import javax.swing.JFrame;
public class Window{
public Window(int x, int y){
JFrame window = new JFrame();
window.setSize(x,y);
window.setLocationRelativeTo(null);
window.setResizable(false);
window.setVisible(true);
}
}
The explanation for your problem is that since QuizatMainClass extends the Window class, and Window has a specific parameter-using constructor, the QuizatMainClass will either need to create a constructor that specifically calls Window's super constructor with parameters, or else give Window a default no-arg constructor.
Having said that your real problem is that you're misusing inheritance. QuizatMainClass shouldn't extend the Window class, that's it.
Im working on a lab that requires me to make a JFrame with 2 inner classes. One that entends JPanel, has a text area and a jbutton. And another that implements action listener. How do i add an anonymouse instance of the second class to my JButton that is already in an inner class. Here is the brief to get a better understanding.
here is the code i have written so far. I can get the Frame to appear, but the JPanel doesnt appear, nor does the JButtons or JTextArea.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class FormFrame extends JFrame
{
public static void main(String[] args)
{
JFrame frame = new FormFrame();
frame.setLocationRelativeTo(null);
}
public FormFrame()
{
Container contentPane = getContentPane();
RegisterPanel p = new RegisterPanel();
p.button.addActionListener(new SubmitResponder());
//
// Here is where im lost...
//
contentPane.add(p);
setSize(300, 200);
setVisible(true);
}
class RegisterPanel extends JPanel
{
JPanel panel = new JPanel();
JTextField text = new JTextField();
JButton button = new JButton("Submit");
}
class SubmitResponder implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource()== RegisterPanel.button) //Asks me to make button static here
{
//Shows "No enclosing instance of the type FormFrame.RegisterPanel is accessible in scope"
RegisterPanel.this.text.setText("Submit Complete");
}
}
}
}
Any help with this would be much appreciated
You could pass the RegisterPanel instance to the action listener:
class SubmitResponder implements ActionListener {
private final RegisterPanel rp;
public SubmitResponder(RegisterPanel rp) {
this.rp = rp;
}
#Override
public void actionPerformed(ActionEvent e) {
rp.text.setText("Submit Complete");
}
}
There's no need to check the source btw. The AL is only listening to 1 source.
RegisterPanel p = new RegisterPanel();
p.button.addActionListener(new SubmitResponder(p));
p.button.addActionListener(new SubmitResponder());
Here the SubmitResponder is already an anonymous instance, quite literally, because it has no name.
Your error about "no enclosing instance" is unrelated. Since SubmitResponder is not an inner class of RegisterPanel (it's a sibling) it doesn't belong to an instance of RegisterPanel and so it cannot logically refer to RegisterPanel.this. How would it know which instance that is? There might be many, or even zero, depending on how many the parent FormFrame decides to create. It so happens that there's only one, but that's not the point. On the other hand if you said FormFrame.this there would be no doubt what that meant no matter the code did, unless RegisterPanel stopped being an inner class or it became static. Does that make sense?
To do what you want, the SubmitResponder needs to talk to RegisterPanel via a method in FormFrame. Incidentally you don't actually need to say FormFrame.this.doSomething() unless SubmitResponder also has a method called doSomething.
The instructions tell you that the RegisterPanel should be a field in the FormFrame class, which you haven't done. Something like this:
public class FormFrame extends JFrame
{
RegisterPanel panel;
...
public FormFrame()
{
panel = new RegisterPanel();
...
}
...
class SubmitResponder implements ActionListener
{
#Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == panel.button)
{
panel.text.setText(...);
}
}
}
}
Now you can access panel from inside the SubmitResponder class.
As a side note, the instructions are using some terminology in an ambiguous and incorrect way:
"Anonymous instance" is not an official term with a precise meaning.
Using official definitions, "class field" would imply the static modifier. Given the context of the assignment, I doubt that's correct. It should probably have said "instance field".
I have three classes which are shown below ,for a game GUI:-
//this is the parent class.
import javax.swing.*;
import java.awt.*;
public class GameGui extends JFrame{
public void decorateButton(JButton aBut,Color forg,Color back){
Font afont = new Font(Font.SANS_SERIF,Font.PLAIN,18);
aBut.setFont(afont);
aBut.setBackground(back);
aBut.setForeground(forg);
}
public void setFrameDefault(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400, 475);
this.setLocationRelativeTo(null);
this.setResizable(false);
}
public void setConstraints(int x,int y,int weightx,int weighty,GridBagConstraints gbc){
gbc.weighty=weighty;
gbc.weightx=weightx;
gbc.gridx=x;
gbc.gridy=y;
}
}
//this class is for result to be shown for the game.
import javax.swing.*;
import java.awt.*;
class Result extends GameGui{
JPanel mainPanel = new JPanel();
JLabel backImage = new JLabel();//I want this variable to be shadowed by the subclass variable,but it is not happening.
JButton continueGame = new JButton("continueGame");
JButton exitGame = new JButton("exitGame");
public Result(){
this.setFrameDefault();
backImage.setLayout(new BorderLayout());
this.setContentPane(backImage);
mainPanel.setLayout(new GridBagLayout());
decorateButton(continueGame,Color.green,Color.white);
decorateButton(exitGame,Color.green,Color.white);
setGui();
}
public void setGui(){
GridBagConstraints gbc = new GridBagConstraints();
mainPanel.setOpaque(false);
gbc.gridy=200;
gbc.gridx=0;
gbc.insets=new Insets(410,0,0,130);
mainPanel.add(continueGame,gbc);
gbc.gridx=GridBagConstraints.RELATIVE;
gbc.insets = new Insets(410,0,0,0);
mainPanel.add(exitGame,gbc);
setFrameDefault();
this.getContentPane().add(mainPanel);
}
}
//this class is for showing the result for a Win.
import javax.swing.*;
import java.awt.*;
public class Win extends Result{
JLabel backImage = new JLabel(new ImageIcon("C:\\Users\\BSK\\Desktop\\win.png"));//Problem is here as i have declared the same named JLabel as in Result class but iam not getting the image as background.
public static void main(String[] args) { //this main method is for testing.
Win w = new Win();
w.setVisible(true);
}
}
I need two classes at end of hierarchy which are Win and Defeat(second one i have not implemented).I need this because i want wining frame and Defeat frame only differ in the image.
So my question is that although i have declared same named JLabel as backImage in both the classes Result and Win,why i am not getting the image at background?I have tested it by putting the image in JLabel backImage of Result class and then it works!But i want to take the advantage of data shadowing because in my Defeat class(which also extends Result)i will name JLabel having same name as backImage but with different image set to it.I hope you understand,So what is the way out?
Thanks in advance.
NOTE please test with your image.
Shadowing affects which variable a name refers to. That is, since the subclass Win defines its own backImage instance variable, methods of Win that refer to backImage will refer to the instance variable in Win (and thus its value) rather than the one in the superclass, Result.
Shadowing does not replace an object that variables and other objects point to. That is, the superclass Result still defines its own backImage instance variable, and Result's methods still refer to that variable (and thus its value). So Win#backImage shadows Result#backImage but it doesn't change how Result works.
Also note that the initialization lines like JLabel backImage = ... run as part of a class's constructor, and the subclass Win's constructor begins by running its superclass Result constructor. So if the subclass didn't declare another backImage and its constructor assigned a new value to the inherited instance variable Result#backImage, this would happen after the Result constructor built the content pane, so it wouldn't change the display.
You could change the contents of the backImage object:
public class Win extends Result {
public Win() {
super();
backImage.setIcon(new ImageIcon("C:\\Users\\BSK\\Desktop\\win.png"));
}
...
to modify backImage's icon for the Win subclass.
Fields in Java don't get overriden as methods, so this will not work for you. Fortunately, there are plenty solutions.
One of them (i'm definetly not saying the best one!) is to make your Result game abstract with abstract getIcon() method or something and call that from your setGui() method, then your Win/Lose classes will just return different icons in there.
I am newbie in java
package assigment;
import java.awt.*;
import java.sql.*;
import javax.swing.*;
public class view extends JFrame {
public static void main(String[] args) {
new view();
}
public view(){
JFrame f = new JFrame("WELCOME");
f.setSize(400, 300);
f.setVisible(true);
f.setLocationRelativeTo(null);
controller cl = new controller();
JButton btnCompany = new JButton ("COMPANY");
f.add(btnCompany);
f.setLayout(null);
btnCompany.setBounds(50, 50, 100, 50);
btnCompany.addActionListener (cl);
}
}
contoller class
package assigment;
import java.awt.event.*;
public class controller {
public static void actioncompany(ActionEvent a,view view) {
if (a.getSource() == view.btnCompany) {
System.out.print ("test");
}
}
}
Problem:
Cannot use controller class
Cannot access btnCompany in controller class
That code shouldn't even compile since there isn't a field, view.btnCompany. The btnCompany variable is local to the constructor and thus invisible everywhere else. Also, as MadProgrammer notes, your controller class (re-name it Controller) doesn't implement ActionListener and so cannot be used as an ActionListener.
I have other issues with your code:
Don't use null layout and absolute positioning.
Do abide by Java naming rules including starting class and interface names with an upper case letter so that others can more easily understand your code.
Yes, separate out your control from your view.
Most all fields should be private, and so view.BtnCompany shouldn't be visible, even if the field existed.
ActionListeners must implement the ActionListener interface or extend a class that implements the interface such as AbstractAction.