My Code:
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.*;
public class TAFrame {
private JFrame mainFrame;
private JPanel mainPanel;
private JButton button;
private JTextArea textArea; //eclipse say Syntax error } expected
mainFrame = new JFrame("mainFrame");
mainPanel = new JPanel();
button = new JButton("click me");
area = new JTextArea(10, 15);
}
Cant find the solution, but i think it is embarrassing easy :/
I believe you wanted to put some of the code within a constructor, like this:
public class TAFrame {
private JFrame mainFrame;
private JPanel mainPanel;
private JButton button;
private JTextArea textArea;
public TAFrame() {
mainFrame = new JFrame("mainFrame");
mainPanel = new JPanel();
button = new JButton("click me");
area = new JTextArea(10, 15);
}
}
The problem was that you tried to execute arbitrary code outside any method. Once a field has been declared, you need to access it through a method. It is only possible to initialize it on the same line, so you can do like the following:
public class TAFrame {
private JFrame mainFrame = new JFrame("mainFrame");
private JPanel mainPanel = new JPanel();
private JButton button = new JButton("click me");
private JTextArea textArea = new JTextArea(10, 15);
}
I recommend the constructor-approach in this case, but either way you will most need a constructor anyways since you probably want to add an actionlistener to the button (for example).
Most of the answers here have correctly pointed out that you can use initial values for initialization, and that you can use constructors. However, the Java tutorial, Initializing Fields, actually describes two non-constructor ways of initializing fields: (i) initial values; and (ii) initialization blocks.
The following code demonstrates all three methods (and shows both instance and static initialization blocks):
public class InitializationExample {
private int field1 = 1; // in-line initializer
private int field2a;
private static int field2b;
private int field3;
{
field2a = 3; // instance initializer
}
static {
field2b = 3; // static initializer
}
public InitializationExample( final int field3 ) {
this.field3 = field3;
}
}
Using the initialization blocks, you can make a very minor change to your code and have it compile:
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.*;
public class TAFrame {
private JFrame mainFrame;
private JPanel mainPanel;
private JButton button;
private JTextArea textArea;
{
mainFrame = new JFrame("mainFrame");
mainPanel = new JPanel();
button = new JButton("click me");
area = new JTextArea(10, 15);
}
}
Even though this is possible, it isn't incredibly common, so unless you have some particularly good reason for using this, or it's already common in a codebase that you're working on, initial values or constructors are probably a more readable and maintainable option. It's also important to note that, according to 12.5. Creation of New Class Instances from the Java Language Specification, instance initialization code (and initial values) are processed before constructor code runs.
There is one possible benefit to the initialization block approach over constructor based methods. If you did make this a constructor, along the lines of
public TAFrame() {
mainFrame = new JFrame("mainFrame");
mainPanel = new JPanel();
button = new JButton("click me");
area = new JTextArea(10, 15);
}
and then introduced another constructor later that takes some arguments, you'll either need to explicitly call the zero-argument constructor from that constructor (constructor chaining), or include initialization assignments in that constructor, too. Using the initialization blocks, you wouldn't need to do either.
Initialization blocks are also handy when you're creating an instance of an anonymous subclass, because you can keep the initialization code visually "inside" the class. You can read up on double brace initialization for more details, but here's a simple example:
import java.util.HashMap;
import java.util.Map;
public class MapInitializationExample {
public static void main(String[] args) {
// initialization code for this Map is visually "inside" the map
final Map<Integer,String> numberNames = new HashMap<Integer,String>() {{
put(1,"one");
put(2,"two");
put(3,"three");
}};
}
}
Because you are putting code outside of a method that does not belong.
This block in particular:
mainFrame = new JFrame("mainFrame");
mainPanel = new JPanel();
button = new JButton("click me");
area = new JTextArea(10, 15);
The error is a bit deceiving because it looks like private JTextArea textArea; needs a closing brace. But really, the problem is that the next line does not belong there. The next line, mainFrame = new JFrame("mainFrame"); suggests a method has started and the previous block never closed, thus the reference to a missing }.
You have two options:
Instantiate the objects in-line with their declarations
Instantiate the objects in a constructor
To Instantiate In-line
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.*;
public class TAFrame {
private JFrame mainFrame = new JFrame("mainFrame");
private JPanel mainPanel = new JPanel();
private JButton button = new JButton("click me");
private JTextArea textArea = new JTextArea(10, 15);
}
To Instantiate with a Constructor
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.*;
public class TAFrame {
private JFrame mainFrame;
private JPanel mainPanel;
private JButton button;
private JTextArea textArea;
public TAFrame() {
mainFrame = new JFrame("mainFrame");
mainPanel = new JPanel();
button = new JButton("click me");
area = new JTextArea(10, 15);
}
}
I personally prefer the inline approach as it is far less verbose.
You should do something like this.
public class TAFrame {
private JFrame mainFrame;
private JPanel mainPanel;
private JButton button;
private JTextArea textArea;
public void initComponents() {
mainFrame = new JFrame("mainFrame");
mainPanel = new JPanel();
button = new JButton("click me");
area = new JTextArea(10, 15);
}
}
Or you can create and instantiate the control there itself.
private JFrame mainFrame = new JFrame("mainFrame");
private JPanel mainPanel = new JPanel();
private JButton button = new JButton("click me");
private JTextArea textArea = new JTextArea(10, 15);
Related
I am stumped and desperate for help. Been able to figure everything else out until I got into GUI's. What I am trying to do is go from the LogInPane (Log In Page) to JobSelectionGUI (Job Selection Page);
When I compile it runs how I want it to, but I can't figure out how to get my JFrame from LogInPaneGUI to close when it opens JobSelectionGUI, Tons of reading and videos and picking GUI's/Applying them is rough! I started with a GridLayout then switched to GridBagLAyout, then tried CardLayout and now back to GBL.
I don't use an IDE; I use SublimeText, so if something looks extremely elongated in my code, its because I had to write it out long for Sublime (or because I'm bad). All my code is separated into different classes so it stays neat and easy to debug. Every class has its own package, and every package has no more than 2 Methods. I work my butt off to keep my main completely empty!
Taking all criticism and advice!
MAIN:
package com.hallquist.kurtis.leigh.srcmain;
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.text.*;
// Class imports;
import JobSelection.*;
import LogInPane.*;
// My Main function. Used to pull packages and methods and compile them here;
public class SrcMainUserInformation{
public static void main(String[] args){
LogInPaneGUI logInGUI = new LogInPaneGUI();
logInGUI.logInPaneMainGUI();
}
}
First Class:
package LogInPane; // package name;
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.ImageIcon;
import JobSelection.*; //import for next GUI when LogInButton is clicked;
public class LogInPaneGUI{
private static final JFrame frame = new JFrame();
private static final int COLS = 10; // Max columns;
private static final JPanel panelForm = new JPanel(new GridBagLayout()); // layout
private static final JTextField fieldLogInName = new JTextField(COLS); //login
private static final JPasswordField logInPassword = new JPasswordField(COLS); //pw
private static final JButton logInButton = new JButton("Log In"); //login button
private static final JButton exitButton = new JButton("EXIT"); //system.exit button
private static final JButton newUser = new JButton("New User? Click here to sign up!"); // new user button
// Wigits on login page;
public LogInPaneGUI(){
GridBagConstraints c = new GridBagConstraints();
// Creates the panel that goes ontop of the JFrame;
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.LINE_END;
panelForm.add(new JLabel("Account Name: "), c);
c.gridy ++;
panelForm.add(new JLabel("Password: "), c);
c.gridy ++;
c.gridx = 1;
c.gridy = 0;
c.anchor = GridBagConstraints.LINE_START;
panelForm.add(fieldLogInName, c);
c.gridy++;
panelForm.add(logInPassword, c);
c.gridy++;
panelForm.add(logInButton, c);
c.gridy++;
panelForm.add(newUser, c);
c.gridy++;
panelForm.add(exitButton, c);
// Goes to fourm/website on newUser click;
newUser.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
System.out.println("Fourm/Website to sign up for game");
}
});
// Exits program on exitButton click;
exitButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
// Goes to JobSelectionGUI on logInButton Click;
logInButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
JobSelectionGUI jobSelecting = new JobSelectionGUI();
jobSelecting.jobSelectionJFrameGUI();
// frame.dispose();
// System.out.println("Will log you in when I set it up");
}
});
}
// Actual JFrame that everything goes ontop of;
public static void logInPaneMainGUI(){
JFrame frame = new JFrame("FirstProject");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setSize(1080, 720);
frame.setResizable(false);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.getContentPane().add(panelForm);
}
}
Second Class:
package JobSelection;
import java.awt.*;
import java.awt.event.ActionEvent.*;
import javax.swing.*;
import javax.swing.text.*;
// Mass import from JobSelection package; All base job information;
import JobSelection.JobInformationIndex.JobAmazonData.*;
import JobSelection.JobInformationIndex.JobBanditData.*;
import JobSelection.JobInformationIndex.JobLancerData.*;
import JobSelection.JobInformationIndex.JobSorcererData.*;
import JobSelection.JobInformationIndex.JobWitchData.*;
import LogInPane.*; // to return to login screen;
import JobSelection.*; // dont know if needed;
public class JobSelectionGUI{
private static JFrame frame = new JFrame();
private static JSplitPane jSplitPane = new JSplitPane();
private static JPanel leftPane = new JPanel();
private static JLabel logInCharacterName = new JLabel();
private static JTextField userCharacterName = new JTextField();
private static JButton logInAccept = new JButton("Accept");
private static JButton logInBack = new JButton("Back");
private static JTextArea firstGameIntroduction = new JTextArea();
private static JTextArea descriptionIntroduction = new JTextArea();
private static JTextArea jobSelectedInformation = new JTextArea();
private static JPanel allWidgits = new JPanel();
public JobSelectionGUI(){
JTextArea firstGameIntroduction = new JTextArea("\ Text.");
firstGameIntroduction.setLineWrap(true);
firstGameIntroduction.setWrapStyleWord(true);
JScrollPane areaScrollPane = new JScrollPane(firstGameIntroduction);
areaScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
areaScrollPane.setPreferredSize(new Dimension(250, 250));
areaScrollPane.setBorder(
BorderFactory.createCompoundBorder(
BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Introduction"),
BorderFactory.createEmptyBorder(5,5,5,5)),
areaScrollPane.getBorder()));
leftPane.add(areaScrollPane);
JTextArea descriptionIntroduction = new JTextArea(" Text.\n");
descriptionIntroduction.setLineWrap(true);
descriptionIntroduction.setWrapStyleWord(true);
JScrollPane areaScrollPaneTwo = new JScrollPane(descriptionIntroduction);
areaScrollPaneTwo.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
areaScrollPaneTwo.setPreferredSize(new Dimension(250, 250));
areaScrollPaneTwo.setBorder(
BorderFactory.createCompoundBorder(
BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("What to expect"),
BorderFactory.createEmptyBorder(5,5,5,5)),
areaScrollPaneTwo.getBorder()));
leftPane.add(areaScrollPaneTwo);
}
public static void jobSelectionJFrameGUI(){
JFrame frame = new JFrame("FirstProject");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1080, 720);
frame.setResizable(false);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.getContentPane().add(leftPane);
}
}
You grossly overuse the static modifier and most of your fields should not in fact be static. I would venture to state that most if not all of your class's fields should be private instance fields.
The log-in window should not be a JFrame but rather a blocking or "modal" dialog, and for Swing that means using a modal JDialog or JOptionPane (which creates a modal JDialog behind the scenes)
A modal dialog will block the calling code when it is displayed
And if the dialog is modal, then you know when it is no longer visible since the calling code is unblocked. This is when you would query the state of the dialog's fields (using public getter methods, not calling static fields directly), and decide if the login was successful or not. If so, show your main GUI window or JFrame.
Another option is to yes, use CardLayout, but for this to work, all your major GUI classes should be geared towards creating JPanels, not JFrames. This way you can insert the panels where and when needed, including within top-level windows such as JFrames or JDialogs, within or JPanels, or swapped using a CardLayout.
Note that frame.dispose() isn't working for you because you shadow the frame field by re-declaring it logInPaneMainGUI() method.
public static void logInPaneMainGUI() {
// ***** this creates a new local JFrame variable called frame
JFrame frame = new JFrame("FirstProject");
// so calling frame.dispose() elsewhere will have no effect on this window
Don't do this, and the .dispose() method call will close the first window.
public static void logInPaneMainGUI() {
frame = new JFrame("FirstProject"); // this initializes the frame field
// so calling frame.dispose() elsewhere will have no effect on this window
Of course frame would have to be non-final or not-initialized previously. I still would recommend using a JDialog however, as well as moving out of the static world and into the instance world
Unrelated criticism:
Less chatty text in your question, text that is completely unrelated to your actual problem at hand, and more text that tells us useful information that helps us to understand your problem and your code, and thereby helping us solve the problem.
Hi though i did complete the basics of java which im fairly new of, i keep getting errors when i try to add buttons on a new Frame/Panel. Care to educate me on what the problem might be?
import javax.swing.*;
import java.awt.*;
class MainClass {
String cont_orders;
private JFrame frame1;
private JPanel mainpanel;
JButton bt1, bt2, bt3, bt4, bt5;
private JButton btotal = new JButton("Order");
private JButton clearOr = new JButton("Clear");
private JTextField pricetotal = new JTextField();
private JTextField list_of_orders = new JTextField();
public MainClass(){
gui();
}
private void gui(){
frame1 = new JFrame("Order");
frame1.setSize(500,430);
frame1.setVisible(true);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setResizable(false);
mainpanel = new JPanel();
mainpanel.setBackground(Color.BLUE);
mainpanel.add(bt1);
bt1 = new JButton("M-Item 1 [Soda]");
frame1.add(mainpanel,BorderLayout.CENTER);
}
public static void main (String[]args){
new MainClass();
}
}
im trying to practice on coding normally instead of relying on that automatic one in NetBeans [JFrame Form/JPanel Form]
care to help?
Now this cannot be done in java
mainpanel.add(bt1);
bt1 = new JButton("M-Item 1 [Soda]");
Turn it around.
Explanation: the field bt1 is at that time a variable holding the null object.
That object (value) is added, not some variable address as in other languages.
Reverse it bt1 = new JButton("M-Item 1 [Soda]"
mainpanel.add(bt1);
Because if not the value of bt1 would be null so you must fill it first then use it .
Or
mainpanel.add(new JButton("..."));
i'm having trouble to get the 2nd frame to display the GUI Components. i've opened the frame using the JButton from the 1st frame.
Here's the screen shot
This is the first frame - ClientModule.java
2nd frame - ClientMenu.java
Here's the codes i've tried
ClientModule.java
import java.net.*;
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ClientModule extends JFrame implements Runnable{
private JPanel panel;
private JFrame frame;
private JLabel titleLbl, userLbl, passLbl, hostLbl, portLbl, ipLbl;
private JTextField userTxt, hostTxt, portTxt, ipTxt;
private JPasswordField passTxt;
private JButton loginBtn;
public static void main(String[] args)
{
new ClientModule().run();
}
public ClientModule()
{
frame = new JFrame("DMS(Drawing Message System)");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
panel = new JPanel();
panel.setPreferredSize(new Dimension(500,500));
panel.setLayout(new FlowLayout());
titleLbl = new JLabel("LogIn to Drawing Message System(DMS)");
titleLbl.setFont(new Font("Rockwell Condensed",Font.BOLD,28));
userLbl = new JLabel("Username:");
passLbl = new JLabel("Password:");
hostLbl = new JLabel("Hostname:");
portLbl = new JLabel("Port No.:");
ipLbl = new JLabel("IP Address:");
userTxt = new JTextField();
userTxt.setPreferredSize(new Dimension(100,30));
passTxt = new JPasswordField();
passTxt.setEchoChar('*');
passTxt.setPreferredSize(new Dimension(100,30));
portTxt = new JTextField();
portTxt.setPreferredSize(new Dimension(100,30));
ipTxt = new JTextField();
ipTxt.setPreferredSize(new Dimension(100,30));
hostTxt = new JTextField();
hostTxt.setPreferredSize(new Dimension(100,30));
loginBtn = new JButton("Login!");
loginBtn.setPreferredSize(new Dimension(90,30));
loginBtn.addActionListener(new LoginBtnListener());
panel.add(titleLbl);
panel.add(userLbl);
panel.add(userTxt);
panel.add(passLbl);
panel.add(passTxt);
panel.add(hostLbl);
panel.add(hostTxt);
panel.add(portLbl);
panel.add(portTxt);
panel.add(ipLbl);
panel.add(ipTxt);
panel.add(loginBtn);
frame.add(panel);
}
private class LoginBtnListener implements ActionListener
{
#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent action)
{
//thinking this frame will close after ClientMenu's frame is open
ClientModule client = new ClientModule();
client.setVisible(false);
ClientMenu menu = new ClientMenu();
menu.setVisible(true);
}
}
public void run()
{
frame.pack();
frame.setVisible(true);
}
}
ClientMenu.java
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
public class ClientMenu extends JFrame{
JFrame frame;
JPanel panel;
JLabel titleLbl;
JButton sendBtn,receiveBtn,logoutBtn;
public ClientMenu()
{
frame = new JFrame("Drawing Message System(DMS)");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.setPreferredSize(new Dimension(500,500));
titleLbl = new JLabel("Main Menu");
titleLbl.setFont(new Font("Rockwell Condensed",Font.BOLD,28));
sendBtn = new JButton("Send a Drawing");
sendBtn.setPreferredSize(new Dimension(100,30));
receiveBtn = new JButton("Receive a Drawing");
receiveBtn.setPreferredSize(new Dimension(100,30));
logoutBtn = new JButton("Logout");
logoutBtn.setPreferredSize(new Dimension(100,30));
logoutBtn.addActionListener(new LogoutBtnListener());
panel.add(titleLbl);
panel.add(sendBtn);
panel.add(receiveBtn);
panel.add(logoutBtn);
frame.add(panel);
}
private class LogoutBtnListener implements ActionListener
{
//#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent action)
{
ClientModule client = new ClientModule();
client.setVisible(true);
ClientMenu menu = new ClientMenu();
menu.setVisible(false);
}
}
public static void main(String[] args)
{
new ClientMenu().run();
}
public void run()
{
frame.pack();
frame.setVisible(true);
}
}
I'm not sure if i'm missing something, or coded something wrong, or something else. I've already searched and tried..
any help and understanding is appreciated (:
I managed to get the second frame displayed (including its contents) by adding a call to the run() method:
ClientMenu menu = new ClientMenu();
menu.setVisible(true);
menu.run();
That being said, there are quite some problems with your code:
You have a main method in each of your classes. You should have only 1 main method per application. Since ClientModule seems to be the first Frame you want to have opened, your might want to keep the main method there and remove the one in the other class.
You have a run() method in each class. Personally, I tend to avoid naming methods like this, since it might cause confusion with the run() method which needs to be overridden when dealing with threads. You are clearly attempting to do some multi threading in your ClientModule, but will not work. Please look into this concurrency tutorial to better understand threads. You should also understand that you should never call run() yourself. The tutorial should make that clear.
Swing applications are started a little bit differently that other applications. Please refer to this tutorial for more information.
You have both your classes extend JFrame but then, provide your own. This results in other JFrames being created, which is what happened in my case (I get 2 JFrames per instantiation). If you want your class to behave like a JFrame, consider extending it, if you want to use a JFrame, then compose your class of one, not both (at least not in this case).
Lastly, to get rid of the previous JFrame you could call dispose() on the it. That being said, the approach usually is to use the Card Layout. This would allow you to have 1 frame with multiple content.
Sorry for the long post, but please consider re factoring as per the above prior to continuing.
You can use the setVisible property to 'true' or 'false'.
I used a plug-in of Eclipse to create the class diagram of this code:
public class ButtonGrid
{
private static int difficulty, moveleft, Counter, treasure_x , treasure_y;
private static String message;
JTextField tf = new JTextField();
public static JTextField tf2 = new JTextField();
JFrame frame = new JFrame(); //creation of the main game window
JPanel panel = new JPanel();
JPanel panel2 = new JPanel(new FlowLayout());
JPanel panel3 = new JPanel();
JLabel hint = new JLabel("Hint:");
JButton[][] grid; //grid buttons
public ButtonGrid (int width, int length)
{
}
ActionListener al = new ActionListener() //Action listener for the buttongrid
{
public void actionPerformed(ActionEvent e)
{
}
};
ActionListener al2 = new ActionListener() // Action listener for the reset button
{
public void actionPerformed (ActionEvent e)
{
}
}
};
public static void main (String[] args)
{
}
I cut some useless parts to reduce the size. The diagram that Eclipse draw is this one:
Do you think it's correct? I'm wondering because i thougth the ActionListeners were considered sub-classes, and also the ActionListener in the main method is not showed, but maybe it's just me not understanding how class diagrams work.
It looks right to me. The ActionListeners you have defined are anonymous classes for your protected attributes a1, and a2. Basically what the anonymous classes are doing is subclassing the ActionListener class. These new, unnamed classes are set to a1, and a2. That is why they show up the way they do in the class diagram. Also the reason that the one in your main method isn't showing up, is that anonymous ActionListener is a local variable to your main function.
Here is some information that Oracle: has about anonymous classes (http://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html)
Hope this help, good luck with your programming.
Your diagram seems correct. None of the variables you create inside the methods will appear in this diagram. Only the variables you define on the top (or outside the methods but inside the class definition) will appear in the diagram:
private static int difficulty, moveleft, Counter, treasure_x , treasure_y;
private static String message;
JTextField tf = new JTextField();
public static JTextField tf2 = new JTextField();
JFrame frame = new JFrame(); //creation of the main game window
JPanel panel = new JPanel();
JPanel panel2 = new JPanel(new FlowLayout());
JPanel panel3 = new JPanel();
JLabel hint = new JLabel("Hint:");
JButton[][] grid; //grid buttons
ActionListener al = new ActionListener() //Action listener for the buttongrid
{
//defintion of this ActionListner
};
ActionListener al2 = new ActionListener() // Action listener for the reset button
{
//definition of this ActionListener
};
ActionListener is actually an interface:
http://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionListener.html
You must define it or else you can't use it. A subclass is a class that has a parent class:
http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
Please let me state that this is for a homework assignment and any help would be appreciated.
I am am writing a program using Eclipse (Juno) that creates a frame, places a ball in the top of the frame and places a row of buttons on the 'south' of the border frame. The issue I am having is in the class that adds the buttons, called Btns.java, I am receiving some errors.
Error 1: add cannot be resolved to a variable
Error 2: Constructor call must be the first statement in a constructor
Error 3: Syntax error on token ".", super expected after this token
The code looks correct to me never the less.
The code for the Btns class is below.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Btns extends JFrame
{
public Btns()
{
JButton jbtL = new JButton("Left");
JButton jbtR = new JButton("Right");
JButton jbtU = new JButton("Up");
JButton jbtD = new JButton("Down");
JButton jbtRd = new JButton("Red");
JButton jbtG = new JButton("Green");
add.(jbtL);
add.(jbtR);
add.(jbtU);
add.(jbtD);
add.(jbtRd);
add.(jbtG);
}
}
Lab2.java Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Lab2 extends JFrame {
public Lab2()
{
setLayout(new BorderLayout());
add(new Ball(), BorderLayout.CENTER);
add(new Btns(), BorderLayout.SOUTH);
}
public static void main (String[] args) {
Lab2 frame = new Lab2();
frame.setTitle("Move The Ball");
frame.setSize(450, 700);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
You have extra dots here before the method parenthesis:
Replace:
add.(jbtL);
add.(jbtR);
add.(jbtU);
...
with
add(jbtL);
add(jbtR);
add(jbtU);
...
add()
is a inherited method from the Component & Container class, so you remove the dots and choose the correct implementation for your case, See javadocs
Have you even written a Java code?
public Btns()
{
JButton jbtL = new JButton("Left");
JButton jbtR = new JButton("Right");
JButton jbtU = new JButton("Up");
JButton jbtD = new JButton("Down");
JButton jbtRd = new JButton("Red");
JButton jbtG = new JButton("Green");
super.add(jbtL);
super.add(jbtR);
this.add(jbtU);
super.add(jbtD);
add(jbtRd);
add(jbtG);
}
The dot is used as a resolution scope operator to indicate that something is a member of a class. super above indicate the super class JFrame, which has the method add derived from Component. this indicate the current object, which is of type Btns, which also has the method add derived from JFrame.
this and super are not necessary qualifiers in most cases, therefore the last two calls don't use super.
Also, if you are adding object of type Btns to your main frame, then you should extend JInternalFrame instead of JFrame.
public class Btns extends javax.swing.JInternalFrame {
Then is constructor:
public Lab2() {
JDesktopPane p = new JDesktopPane();
add(p);
p.add(new Btns());
}