I am a beginner to java and stuck with the below issue.
The purpose is to display the login window when log out button is pressed.
First JFrame window displayed is "Plain" with 2 fields username and password(I will be adding the log in functionality later)
When I press the submit button the JFrame "NEw Window" is displayed with the button "LOGOUT"
What I would like to do is that when the "LOGOUT" is pressed the "NEw Window" should close and the "Plain" window should open.
Present issue: When "LOGOUT" button is pressed the "NEw Window" is opening up.
Please correct the code so that I get the desired functionality
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
class Test implements ActionListener{
JButton submit;
JFrame j;
JFrame jf;
public Test()
{
j = new JFrame("PLAIN");
j.setBounds(500,150,300,400);
j.setVisible(true);
j.setDefaultCloseOperation(j.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
j.add(panel);
panel.setSize(50, 50);
panel.setLayout(null);
JLabel label = new JLabel("User Name");
label.setSize(10,10);
label.setBounds(100, 30, 400, 30);
panel.add(label);
JTextField username = new JTextField(10);
username.setSize(10,10);
username.setBounds(300, 30, 400, 30);
panel.add(username);
JLabel password= new JLabel("Password");
password.setBounds(100, 90, 400, 30);
panel.add(password);
JPasswordField pass = new JPasswordField(10);
pass.setBounds(300, 90, 400, 30);
panel.add(pass);
submit = new JButton("Submit");
submit.setSize(10, 10);
submit.setBounds(300, 160, 200, 40);
panel.add(submit);
submit.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
j.setVisible(false);
jf = new JFrame("NEw Window");
jf.setVisible(true);
jf.setBounds(500,150,300,400);
JPanel panel2 = new JPanel();
panel2.setLayout(null);
jf.add(panel2);
JButton logout = new JButton("LOGOUT");
logout.setBounds(100, 30, 400, 30);
panel2.add(logout);
logout.addActionListener(this);
jf.setDefaultCloseOperation(j.EXIT_ON_CLOSE);
}
public void actionPerformed1(ActionEvent e1) {
jf.dispose();
j.setVisible(true);
}
public static void main(String args[])
{
new Test();
}
}
Some Points:
Call JFrame#setVisible() in the end after adding all the components.
Never use null layout at all instead use proper Layout Manager.
Read more A Visual Guide to Layout Managers where all the layout manger are described in detail along with sample code.
Use SwingUtilities.invokeLater() to make sure that EDT is initialized properly.
Read more
Why to use SwingUtilities.invokeLater in main method?
SwingUtilities.invokeLater
Try with WindowConstants.DISPOSE_ON_CLOSE instead of JFrame.EXIT_ON_CLOSE.
Just put j.setVisible(true) from Test() at the end, after adding all the components.
If you want to make a new form, don't do it in the same class where you already have one because it isn`t right.
Read the book named Clean code. You also have some errors in your code and useless.
Related
I'm very new to Java and being the GUI obsessed freak I am, got drawn to Swing. I have not much experience with Java (really basic knowledge) and I've started making a game. I want to use Swing for it and have started with some basic code for the login/register system under the guidance of a website.
However, they don't tell me how to make a button run a command, so, I scoured the internet and found ActionListener but I'm not sure how to use it. I've tried implementing it in my code but I get an error for it. I'm don't know what is wrong, I can't find anything useful on how to fix this error:
Apiary is not abstract and does not override abstract method
actionPerformed(java.awt.event.ActionListener) in
java.awt.event.ActionListener
Here is my code:
import javax.swing.*;
import java.awt.event.ActionListener;
public class Apiary implements ActionListener {
public static void main(String[]args) {
JFrame frame = new JFrame("Apiary");
frame.setSize(350, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
placeComponents(panel);
frame.setVisible(true);
panel.addActionListener(placeComponents);
}
private static void placeComponents(JPanel panel) {
panel.setLayout(null);
JLabel usernameLabel = new JLabel("Username");
usernameLabel.setBounds(10,20,80,25);
panel.add(usernameLabel);
JTextField userText = new JTextField(20);
userText.setBounds(100,20,165,25);
panel.add(userText);
JLabel passwordLabel = new JLabel("Password");
passwordLabel.setBounds(10,50,80,25);
panel.add(passwordLabel);
JPasswordField passwordText = new JPasswordField(20);
passwordText.setBounds(100,50,165,25);
panel.add(passwordText);
JButton loginButton = new JButton("Login");
loginButton.setBounds(10, 80, 80, 25);
panel.add(loginButton);
}
}
How can I fix the Java error: myClass is not abstract and does not override abstract method?
Add an actionPerformed(ActionEvent) method. Be sure to add the #Override notation. See other changes as noted in this working example.
import javax.swing.*;
import java.awt.event.*;
public class Apiary implements ActionListener {
private static void placeComponents(JPanel panel) {
panel.setLayout(null);
JLabel usernameLabel = new JLabel("Username");
usernameLabel.setBounds(10,20,80,25);
panel.add(usernameLabel);
JTextField userText = new JTextField(20);
userText.setBounds(100,20,165,25);
panel.add(userText);
JLabel passwordLabel = new JLabel("Password");
passwordLabel.setBounds(10,50,80,25);
panel.add(passwordLabel);
JPasswordField passwordText = new JPasswordField(20);
passwordText.setBounds(100,50,165,25);
panel.add(passwordText);
JButton loginButton = new JButton("Login");
loginButton.setBounds(10, 80, 80, 25);
panel.add(loginButton);
Apiary apiary = new Apiary();
loginButton.addActionListener(apiary);
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("ToDo!");
}
public static void main(String[]args) {
JFrame frame = new JFrame("Apiary");
frame.setSize(350, 150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
placeComponents(panel);
frame.setVisible(true);
}
}
General tips:
For a log-in, I'd recommend using a modal JDialog or a JOptionPane instead of a JFrame to display it. See The Use of Multiple JFrames, Good/Bad Practice?
Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or combinations of them along with layout padding and borders for white space.
I have created a simple Login Frame using a JFrame.
I have hardcoded validations wherein if a user enters username as AKASH and password as 12345 then Login Success is displayed below the Button else Wrong Password is displayed.
Everything is working fine.The only thing is :
I have to double click to see the result after entering the details
Could anyone please help me on this.
Here is my code :
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LginForm extends JFrame implements ActionListener{
Container c;
JTextField jt;
JButton jb;
JPasswordField jp;
JLabel jl1,jl2;
JLabel jl3 = new JLabel("Wrong Password");
JLabel jl4 = new JLabel("Login Successful");
public static void main(String[] args) {
LginForm lf = new LginForm();
lf.setBounds(100, 50, 500, 400);
lf.setVisible(true);
lf.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public LginForm() {
c = this.getContentPane();
c.setBackground(Color.yellow);
c.setLayout(null);
jl1 = new JLabel("Enter Username");
jl1.setBounds(50, 10, 100, 30);
jl1.setFont(new Font(Font.SANS_SERIF, Font.ITALIC, 12));
jl2 = new JLabel("Enter Password");
jl2.setBounds(50, 100, 100, 30);
jl2.setFont(new Font(Font.SANS_SERIF, Font.ITALIC, 12));
jt = new JTextField();
jt.setBounds(200,10,100,30);
jp = new JPasswordField();
jp.setBounds(200,100,100,30);
jb = new JButton("login");
jb.setBounds(130,180,80,30);
c.add(jl1);
c.add(jl2);
c.add(jt);
c.add(jp);
c.add(jb);
jb.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent event) {
if(event.getSource() == jb) {
String usrname = jt.getText();
String passwrd = String.valueOf(jp.getPassword());
if(usrname.equals("Akash") && passwrd.equals("12345")) {
jl4.setBounds(100, 230, 150, 40);
jl4.setFont(new Font(Font.SANS_SERIF, Font.ITALIC, 12));
c.add(jl4);
c.remove(jl3);
}
else {
jl3.setBounds(100, 230, 150, 40);
jl3.setFont(new Font(Font.SANS_SERIF, Font.ITALIC, 12));
c.add(jl3);
c.remove(jl4);
}
}
}
}
This the login frame created
c.add(jl4);
c.remove(jl3);
I would guess that after adding/removing components from the panel you need to invoked repaint() the panel.
This is only a guess because you should NOT be using a null layout. Swing was designed to be used with layout managers. Let the layout manager determine the size/location of components based on the rules the layout manager.
Then when you add/remove components from a panel the basic logic would be:
panel.remove(...);
panel.add(...);
panel.revalidate();
panel.repaint();
Read the Swing tutorial on Using Layout Managers for more information.
Note:
I would also suggest a simpler solution is to add the "message label" to the panel with text set to " ". Then you can simply use the setText(...) method of the label to change the message. This way you don't even need to worry about adding/removing components.
So, i have my main screen showing and i would like it so that when the user clicks "Login" is loads another screen. I have my second screen in another function called "fixtureLists". When i call this function it just overlays the buttons ontop of the login screen. How would i get it so that the screen is cleared and then the fixtureLists screen loads?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Main extends JFrame
{
public Main()
{
loginButton = new JButton("Login");
loginButton.setBounds( 125, 300, 100, 35);
add(loginButton);
loginButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
fixtureList();
System.out.println("Loading the fixtures screen");
}
});
}
public void fixtureList()
{
JButton editButton;
JButton createButton;
JCheckBox chkBox;
setLayout(null);
editButton = new JButton("Edit");
editButton.setBounds( 10, 10, 100, 35);
add(editButton);
createButton = new JButton("Create");
createButton.setBounds( 140, 10, 100, 35);
add(createButton);
editButton = new JButton("Edit");
createButton.setBounds( 10, 30, 100, 35);
}
public static void main(String args[])
{
Main window = new Main();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setSize(250, 430);
window.getContentPane().setBackground(new Color(53, 56, 64));
window.setVisible(true);
window.setTitle("PE Timetable v1.0");
}
}
I would not define the login dialog in the main frame.
Your login dialog should pop up in a dialog over the frame.
Having said that, if you want the login on the same frame, then use Cardlayout. On one Cardlayout have your login stuff, then when you login, switch the cardlayout to another panel.
Please take a look at my code it is working fine the way I want but the only issue is that I want to add another button opposite my current button and I am not able to do so can any body please help me.
import java.awt.event.*;
import javax.swing.*;
public class Example2 extends JFrame {
public Example2() {
initUI();
}
public final void initUI() {
JPanel panel = new JPanel();
getContentPane().add(panel);
panel.setLayout(null);
panel.setToolTipText("A Panel container");
JButton button = new JButton("Even");
button.setBounds(100, 60, 100, 30);
button.setToolTipText("A button component");
JButton button2 = new JButton("Odd");
button2.setBounds(100, 60, 100, 30);
button2.setToolTipText("A button component");
//Add action listener to button
button.addActionListener(new ActionListener () {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System .out.println("You clicked the button");
int sum=0;
for(int i=1;i<=100;i++){
if(i%2==0){
System.out.println(i);
sum+=i;
}
}
System.out.println("Sum of even numbers: "+sum);
}
});
panel.add(button);
panel.add(button2);
setTitle("Tooltip");
setSize(500, 400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Example2 ex = new Example2();
ex.setVisible(true);
}
}
panel.setLayout(null);
That is where it starts to go wrong.
Use layouts. See Laying Out Components Within a Container & Effective Layout Management: Short Course for more details.
Use:
The appropriate layouts.
Possibly nested inside one another.
With appropriate layout padding and component border/insets for white space.
As an aside.
...
button.setBounds(100, 60, 100, 30);
button.setToolTipText("A button component");
JButton button2 = new JButton("Odd");
button2.setBounds(100, 60, 100, 30);
...
Did you notice how the bounds of the two buttons were identical? What do you think happens when you put two components of the same size in the same place?
You have to change panel.setLayout(null) to layout you need. For example:
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
or
panel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER));
Andrew Thompson +1 ,
Here are some usefull links :
A Visual Guide to Layout Managers
Using Layout Managers
Adding space between components
on button click, new window(internal frame) should open, what's wrong with my code?
can somebody explain the relationship between desktopane and internalframe and just
regular contentpane?
import javax.swing.*;
import java.awt.event.*;
public class tuna extends JFrame{
private JButton button1;
JDesktopPane desktop;
JInternalFrame internalFrame;
public tuna(){
super("iLyrics");
desktop = new JDesktopPane();
add(desktop);
button1 = new JButton("Open Internal Frame");
add(button1);
button1.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
JInternalFrame internalFrame = new JInternalFrame("Internal Frame", true, true, true, true );
internalFrame.setBounds(110, 130, 105, 70);
desktop.add(internalFrame, JLayeredPane.DEFAULT_LAYER);
//desktop.add(internalFrame);
internalFrame.setVisible(true);
}
});
}
}
}
It looks like you're adding the desktop and the button to the CENTER of the content pane, making the button replace the desktop pane, so you'll never see it.
// put the desktop in the center
desktop = new JDesktopPane();
getContentPane().add(desktop, BorderLayout.CENTER);
// but the button at the top
button1 = new JButton("Open Internal Frame");
getContentPane().add((button1, BorderLayout.NORTH);
I don't believe you can add a frame to a pane. If you look at the hierarchy of swing containers. It would go Label -> Pane -> Frame. I think the problem with your code is when your doing
desktop.add(internalFrame);
I would change desktop to be a new JFrame
desktop = new JFrame();
http://docs.oracle.com/javase/tutorial/uiswing/components/toplevel.html
This post talks about your relationship with top-level containers.
add this code after you create jinternaframe:
internalFrame.setBounds(110, 130, 105, 70);
desktopPane.add(internalFrame, JLayeredPane.DEFAULT_LAYER);