I have this piece of my code that doesn't work, it refuses to recognize the equal sign, it says error: '(' or '[' expected new newframe = new frame(); with an up arrow pointing to the = sign. However, even when I put in the ( and [, it still doesn't work. I am unsure what to do as I've never encountered this issue before. Any type of advice would be greatly appreciated, the full code is below. I am still very new to java so forgive me if this is something simple that I missed, I couldn't find any info elsewhere that helped me really. Thank you for any help
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
class LoginFrame extends JFrame implements ActionListener {
Container container=getContentPane();
JLabel userLabel=new JLabel("USERNAME");
JLabel passwordLabel=new JLabel("PASSWORD");
JTextField userTextField=new JTextField();
JPasswordField passwordField=new JPasswordField();
JButton loginButton=new JButton("LOGIN");
JButton resetButton=new JButton("RESET");
JCheckBox showPassword=new JCheckBox("Show Password");
LoginFrame()
{
setLayoutManager();
setLocationAndSize();
addComponentsToContainer();
}
public void setLayoutManager()
{
container.setLayout(null);
}
public void setLocationAndSize()
{
userLabel.setBounds(50,150,100,30);
passwordLabel.setBounds(50,220,100,30);
userTextField.setBounds(150,150,150,30);
passwordField.setBounds(150,220,150,30);
showPassword.setBounds(150,250,150,30);
loginButton.setBounds(50,300,100,30);
resetButton.setBounds(200,300,100,30);
}
public void addComponentsToContainer()
{
container.add(userLabel);
container.add(passwordLabel);
container.add(userTextField);
container.add(passwordField);
container.add(showPassword);
container.add(loginButton);
container.add(resetButton);
}
public void actionPerformed(ActionEvent e) {
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String puname = userLabel.getText();
String ppaswd = passwordLabel.getText();
if(puname.equals("teacher") && ppaswd.equals("123"))
{
new newframe = new frame();
frame.setVisible(true);
dispose();
}
else {
JOptionPane.showMessageDialog(null,"Wrong Password / Username");
userLabel.setText("");
passwordLabel.setText("");
userLabel.requestFocus();
}
}
});
}
}
It looks like your problem is here.
new newframe = new frame();
Did you mean to do this instead?
JFrame newframe = new JFrame();
If so, then I will break this down into parts, just to explain what is going on.
JFrame newframe -- This tells java that you have a variable called newframe that can only be a type of JFrame. Right now, newframe does NOT have a value, it's just an empty box that can hold a JFrame if you give it one.
= new JFrame(); -- This tells java that NOW you want to give the variable newframe a new JFrame. Remember, up until this point, newframe was an empty box. But this piece of code's job is to actually put a JFrame into that box.
Let us know if that solves your problem.
Just from looking at it, I'm pretty sure it's the way you're declaring it.
In Java, you only use the "new" keyword on the right side of the declaration.
Instead of new newframe = new frame();
Try the line frame newframe = new frame();
If that's not it, I'm not really sure. Let me know though, and I'll actually boot it up and give it a spin.
new keyword is used in Java to create an instance of a class. This instance can then be assigned to a variable that has a type that is compatible with the class for which the instance was created.
For example, in your code, with new frame() you are creating an object of type frame. You want to assign this object to a variable probably, in which case, the correct way to do that will frame someVariable = new frame()
Related
This might be a very basic question. But I am stuck at this. The error that I get for the String variable display states:
Cannot refer to the non-final local variable display defined in an enclosing scope.
If I use a final keyword, I get the message:
The final local variable display cannot be assigned, since it is defined in an enclosing slope.*
The code is:
public class Frame {
public static void main(String[] args) {
String display=" ";
Frame ob=new Frame();
JFrame frame=new JFrame("Test");
frame.setBounds(300,100,800,500);
//Container c=frame.getContentPane();
frame.setLayout(null);
final JTextField name=new JTextField();
name.setBounds(500,212,150,20);
JLabel nameLabel=new JLabel("Name: ");
nameLabel.setForeground(Color.WHITE);
nameLabel.setBounds(450,171,100,100);
JTextField ohr=new JTextField();
ohr.setBounds(500,282,150,20);
JLabel ohrID=new JLabel("OHR ID: ");
ohrID.setForeground(Color.WHITE);
ohrID.setBounds(450,241,100,100);
final JButton button=new JButton("Submit");
button.setBounds(530,350,90,20);
frame.add(name);
frame.add(ohr);
frame.add(ohrID);
frame.add(nameLabel);
frame.add(button);
frame.getContentPane().setBackground(Color.DARK_GRAY);
frame.setVisible(true);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(e.getSource()==button){
display=name.getText();
JOptionPane.showMessageDialog(null, "Hi "+ display);
System.exit(0);
}
}
});
}
Thanks in advance!
There are multiple issues with your code, and we'll address them right here, right now and solve your problem at the same time.
public class Frame { this particular line has an error, Frame is the name of an AWT class, so it might confuse you or anyone who reads this code later on, give it a more meaningful name and avoid those names that could be confused with other Java packages.
Frame ob=new Frame(); you create an instance of your class and never use it again, why?
frame.setLayout(null); NEVER, please don't use null-layout, Swing has to deal with multiple PLAFs, screen sizes and resolutions, different OS, pixel perfect apps might seem like the easiest way to create complex UIs but later on you'll find that errors like this happen very often.
.setBounds(...) on every component, again, this is due to null-layout but it's better to use Layout managers
final JTextField name=new JTextField(); There's no need to declare any of your components as final, this is due to a poor design of your class, your components should be declared as class members (outside any method including main).
Speaking about main, separate your program into smaller pieces, don't throw everything at main or at the very least create a method that is not static so you can call it after creating an instance of your class (or else later on you'll end up with tons of static variables and that's a poor design of your class once again).
System.exit(0); it will stop the JVM, it's never a good idea to do that, it's better to .dispose() the JFrame and have your JFrame's defaultCloseOperation set to EXIT_ON_CLOSE which will safely dispose your app and then stop the JVM.
display=name.getText();, for this particular case, display could be an inner variable rather than a class member. This will solve your particular question
JOptionPane.showMessageDialog(null, "Hi "+ display); that null should be a reference to your JFrame, this will place your dialog in the middle of that JFrame rather than in the middle of the screen.
You never place your program inside the EDT, see point #2 in this answer.
So, having all the above points in mind, here's an improved version of your code.
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class UsingVariablesInsideActionListenerExample {
//We declare our components here
private JFrame frame;
private JButton button;
private JTextField name;
private JTextField ohr;
private JLabel nameLabel;
private JLabel ohrID;
private JPanel pane;
private JPanel namePane;
private JPanel ohrPane;
public static void main(String[] args) {
SwingUtilities.invokeLater(new UsingVariablesInsideActionListenerExample()::createAndShowGUI); //This is using Java 8 lambdas to place your program in the EDT
}
private void createAndShowGUI() {
frame = new JFrame("Test"); //Create your JFrame
pane = new JPanel();
pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS)); //This will make this JPanel to arrange components vertically
namePane = new JPanel(); //By default, JPanels have FlowLayout which will arrange components horizontally
ohrPane = new JPanel();
name = new JTextField(10); //We create a JTextField with 10 columns
nameLabel = new JLabel("Name: ");
nameLabel.setForeground(Color.WHITE);
ohr = new JTextField(10);
ohrID = new JLabel("OHR ID: ");
ohrID.setForeground(Color.WHITE);
button = new JButton("Submit");
//Add the action listener
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
String display = name.getText(); //The display variable is now an inner variable rather than a class member
JOptionPane.showMessageDialog(frame, "Hi " + display);
frame.dispose(); //We dispose the JFrame and it will be closed after due to EXIT_ON_CLOSE below.
}
}
});
//We add the components to the namePane (horizontally), the order matters
namePane.add(nameLabel);
namePane.add(name);
//Now we add these components to the ohrPane (horizontally again)
ohrPane.add(ohrID);
ohrPane.add(ohr);
//We then add the name and ohr panes to a bigger JPanel (pane, which if you remember will add them vertically) and we add the button at the end
pane.add(namePane);
pane.add(ohrPane);
pane.add(button);
//We make them non opaque (transparent) so that we can see the background color of the JFrame
namePane.setOpaque(false);
ohrPane.setOpaque(false);
pane.setOpaque(false);
frame.add(pane);
frame.getContentPane().setBackground(Color.DARK_GRAY);
frame.pack(); //This will get every component's preferred size and make the JFrame as small as possible where it looks good on every OS, PLAF, screen size and resolution.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true); //We make the frame visible (always at the very end, when we've added everything to it).
}
}
And this is how it looks like now.
The UI may not be perfectly equal to the one you have, but I'm sure you can play with the different layout managers, and nest various JPanels to get a much better looking UI than mine, or at least a more similar one to the one you had.
Variable used in side an inner class should be effectively final . You can use a string[] of length 1 instead of string to resolve this . Please read bellow post for more details
Difference between final and effectively final
Also check this post for more details
Variable used in lambda expression should be final or effectively final
I'm working through a book, and the following code throws a NPE at runtime when the JButton is clicked, at the line button.actionPerformed. I've done my best to be sure my code is exactly what is in the book, can someone point out my problem? (the book was written for java 5, I'm using the latest java 7, this shouldn't make a difference in the following code as far as I know though)
import javax.swing.*;
import java.awt.event.*;
public class SimpleGui implements ActionListener {
JButton button;
public static void main(String[] args) {
SimpleGui gui = new SimpleGui();
gui.go();
}
public void go() {
JFrame frame = new JFrame();
JButton button = new JButton("click here");
button.addActionListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(button);
frame.setSize(300,300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
button.setText("I've been clicked, argh!");
}
}
The reason is this Line:
JButton button = new JButton("click here");
Here you are creating new local JButton object which is shadowing the member variable button . Hence button is still null. You should instead use:
button = new JButton("click here");
In a method, you have this:
JButton button = new JButton("click here");
This create the variable, but the scope of this new variable is inside the method. You've already declared button in your class though. It should just be:
button = new JButton("click here");
You're shadowing your variables.
You declare button as a class variable, but the re-declare within your go method, meaning that the class variable (which you reference within your actionPerformed method) is null
Change JButton button = new JButton("click here"); to button = new JButton("click here");
Well, your JButton button; is still null.you are not assigned it anywhere in your programm
This problem is known as "Variable Hiding" or "Hidden Variables" or "Shadowing Variables". Which means, a local variable hides another variable which has the same name. You have re defined your variable button inside the go method. Just removed the re definition from the go method, so it will work fine. Have a look at the following code
import javax.swing.*;
import java.awt.event.*;
public class SimpleGui implements ActionListener {
JButton button;
public static void main(String[] args) {
SimpleGui gui = new SimpleGui();
gui.go();
}
public void go() {
JFrame frame = new JFrame();
button = new JButton("click here"); //Variable Re definition removed
button.addActionListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(button);
frame.setSize(300,300);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event) {
button.setText("I've been clicked, argh!");
}
}
Since you seems to be new to the Java GUI, take the following few advises.
It is always a best practice to define your class variables inside the constructor
Use access specifiers. private is a good specifier for your button variable
Even though the constructor can be automatically get created (default constructor) it is a best practice to code it by your self, at least a blank one.
[UPDATE] i fixed the problem. user "Hovercraft Full Of Eels" was right, i changed 3D graphics settings prefer to nvidea driver and problem fixed
i have problem and can't understand what is matter.
i am creating simple GUI window and putting JTextField object on it.
when i run project and enter text in text field it does not displays properly.
i already tryed to reinstal java, but can't fix problem.
can anyone help me?
here is my GUI window image
here is my code (no exception thrown, nor error was occured!)
package test;
import javax.swing.*;
import java.awt.*;
public class MainClass {
public static void main(String[] args) {
new Form().Run();
}
}
class Form{
JFrame form = new JFrame();
JButton btn = new JButton();
JTextField txt = new JTextField();
public Form(){
form.setLayout(new FlowLayout());
form.setSize(500, 500);
form.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btn.setText("caption");
form.add(btn);
txt.setColumns(10);
form.add(txt);
}
public void Run(){
form.setVisible(true);
}
}
Try to change your "Look and Feel" settings in your GUI-Class, there should be the string "Nimbus". Change it to "Windows" and try it again. The second thing you can try is to set a Border to your JTextfield, probably it works.
The code for changing or to set a Border on your JTextfield:
JTextField your_field = new JTextField(10);
your_field.setBorder(BorderFactory.createMatteBorder(0, 0, 5, 0, Color.black));
I'm trying to get my program to launch a gui that gathers information before the actual programs starts. In main I try to call the JFrame which should then run until the start button is pressed and then the main program should launch. Everything seems to be correct except for the base class of the initializeLauncher. Thanks!
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class InitializeLauncher implements ActionListener {
InitializeLauncher() {
JFrame frame = new JFrame("launcherClient");
Container c = frame.getContentPane();
Dimension d = new Dimension(700,400);
c.setPreferredSize(d);
JButton startButton = new JButton("Start");
JPanel pane = new JPanel();
startButton.addActionListener(this);
pane.add(startButton);
frame.add(pane);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
}
public void buttonClicked(ActionEvent e)
{
ApplicationDeploy displayExample = new ApplicationDeploy();
displayExample.initializeGameClient();
}
}
...and then in main I call this:
InitializeLauncher launcher = new InitializeLauncher();
launcher.InitializeLauncher();
By making your class abstract, you're fixing the wrong thing. Instead you should give your class the missing method, public void actionPerformed(ActionEvent e) {...}
The basic rule here is, if you state that your class is going to implement an interface, here the ActionListener interface, then the class must implement all of the methods of the interface.
#Override
public void actionPerformed(ActionEvent e) {
// ... your code that should occur when the button is pressed goes here
}
Note that your buttonClicked(...) method will do nothing useful for you. Likely you'll want to get rid of that method and put its code into the actionPerformed method.
As an aside, I often use a JOptionPane for the functionality that you're using a JFrame for.
it's a shame that my first question on SO is so stupid but i can't manage to get around this thing.
After hours of "distilling" i have reduced the issue to this:
Using Netbeans i've made a JFrame, and put a Jbutton1 and a JTextField(named sinonimo) in it.
The idea is to use the text field to grab user input. so i set the onClick action of the button like this
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
System.out.println(sinonimo.getText());
}
Problem is: i can type anything in the text field, the getText() method will return only the string set in the "text" properties in Netbeans, it will never change.
Am i missing something huge about java? can someone point me in the right direction?
EDIT: while copying the complete code i found the problem: in the constructor of the frame, initComponents() was called two times, generating another copy of the textfield inaccessible from the MouseClicked event(i think). Now everything seem to work nicely, thank you guys for the lighting responses!
Using a JTextField, if you call getText() it will return null should the index be out of range or the Document is null. If you could post more code I could help further with this issue. With the following code this works perfectly fine.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Test {
public static void main(final String[] args) {
final JFrame frame = new JFrame();
final JButton button = new JButton("Print");
final JTextField field = new JTextField();
frame.setLayout(new BorderLayout());
frame.add(button, BorderLayout.NORTH);
frame.add(field, BorderLayout.SOUTH);
frame.setVisible(true);
frame.pack();
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(field.getText());
}
});
}
}
From what I can see, until you post more code, is that either the method you print it from is not being used, the document is returning null or that the sinonimo instance was not added correctly and doesn't function how it should.