Related
I am trying to implement an image appearing when a button is pressed. For this purpose I thought I could just copy the concept of button 4 (which works) and exchange the System.exit(0) with code to add an image, but while I've been able to use that code elsewhere successfully, here it does not seem to work.
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JSpinner;
import java.awt.Color;
import java.util.ArrayList;
public class Mainframe {
private JFrame frmOceanlife;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Mainframe window = new Mainframe();
window.frmOceanlife.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Mainframe() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmOceanlife = new JFrame();
frmOceanlife.setTitle("OceanLife");
frmOceanlife.setBounds(100, 100, 750, 600);
frmOceanlife.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmOceanlife.getContentPane().setLayout(null);
JButton btnNewButton_4 = new JButton("Quit");
btnNewButton_4.setBounds(640, 6, 81, 29);
frmOceanlife.getContentPane().add(btnNewButton_4);
btnNewButton_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
JButton btnNewButton_5 = new JButton("Einfügen");
btnNewButton_5.setBounds(410, 34, 103, 29);
frmOceanlife.getContentPane().add(btnNewButton_5);
btnNewButton_5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ImageIcon icon = new ImageIcon("Stone.png");
JLabel label = new JLabel(icon);
// label.setBounds(25,25,50,50);
frmOceanlife.getContentPane().add(label);
}
});
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
panel.setBounds(70, 75, 600, 450);
panel.setLayout(new FlowLayout());
JLabel piclabel = new JLabel(new ImageIcon("underwater-600x450.png"));
panel.add(piclabel);
frmOceanlife.getContentPane().add(panel);
JLabel lblNewLabel_2 = new JLabel("Welcome to Oceanlife - Your Ocean size is 600x450!");
lblNewLabel_2.setBounds(6, 539, 334, 16);
frmOceanlife.getContentPane().add(lblNewLabel_2);
}
}
The problem is that you are creating a new JLabel and trying to add it to the frame, once the button is pressed. Instead, you should just change the Icon of the label that is already added to the frame (i.e., piclabel), using piclabel.setIcon(icon);. So, you should declare picLabel at the start of your code, so that it can be accessible in the actionPerformed method of your button.
public class Mainframe {
private JFrame frmOceanlife;
JLabel piclabel;
...
Then, instantiate the label in the initialize() method as below:
...
panel.setBounds(70, 75, 600, 450);
panel.setLayout(new FlowLayout());
piclabel = new JLabel(new ImageIcon("underwater-600x450.png"));
...
Finally, your actionPerformed method for btnNewButton_5 (please consider using descriptive names instead) should look like this:
btnNewButton_5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ImageIcon icon = new ImageIcon("Stone.png");
piclabel.setIcon(icon);
}
});
Update
If, however, what you want is to add a new JLabel each time, and not change the icon of the existing one, you could use Box object with BoxLayout added to a ScrollPane. Then add the ScrollPane to your JFrame. Working example is shown below, based on the code you provided (again, please consider using descriptive names and removing unecessary code):
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.*;
import javax.swing.*;
public class Mainframe {
private JFrame frmOceanlife;
Box box;
JScrollPane scrollPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Mainframe mf = new Mainframe();
mf.initialize();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
JButton insertBtn = new JButton("Einfügen");
insertBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ImageIcon icon = new ImageIcon("Stone.png");
JLabel label = new JLabel(icon);
box.add(Box.createRigidArea(new Dimension(0, 5)));// creates space between the JLabels
box.add(label);
frmOceanlife.repaint();
frmOceanlife.revalidate();
Rectangle bounds = label.getBounds();
scrollPane.getViewport().scrollRectToVisible(bounds);// scroll to the new image
}
});
JButton quitBtn = new JButton("Quit");
quitBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
box = new Box(BoxLayout.Y_AXIS);
JLabel piclabel = new JLabel(new ImageIcon("underwater-600x450.png"));
box.add(piclabel);
scrollPane = new JScrollPane(box);
Dimension dim = new Dimension(box.getComponent(0).getPreferredSize());
scrollPane.getViewport().setPreferredSize(dim);
scrollPane.getVerticalScrollBar().setUnitIncrement(dim.height);
scrollPane.getViewport().setBackground(Color.WHITE);
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
controlPanel.add(insertBtn);
controlPanel.add(quitBtn);
JLabel titleLbl = new JLabel("Welcome to Oceanlife - Your Ocean size is 600x450!", SwingConstants.CENTER);
frmOceanlife = new JFrame();
frmOceanlife.getContentPane().add(titleLbl, BorderLayout.NORTH);
frmOceanlife.getContentPane().add(scrollPane, BorderLayout.CENTER);
frmOceanlife.getContentPane().add(controlPanel, BorderLayout.SOUTH);
frmOceanlife.setTitle("OceanLife");
frmOceanlife.pack();
frmOceanlife.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmOceanlife.setLocationRelativeTo(null);
frmOceanlife.setVisible(true);
}
}
Here is a sample application demonstrating the use of CardLayout. Note that I used [Eclipse] WindowBuilder. All the below code was generated by WindowBuilder apart from the ActionListener implementations. Also note that the ActionListener implementation for quitButton uses a lambda expression while the insertButton implementation uses a method reference.
More notes after the code.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import javax.swing.JLabel;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import javax.swing.ImageIcon;
import javax.swing.JButton;
public class MainFram {
private JFrame frame;
private JPanel cardsPanel;
private JPanel firstPanel;
private JLabel firstLabel;
private JPanel secondPanel;
private JLabel secondLabel;
private JPanel buttonsPanel;
private JButton insertButton;
private JButton quitButton;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFram window = new MainFram();
window.frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainFram() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(getCardsPanel(), BorderLayout.CENTER);
frame.getContentPane().add(getButtonsPanel(), BorderLayout.SOUTH);
}
private JPanel getCardsPanel() {
if (cardsPanel == null) {
cardsPanel = new JPanel();
cardsPanel.setLayout(new CardLayout(0, 0));
cardsPanel.add(getFirstPanel(), "first");
cardsPanel.add(getSecondPanel(), "second");
}
return cardsPanel;
}
private JPanel getFirstPanel() {
if (firstPanel == null) {
firstPanel = new JPanel();
firstPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
firstPanel.add(getFirstLabel());
}
return firstPanel;
}
private JLabel getFirstLabel() {
if (firstLabel == null) {
firstLabel = new JLabel("");
firstLabel.setIcon(new ImageIcon(getClass().getResource("underwater-600x450.png")));
}
return firstLabel;
}
private JPanel getSecondPanel() {
if (secondPanel == null) {
secondPanel = new JPanel();
secondPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
secondPanel.add(getLabel_1());
}
return secondPanel;
}
private JLabel getLabel_1() {
if (secondLabel == null) {
secondLabel = new JLabel("");
secondLabel.setIcon(new ImageIcon(getClass().getResource("Stone.png")));
}
return secondLabel;
}
private JPanel getButtonsPanel() {
if (buttonsPanel == null) {
buttonsPanel = new JPanel();
buttonsPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
buttonsPanel.add(getInsertButton());
buttonsPanel.add(getQuitButton());
}
return buttonsPanel;
}
private JButton getInsertButton() {
if (insertButton == null) {
insertButton = new JButton("Einfügen");
insertButton.addActionListener(this::insertAction);
}
return insertButton;
}
private JButton getQuitButton() {
if (quitButton == null) {
quitButton = new JButton("Quit");
quitButton.addActionListener(e -> System.exit(0));
}
return quitButton;
}
private void insertAction(ActionEvent event) {
CardLayout cardLayout = (CardLayout) cardsPanel.getLayout();
cardLayout.next(cardsPanel);
}
}
The above code requires that the image files, i.e. underwater-600x450.png and Stone.png, be located in the same directory as file MainFram.class. Refer to How to Use Icons.
When you click on the insertButton, the panel containing the underwater-600x450.png image is hidden and the panel containing the Stone.png image is displayed. Clicking the insertButton a second time will hide Stone.png and display underwater-600x450.png. In other words, clicking the insertButton toggles the images.
The first thing to do is using layout managers instead of setting bounds manually:
import java.awt.*;
import javax.swing.*;
public class Mainframe {
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
try {
new Mainframe();
} catch (Exception e) {
e.printStackTrace();
}
});
}
/**
* Create the application.
*/
public Mainframe() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
JFrame frmOceanlife = new JFrame();
frmOceanlife.setTitle("OceanLife");
//frmOceanlife.setBounds(100, 100, 750, 600);
frmOceanlife.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frmOceanlife.getContentPane().setLayout(null);
frmOceanlife.setLayout(new BoxLayout(frmOceanlife.getContentPane(), BoxLayout.PAGE_AXIS));
JButton btnNewButton_4 = new JButton("Quit");
btnNewButton_4.addActionListener(e -> System.exit(0));
//btnNewButton_4.setBounds(640, 6, 81, 29);
JPanel quitPanel = new JPanel();
quitPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
quitPanel.add(btnNewButton_4);
frmOceanlife.getContentPane().add(quitPanel);
JPanel stonesPanel = new JPanel();
frmOceanlife.getContentPane().add(stonesPanel);
JButton btnNewButton_5 = new JButton("Insert");
//btnNewButton_5.setBounds(410, 34, 103, 29);
btnNewButton_5.addActionListener(e -> {
ImageIcon icon = new ImageIcon("Stone.png");
JLabel label = new JLabel(icon);
//label.setBounds(25,25,50,50);
stonesPanel.add(label);
frmOceanlife.revalidate();
});
JPanel insertPanel = new JPanel();
insertPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
insertPanel.add(btnNewButton_5);
frmOceanlife.getContentPane().add(insertPanel);
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
//panel.setBounds(70, 75, 600, 450);
panel.setLayout(new FlowLayout());
panel.setPreferredSize(new Dimension(700,550));
JLabel piclabel = new JLabel(new ImageIcon("underwater-600x450.png"));
panel.add(piclabel);
frmOceanlife.getContentPane().add(panel);
JLabel lblNewLabel_2 = new JLabel("Welcome to Oceanlife - Your Ocean size is 600x450!");
//lblNewLabel_2.setBounds(6, 539, 334, 16);
JPanel infoPanel = new JPanel();
infoPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
infoPanel.add(lblNewLabel_2);
frmOceanlife.getContentPane().add(infoPanel);
frmOceanlife.pack();
frmOceanlife.setVisible(true);
}
}
Next, let's introduce better names and use publicly available images to make the code more readable and more of an mre:
import java.awt.*;
import java.net.*;
import javax.swing.*;
public class Mainframe {
private static final String STONE = "https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/32x32/Circle_Red.png",
OCEAN ="https://media-gadventures.global.ssl.fastly.net/media-server/dynamic/blogs/posts/robin-wu/2014/12/PB110075.jpg";
public Mainframe() {
initialize();
}
private void initialize() {
JFrame frmOceanlife = new JFrame();
frmOceanlife.setTitle("OceanLife");
frmOceanlife.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmOceanlife.setLayout(new BoxLayout(frmOceanlife.getContentPane(), BoxLayout.PAGE_AXIS));
JButton quitBtn = new JButton("Quit");
quitBtn.addActionListener(e -> System.exit(0));
JPanel quitPanel = new JPanel();
quitPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
quitPanel.add(quitBtn);
frmOceanlife.getContentPane().add(quitPanel);
JPanel stonesPanel = new JPanel();
frmOceanlife.getContentPane().add(stonesPanel);
JButton insertBtn = new JButton("Insert");
insertBtn.addActionListener(e -> {
try {
ImageIcon icon = new ImageIcon(new URL(STONE));
JLabel stoneLbl = new JLabel(icon);
stonesPanel.add(stoneLbl);
frmOceanlife.revalidate();
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
});
JPanel insertPanel = new JPanel();
insertPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
insertPanel.add(insertBtn);
frmOceanlife.getContentPane().add(insertPanel);
JPanel oceanPanel = new JPanel();
oceanPanel.setBackground(Color.WHITE);
oceanPanel.setLayout(new FlowLayout());
oceanPanel.setPreferredSize(new Dimension(700,550));
try {
JLabel oceanLbl = new JLabel(new ImageIcon(new URL(OCEAN)));
oceanPanel.add(oceanLbl);
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
frmOceanlife.getContentPane().add(oceanPanel);
JLabel infoLabel = new JLabel("Welcome to Oceanlife - Your Ocean size is 600x450!");
JPanel infoPanel = new JPanel();
infoPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
infoPanel.add(infoLabel);
frmOceanlife.getContentPane().add(infoPanel);
frmOceanlife.pack();
frmOceanlife.setVisible(true);
}
public static void main(String[] args) {
//no change in main
}
}
And add some final touchups :
public class Mainframe {
private static final String STONE = "https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/32x32/Circle_Red.png",
OCEAN ="https://media-gadventures.global.ssl.fastly.net/media-server/dynamic/blogs/posts/robin-wu/2014/12/PB110075.jpg";
private ImageIcon oceanIcon;
public Mainframe() {
initialize();
}
private void initialize() {
JFrame frmOceanlife = new JFrame();
frmOceanlife.setTitle("OceanLife");
frmOceanlife.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmOceanlife.setLayout(new BoxLayout(frmOceanlife.getContentPane(), BoxLayout.PAGE_AXIS));
JButton quitBtn = new JButton("Quit");
quitBtn.addActionListener(e -> System.exit(0));
JPanel quitPanel = new JPanel();
quitPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
quitPanel.add(quitBtn);
frmOceanlife.getContentPane().add(quitPanel);
JPanel stonesPanel = new JPanel();
JLabel stoneLbl = new JLabel();
stonesPanel.add(stoneLbl);
frmOceanlife.getContentPane().add(stonesPanel);
JButton insertBtn = new JButton("Insert");
insertBtn.addActionListener(e -> {
try {
ImageIcon icon = new ImageIcon(new URL(STONE));
stoneLbl.setIcon(icon);
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
});
JPanel insertPanel = new JPanel();
insertPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
insertPanel.add(insertBtn);
frmOceanlife.getContentPane().add(insertPanel);
try {
oceanIcon = new ImageIcon(new URL(OCEAN));
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
JLabel oceanLbl = new JLabel();
oceanLbl.setIcon(oceanIcon);
JPanel oceanPanel = new JPanel(){
#Override
public Dimension getPreferredSize() {
return new Dimension(oceanIcon.getIconWidth()+100, oceanIcon.getIconHeight());
};
};
oceanPanel.add(oceanLbl);
oceanPanel.setBackground(Color.WHITE);
oceanPanel.setLayout(new GridBagLayout()); //center image in panel
frmOceanlife.getContentPane().add(oceanPanel);
JLabel infoLabel = new JLabel("Welcome to Oceanlife - Your Ocean size is "+oceanIcon+oceanIcon.getIconWidth()+
"x"+oceanIcon.getIconHeight()+"!");
JPanel infoPanel = new JPanel();
infoPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
infoPanel.add(infoLabel);
frmOceanlife.getContentPane().add(infoPanel);
frmOceanlife.pack();
frmOceanlife.setVisible(true);
}
public static void main(String[] args) {
//no change in main
}
}
I have a login and a register panel and a window to hold all the panels. What I am trying to do is to go to the login panel when the register button is pressed. But it does not work. The method that I use would work if the login panel is inside the window but when it is in its own class it doesn't. Can someone please let me know how to do this?
Here is my code for the Window
package userInterface;
import java.awt.*;
import java.awt.EventQueue;
import java.sql.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import company.CompanySys;
import javax.swing.*;
import java.awt.CardLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
public class FrontEnd {
/**
* Variables
*/
// System
CompanySys sys = CompanySys.getSystem();
private static FrontEnd front = new FrontEnd();
private JFrame frame;
private final JLayeredPane layeredPane = new JLayeredPane();
public final RegisterPanel registerPan = new RegisterPanel();
public final LoginPanel loginPan = new LoginPanel();
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
FrontEnd window = new FrontEnd();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
private FrontEnd() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
this.setFrame();
this.setLayout();
this.addPanels();
}
/**
* Setting up the main frame
*/
private void setFrame() {
frame = new JFrame();
frame.setBounds(100, 100, 900, 700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
layeredPane.setBounds(0, 0, 900, 700);
frame.getContentPane().add(layeredPane);
layeredPane.setLayout(new CardLayout(0, 0));
}
/**
* Setting Layout
*/
public void setLayout() {
// frame.getContentPane().add(layeredPane, "name_2578740971832500");
// layeredPane.setLayout(new CardLayout(0, 0));
}
public void SetSizeandLocation() {
this.registerPan.setBounds(10, 10, 900, 700);
layeredPane.setLayer(loginPan, 0);
this.loginPan.setBounds(10, 10, 900, 700);
}
/**
* Set visibility of the components
*/
private void setVisibility() {
// this.registerPan.setVisible(true);
// this.loginPan.setVisible(true);
}
/**
* Adding panels to the window
*/
private void addPanels() {
layeredPane.add(registerPan);
layeredPane.add(loginPan);
}
public static FrontEnd getFront() {
return front;
}
/**
* Switching Panels
* #param panel
*/
public void switchPanels(JPanel panel) {
layeredPane.removeAll();
layeredPane.add(panel);
layeredPane.repaint();
layeredPane.revalidate();
}
public LoginPanel getLoginPan() {
return this.loginPan;
}
}
Here is the code for Register Panel
package userInterface;
import company.*;
import javax.swing.*;
import java.awt.event.*;
public class RegisterPanel extends JPanel implements ActionListener{
/**
* Variables
*/
// System
CompanySys sys = CompanySys.getSystem();
FrontEnd front = FrontEnd.getFront();
// Input fields
private JTextField usernameTextField = new JTextField();
private JPasswordField passwordField1 = new JPasswordField();
private JPasswordField passwordField2 = new JPasswordField();
// Labels
private JLabel usernameLabel = new JLabel("Username");
private JLabel password1Label = new JLabel("Password");
private JLabel password2Label = new JLabel("Password");
// Buttons
private JButton registerButton = new JButton("REGISTER");
private JButton cancelButton = new JButton("CANCEL");
private JButton haveAccount = new JButton("Already have an account? Login");
private JButton clearButton = new JButton("CLEAR");
// Others
private JCheckBox showPasswordCheckBox = new JCheckBox("Show Password");
/**
* Create the panel.
*/
public RegisterPanel() {
setLayout(null);
this.addComponents();
this.setSizeandLocations();
this.addActionEvent();
}
/**
* Methods
*/
// Set size and location of the components
public void setSizeandLocations() {
// Labels
usernameLabel.setBounds(312, 106, 64, 14);
password1Label.setBounds(324, 175, 64, 14);
password2Label.setBounds(312, 237, 64, 14);
// Input Fields
usernameTextField.setBounds(493, 103, 96, 20);
passwordField1.setBounds(493, 173, 97, 17);
passwordField2.setBounds(494, 234, 96, 20);
passwordField1.setEchoChar('*');
passwordField2.setEchoChar('*');
//Buttons
registerButton.setBounds(337, 301, 89, 23);
cancelButton.setBounds(479, 301, 89, 23);
haveAccount.setBounds(366, 363, 196, 23);
clearButton.setBounds(606, 301, 89, 23);
// Others
showPasswordCheckBox.setBounds(493, 261, 141, 23);
}
// Add all components to the panel
public void addComponents() {
// Add Labels
add(usernameLabel);
add(password1Label);
add(password2Label);
// Add input fields
add(usernameTextField);
add(passwordField1);
add(passwordField2);
// Add Buttons
add(registerButton);
add(cancelButton);
add(haveAccount);
add(clearButton);
// Others
add(showPasswordCheckBox);
}
/**
* Adding Action listener
*/
public void addActionEvent() {
this.registerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
front.switchPanels(front.getLoginPan());
}
});
this.cancelButton.addActionListener(this);
this.haveAccount.addActionListener(this);
this.clearButton.addActionListener(this);
this.showPasswordCheckBox.addActionListener(this);
}
/**
* Main method of the panel
* #param args
*/
public static void main(String args[]) {
RegisterPanel frame = new RegisterPanel();
frame.setVisible(true);
frame.setBounds(10, 10, 900, 500);
}
/**
* Adding the functionality to the components
*/
#Override
public void actionPerformed(ActionEvent e) {
String usr = this.usernameTextField.getText();
String pass1 = String.valueOf(this.passwordField1.getPassword());
String pass2 = String.valueOf(this.passwordField2.getPassword());
// if (e.getSource() == this.registerButton) {
// if (sys.register(usr, pass1, pass2)) {
// // JOptionPane.showConfirmDialog(null, "Success", getName(), JOptionPane.DEFAULT_OPTION);
//
// front.switchPanels(front.getLoginPan());
// }
// else {
// JOptionPane.showConfirmDialog(null, "fail", getName(), JOptionPane.DEFAULT_OPTION);
// }
// }
if (e.getSource() == this.cancelButton) {
}
else if (e.getSource() == this.haveAccount) {
}
else if (e.getSource() == this.showPasswordCheckBox) {
if(this.showPasswordCheckBox.isSelected()) {
this.passwordField1.setEchoChar((char) 0);
this.passwordField2.setEchoChar((char) 0);
}
else {
this.passwordField1.setEchoChar('*');
this.passwordField2.setEchoChar('*');
}
}
else if (e.getSource() == this.clearButton) {
this.passwordField1.setText("");
this.passwordField2.setText("");
this.usernameTextField.setText("");
}
}
}
Here is code for login panel
package userInterface;
import company.CompanySys;
import javax.swing.*;
import java.awt.event.*;
public class LoginPanel extends JPanel implements ActionListener{
/**
* Variables
*/
// System
CompanySys sys = CompanySys.getSystem();
// Fields
private JTextField userNameTextField = new JTextField();;
private JPasswordField passwordField = new JPasswordField();;
// Labels
JLabel userNameLabel = new JLabel("Username");
JLabel passwordLabel = new JLabel("Password");
// Buttons
JButton cancelButton = new JButton("CANCEL");
JButton loginButton = new JButton("LOGIN");
JButton noAccountButton = new JButton("Don't have an acount? register");
JButton clearButton = new JButton("CLEAR");
// Others
JCheckBox showPassCheckBox = new JCheckBox("Show Password");
/**
* Constructor
*/
public LoginPanel() {
setLayout(null);
this.setSizeAndLocation();
this.addComponent();
this.addAction();
}
/**
* Setting size and location of the components
*/
public void setSizeAndLocation() {
// Labels
userNameLabel.setBounds(97, 52, 69, 14);
passwordLabel.setBounds(97, 88, 48, 14);
// TextFields
passwordField.setBounds(197, 85, 103, 20);
userNameTextField.setBounds(197, 49, 96, 20);
// Buttons
clearButton.setBounds(325, 146, 89, 23);
noAccountButton.setBounds(85, 196, 208, 23);
cancelButton.setBounds(209, 146, 89, 23);
loginButton.setBounds(85, 146, 89, 23);
// Others
showPassCheckBox.setBounds(197, 116, 130, 23);
}
/**
* Adding components to the Panel
*/
public void addComponent() {
// Labels
this.add(userNameLabel);
this.add(passwordLabel);
// TextFields
this.add(userNameTextField);
this.add(passwordField);
// Buttons
this.add(loginButton);
this.add(cancelButton);
this.add(noAccountButton);
this.add(clearButton);
// Others
this.add(showPassCheckBox);
}
/**
* Adding ActionListener to the interactive components
*/
public void addAction() {
// Buttons
this.clearButton.addActionListener(this);
this.cancelButton.addActionListener(this);
this.loginButton.addActionListener(this);
this.noAccountButton.addActionListener(this);
// Others
this.showPassCheckBox.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
}
public static void main(String args[]) {
LoginPanel frame = new LoginPanel();
frame.setVisible(true);
frame.setBounds(10, 10, 900, 700);
}
}
I have tried other ways too but it doesnt work!
being new to programming, i'm having a slight issue resizing the text fields I've added to the JPanel. While I could go the route of creating individual panels with their own text field, I though it would be better to add all the components into one panel. Part of my overall idea is to have my add button reference the panel, containing the text fields, to add more text fields on the tracker for users to fill out, and while I can get the fields to display when I implement the setBounds method on my panel object, i'm having tough time figuring out how resize them in the panel itself. And if you have any other advice on my overall structure, I welcome it.
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class UI {
JFrame frame;
JLabel Title,Name, CheckOut, CheckIn, Email;
JTextField NameField,CheckOutField, CheckInField, EmailField;
JButton Add, Delete;
JPanel buttons, textfields, primary;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UI window = new UI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public UI(){
design();
}
private void design(){
frame = new JFrame("Form 48 Tracker");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(100, 100, 750, 400);
frame.getContentPane().setLayout(null);
Title = new JLabel();
Title.setText("Form 48 Tracker");
Title.setFont(new Font("Calibri", Font.PLAIN, 28));
Title.setBounds(233, 11, 200, 75);
frame.getContentPane().add(Title);
Title.setForeground(Color.BLACK);
Name = new JLabel();
Name.setText("Name");
Name.setFont(new Font("Calibri", Font.PLAIN, 15));
Name.setBounds(50, 80, 128, 20);
frame.getContentPane().add(Name);
Name.setForeground(Color.BLACK);
CheckOut = new JLabel();
CheckOut.setText("Check Out Date");
CheckOut.setFont(new Font("Calibri", Font.PLAIN, 15));
CheckOut.setBounds(200, 80, 128, 20);
frame.getContentPane().add(CheckOut);
CheckOut.setForeground(Color.BLACK);
CheckIn = new JLabel();
CheckIn.setText("Check In Date");
CheckIn.setFont(new Font("Calibri", Font.PLAIN, 15));
CheckIn.setBounds(350, 80, 128, 20);
frame.getContentPane().add(CheckIn);
CheckIn.setForeground(Color.BLACK);
Email = new JLabel();
Email.setText("Email");
Email.setFont(new Font("Calibri", Font.PLAIN, 15));
Email.setBounds(500, 80, 128, 20);
frame.getContentPane().add(Email);
Email.setForeground(Color.BLACK);
Add = new JButton("Add");
buttons = new JPanel();
buttons.add(Add);
buttons.setBounds(200, 270, 157, 50); //x , y , width , height//
frame.getContentPane().add(buttons);
Add.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
}
});
Delete = new JButton("Delete");
buttons = new JPanel();
buttons.add(Delete);
buttons.setBounds(605, 101, 128, 50);
frame.getContentPane().add(buttons);
primary = new JPanel();
NameField = new JTextField();
CheckOutField = new JTextField();
CheckInField = new JTextField();
EmailField = new JTextField();
primary.add(NameField);
primary.add(CheckOutField);
primary.add(CheckInField);
primary.add(EmailField);
primary.setBounds(50, 110, 128, 20);
frame.getContentPane().add(primary);
}
}
Let's concentrate on the code that's causing the problem, and only that code. I've created a minimal example program, one that has enough code to compile and run, and that demonstrates the problem, but that has no unnecessary code:
import javax.swing.*;
public class UiFoo {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Foo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null); // **** no!! ****
JPanel primary = new JPanel();
JTextField NameField = new JTextField();
JTextField CheckOutField = new JTextField();
JTextField CheckInField = new JTextField();
JTextField EmailField = new JTextField();
primary.add(NameField);
primary.add(CheckOutField);
primary.add(CheckInField);
primary.add(EmailField);
primary.setBounds(50, 110, 128, 20);
frame.getContentPane().add(primary);
frame.setSize(600, 250);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
So, if you run this code, you'll see 4 very small JTextFields. Why are they so small? Because you've not set the columns property for the JTextFields, and so they default to columns size 0 and show up like so:
So it's better if you can give the JTextField a columns property so that they have some width, e.g., make this change:
JPanel primary = new JPanel();
int columns = 8;
JTextField NameField = new JTextField(columns);
JTextField CheckOutField = new JTextField(columns);
JTextField CheckInField = new JTextField(columns);
JTextField EmailField = new JTextField();
But this just shows one JTextField, and cuts off the bottom as well:
Why? Because you're artificially constraining the size of the containing JPanel, primary via:
primary.setBounds(50, 110, 128, 20);
This containing JPanel is only 128 pixels wide by 20 pixels high, meaning that it won't even display one JTextField well.
One solution is to use a mix of layout managers and JPanels as well as a JScrollPane to allow for a grid of JPanels to be added, something like so (try it out!):
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.*;
#SuppressWarnings("serial")
public class UiFoo2 extends JPanel {
JPanel singleColumnPanel = new JPanel(new GridLayout(0, 1, 2, 2));
public UiFoo2() {
JButton addButton = new JButton("Add");
addButton.addActionListener(e -> {
JPanel rowPanel = new JPanel(new GridLayout(1, 4, 2, 2));
for (int i = 0; i < 4; i++) {
rowPanel.add(new JTextField(8));
}
singleColumnPanel.add(rowPanel);
singleColumnPanel.revalidate();
singleColumnPanel.repaint();
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(addButton);
JPanel labelPanel = new JPanel(new GridLayout(1, 4, 2, 2));
labelPanel.add(new JLabel("Name", SwingConstants.CENTER));
labelPanel.add(new JLabel("Check Out Date", SwingConstants.CENTER));
labelPanel.add(new JLabel("Check In Date", SwingConstants.CENTER));
labelPanel.add(new JLabel("Email", SwingConstants.CENTER));
singleColumnPanel.add(labelPanel);
JPanel containerPanel = new JPanel(new BorderLayout(5, 5));
containerPanel.add(singleColumnPanel, BorderLayout.PAGE_START);
JScrollPane scrollPane = new JScrollPane(containerPanel);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setPreferredSize(new Dimension(650, 400));
setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.PAGE_END);
}
private static void createAndShowGui() {
UiFoo2 mainPanel = new UiFoo2();
JFrame frame = new JFrame("UiFoo2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
This will create a row JPanel that holds four JTextFields that get added to the JScrollPane when the add JButton is pressed, and looks like so:
but we still can do better. Why not instead create a class to hold a row of data, something like so:
import java.util.Date;
public class Form48Customer {
private String name;
private Date checkIn;
private Date checkOut;
private String Email;
public Form48Customer(String name, Date checkIn, Date checkOut, String email) {
this.name = name;
this.checkIn = checkIn;
this.checkOut = checkOut;
Email = email;
}
public Date getCheckIn() {
return checkIn;
}
public void setCheckIn(Date checkIn) {
this.checkIn = checkIn;
}
public Date getCheckOut() {
return checkOut;
}
public void setCheckOut(Date checkOut) {
this.checkOut = checkOut;
}
public String getName() {
return name;
}
public String getEmail() {
return Email;
}
// should override hashCode and equals here
}
and then create a JTable complete with custom model to display objects of this type, and then display them in the GUI. This is much cleaner, more flexible, and extendable. Something like so:
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.*;
import java.util.Date;
import javax.swing.*;
import javax.swing.JFormattedTextField.AbstractFormatter;
import javax.swing.table.*;
#SuppressWarnings("serial")
public class Form48TrackerPanel extends JPanel {
public static final String TITLE = "Form 48 Tracker";
private static final String DATE_FORMAT_TXT = "MM/dd/yyyy";
private Form48TableModel model = new Form48TableModel();
private JTable table = new JTable(model);
private JButton addButton = new JButton("Add");
private JButton deleteButton = new JButton("Delete");
private JButton exitButton = new JButton("Exit");
public Form48TrackerPanel() {
final SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_TXT);
TableCellRenderer dateRenderer = new DefaultTableCellRenderer() {
#Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if( value instanceof Date) {
value = dateFormat.format(value);
}
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
}
};
table.getColumnModel().getColumn(1).setCellRenderer(dateRenderer);
table.getColumnModel().getColumn(2).setCellRenderer(dateRenderer);
JLabel titleLabel = new JLabel(TITLE, SwingConstants.CENTER);
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 28f));
addButton.addActionListener(new AddListener());
addButton.setMnemonic(KeyEvent.VK_A);
deleteButton.addActionListener(new DeleteListener());
deleteButton.setMnemonic(KeyEvent.VK_D);
exitButton.addActionListener(new ExitListener());
exitButton.setMnemonic(KeyEvent.VK_X);
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 0));
buttonPanel.add(addButton);
buttonPanel.add(deleteButton);
buttonPanel.add(exitButton);
setPreferredSize(new Dimension(800, 500));
int ebGap = 8;
setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
setLayout(new BorderLayout(ebGap, ebGap));
add(titleLabel, BorderLayout.PAGE_START);
add(new JScrollPane(table), BorderLayout.CENTER);
add(buttonPanel, BorderLayout.PAGE_END);
model.addRow(new Form48Customer("John Smith", new Date(), new Date(), "JSmith#Yahoo.com"));
model.addRow(new Form48Customer("Fred Flinstone", new Date(), new Date(), "FFlinstone#GMail.com"));
}
private class AddListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
AddForm48Panel addFormPanel = new AddForm48Panel();
int result = JOptionPane.showConfirmDialog(Form48TrackerPanel.this,
addFormPanel, "Add Customer", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
Form48Customer customer = addFormPanel.getForm48Customer();
model.addRow(customer);
}
}
}
private class DeleteListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// TODO *** finish this code ***
}
}
private class ExitListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
Window win = SwingUtilities.getWindowAncestor(Form48TrackerPanel.this);
win.dispose();
}
}
private static void createAndShowGui() {
Form48TrackerPanel mainPanel = new Form48TrackerPanel();
JFrame frame = new JFrame(TITLE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
#SuppressWarnings("serial")
class AddForm48Panel extends JPanel {
private static final int TFIELD_COLS = 10;
private static final String DATE_FORMAT_TXT = "MM/dd/yyyy";
private static final Format DATE_FORMAT = new SimpleDateFormat(DATE_FORMAT_TXT);
private static final Insets INSETS = new Insets(5, 5, 5, 5);
private JTextField nameField = new JTextField(TFIELD_COLS);
private JFormattedTextField checkOutDateField = new JFormattedTextField(DATE_FORMAT);
private JFormattedTextField checkInDateField = new JFormattedTextField(DATE_FORMAT);
private JTextField emailField = new JTextField(TFIELD_COLS);
private JComponent[] fields = {nameField, checkOutDateField, checkInDateField, emailField};
private String[] labels = {"Name", "Check Out Date", "Check In Date", "Email"};
public AddForm48Panel() {
InputVerifier verifier = new DateFieldVerifier();
checkInDateField.setInputVerifier(verifier);
checkOutDateField.setInputVerifier(verifier);
setLayout(new GridBagLayout());
for (int i = 0; i < fields.length; i++) {
add(new JLabel(labels[i] + ":"), createGbc(0, i));
add(fields[i], createGbc(1, i));
}
}
public String getName() {
return nameField.getText();
}
public String getEmail() {
return emailField.getText();
}
public Date getCheckOut() {
return (Date) checkOutDateField.getValue();
}
public Date getCheckIn() {
return (Date) checkInDateField.getValue();
}
public Form48Customer getForm48Customer() {
String name = getName();
Date checkOut = getCheckOut();
Date checkIn = getCheckIn();
String email = getEmail();
return new Form48Customer(name, checkIn, checkOut, email);
}
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = INSETS;
gbc.anchor = x == 0 ? GridBagConstraints.WEST :GridBagConstraints.EAST;
gbc.fill = GridBagConstraints.HORIZONTAL;
return gbc;
}
private class DateFieldVerifier extends InputVerifier {
#Override
public boolean verify(JComponent input) {
if (input instanceof JFormattedTextField) {
JFormattedTextField ftf = (JFormattedTextField)input;
AbstractFormatter formatter = ftf.getFormatter();
if (formatter != null) {
String text = ftf.getText();
try {
formatter.stringToValue(text);
return true;
} catch (ParseException pe) {
return false;
}
}
}
return true;
}
#Override
public boolean shouldYieldFocus(JComponent input) {
boolean verify = verify(input);
if (!verify) {
String message = "Enter a valid date, e.g.: 01/05/2017";
String title = "Invalid Date Format";
int type = JOptionPane.ERROR_MESSAGE;
JOptionPane.showMessageDialog(input, message, title, type);
}
return verify;
}
}
}
#SuppressWarnings("serial")
class Form48TableModel extends DefaultTableModel {
private static final String[] COL_NAMES = {"Name", "Check Out Date", "Check In Date", "Email"};
public Form48TableModel() {
super(COL_NAMES, 0);
}
public void addRow(Form48Customer customer) {
Object[] rowData = {
customer.getName(),
customer.getCheckOut(),
customer.getCheckIn(),
customer.getEmail()
};
addRow(rowData);
}
public Form48Customer getRow(int row) {
String name = (String) getValueAt(row, 0);
Date checkIn = (Date) getValueAt(row, 1);
Date checkOut = (Date) getValueAt(row, 2);
String email = (String) getValueAt(row, 3);
return new Form48Customer(name, checkIn, checkOut, email);
}
#Override
public Class<?> getColumnClass(int columnIndex) {
switch (columnIndex) {
case 1:
return Date.class;
case 2:
return Date.class;
default:
break;
}
return super.getColumnClass(columnIndex);
}
}
Which would look like:
I am making a program which will open a class GUI called "Menu" when correct login info is put into a text field password field and a button called "login" is pressed. The problem is that the Menu window will open blank, not displaying what I have programmed into the Menu.
This is my code for Login class,
package ems;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.SystemColor;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Login extends JFrame implements ActionListener{
private JFrame loginFrame;
private JTextField usernameField;
private JPasswordField passwordField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login window = new Login();
window.loginFrame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Login() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
loginFrame = new JFrame();
loginFrame.setTitle("Login");
loginFrame.setBounds(100, 100, 450, 300);
loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
loginFrame.getContentPane().setLayout(null);
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(112, 116, 74, 16);
loginFrame.getContentPane().add(lblUsername);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(112, 165, 74, 16);
loginFrame.getContentPane().add(lblPassword);
usernameField = new JTextField();
usernameField.setBounds(198, 110, 134, 28);
loginFrame.getContentPane().add(usernameField);
usernameField.setColumns(10);
passwordField = new JPasswordField();
passwordField.setBounds(198, 159, 134, 28);
loginFrame.getContentPane().add(passwordField);
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String uname = usernameField.getText();
String pword = passwordField.getText();
if (uname.equals("test") && pword.equals("test")){
JOptionPane.showMessageDialog(loginFrame, "Login successful.");
loginFrame.setVisible(false);
Menu menu = new Menu ();
menu.setVisible (true);
}else{
JOptionPane.showMessageDialog(loginFrame, "Login unsuccessful.");
}
}
});
btnLogin.setBounds(238, 210, 90, 30);
loginFrame.getContentPane().add(btnLogin);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnExit.setBounds(108, 210, 90, 30);
loginFrame.getContentPane().add(btnExit);
JPanel panel = new JPanel();
panel.setBackground(new Color(192, 192, 192));
panel.setBounds(91, 86, 258, 163);
loginFrame.getContentPane().add(panel);
JLabel lblLoginToThe = new JLabel("LOGIN TO THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
lblLoginToThe.setBounds(26, 23, 418, 16);
loginFrame.getContentPane().add(lblLoginToThe);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
panel_1.setBounds(0, 0, 450, 63);
loginFrame.getContentPane().add(panel_1);
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
This is the code for the Menu class,
package ems;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import ems.Login;
public class Menu extends Login implements ActionListener{
private JFrame menuFrame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu window = new Menu();
window.menuFrame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Menu() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
menuFrame = new JFrame();
menuFrame.setTitle("Menu");
menuFrame.setBounds(100, 100, 450, 300);
menuFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menuFrame.getContentPane().setLayout(null);
JLabel lblLoginToThe = new JLabel("THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
lblLoginToThe.setBounds(64, 22, 331, 16);
menuFrame.getContentPane().add(lblLoginToThe);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
panel_1.setBounds(0, 0, 450, 63);
menuFrame.getContentPane().add(panel_1);
JButton btnLogout = new JButton("Logout");
btnLogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
menuFrame.setVisible(false);
Login login = new Login ();
login.setVisible(true);
}
});
btnLogout.setBounds(307, 222, 117, 29);
menuFrame.getContentPane().add(btnLogout);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnExit.setBounds(10, 222, 117, 29);
menuFrame.getContentPane().add(btnExit);
}
}
Both of these classes are under a package called ems.
I am very new to programming and help would be greatly appreciated.
Thank you
You are creating another JFrame inside of Login and Menu, which is wrong, theres also no need that Menu extends Login
Here is the fixed version for Login:
package ems;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Login extends JFrame {
private static final long serialVersionUID = 1L;
private JTextField usernameField;
private JPasswordField passwordField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login window = new Login();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Login() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
this.setTitle("Login");
this.setBounds(100, 100, 450, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout(null);
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(112, 116, 74, 16);
this.getContentPane().add(lblUsername);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(112, 165, 74, 16);
this.getContentPane().add(lblPassword);
usernameField = new JTextField();
usernameField.setBounds(198, 110, 134, 28);
this.getContentPane().add(usernameField);
usernameField.setColumns(10);
passwordField = new JPasswordField();
passwordField.setBounds(198, 159, 134, 28);
this.getContentPane().add(passwordField);
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String uname = usernameField.getText();
String pword = passwordField.getText();
if (uname.equals("test") && pword.equals("test")){
JOptionPane.showMessageDialog(Login.this, "Login successful.");
Login.this.setVisible(false);
Menu menu = new Menu ();
menu.setVisible (true);
}else{
JOptionPane.showMessageDialog(Login.this, "Login unsuccessful.");
}
}
});
btnLogin.setBounds(238, 210, 90, 30);
this.getContentPane().add(btnLogin);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnExit.setBounds(108, 210, 90, 30);
this.getContentPane().add(btnExit);
JPanel panel = new JPanel();
panel.setBackground(new Color(192, 192, 192));
panel.setBounds(91, 86, 258, 163);
this.getContentPane().add(panel);
JLabel lblLoginToThe = new JLabel("LOGIN TO THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
lblLoginToThe.setBounds(26, 23, 418, 16);
this.getContentPane().add(lblLoginToThe);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
panel_1.setBounds(0, 0, 450, 63);
this.getContentPane().add(panel_1);
}
}
And for Menu
package ems;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Menu extends JFrame{
private static final long serialVersionUID = 1L;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu window = new Menu();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Menu() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
this.setTitle("Menu");
this.setBounds(100, 100, 450, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout(null);
JLabel lblLoginToThe = new JLabel("THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
lblLoginToThe.setBounds(64, 22, 331, 16);
this.getContentPane().add(lblLoginToThe);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
panel_1.setBounds(0, 0, 450, 63);
this.getContentPane().add(panel_1);
JButton btnLogout = new JButton("Logout");
btnLogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Menu.this.setVisible(false);
Login login = new Login ();
login.setVisible(true);
}
});
btnLogout.setBounds(307, 222, 117, 29);
this.getContentPane().add(btnLogout);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnExit.setBounds(10, 222, 117, 29);
this.getContentPane().add(btnExit);
}
}
Still looking, but:
menuFrame.getContentPane().add(lblLoginToThe);
The content pane isn't a container, you can't add multiple things to it. You need to put everything in a panel (note panel != pane) and then add one panel to the content pane.
Also don't call setBounds() directly, use a layout manager. That's another reason you could be seeing nothing: all your components are drawn outside of the window or some other similar error. Layout managers will fix that.
EDIT: And as Edwardth said you have a habit of declaring your classes to be a thing (like JFrame) and then creating a second JFrame inside the initialize method. Don't do that.
public class Login extends JFrame implements ActionListener{
...
private void initialize() {
loginFrame = new JFrame(); // BAD!
The JFrame was already made when you declared that Login extends JFrame you don't need a second frame.
Edwardth got the answer before me so go ahead and study his example and then mark his answer correct. Ask in the comments below if you have further questions.
Here's my example of the Login class, without the setBounds().
class Login extends JFrame implements ActionListener{
private JTextField usernameField;
private JPasswordField passwordField;
/**
* Create the application.
*/
public Login() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
setTitle("Login");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lblUsername = new JLabel("Username");
JLabel lblPassword = new JLabel("Password");
usernameField = new JTextField();
usernameField.setColumns(10);
passwordField = new JPasswordField();
JPanel loginPanel = new JPanel( new GridLayout( 0,2 ) );
loginPanel.add( lblUsername );
loginPanel.add( usernameField );
loginPanel.add( lblPassword );
loginPanel.add( passwordField );
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String uname = usernameField.getText();
String pword = passwordField.getText();
if (uname.equals("test") && pword.equals("test")){
JOptionPane.showMessageDialog( Login.this, "Login successful.");
setVisible(false);
Menu menu = new Menu ();
menu.setVisible (true);
}else{
JOptionPane.showMessageDialog( Login.this, "Login unsuccessful.");
}
}
});
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
JPanel panel = new JPanel();
panel.setBackground(new Color(192, 192, 192));
panel.add( btnLogin );
panel.add( btnExit );
JLabel lblLoginToThe = new JLabel("LOGIN TO THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
panel_1.add( lblLoginToThe );
Box topBox = Box.createVerticalBox();
topBox.add( panel_1 );
topBox.add( loginPanel );
topBox.add( panel );
add( topBox );
pack();
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
And the Main class:
class Menu extends JFrame {
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu window = new Menu();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Menu() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
setTitle("Menu");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Box topBox = Box.createVerticalBox();
JLabel lblLoginToThe = new JLabel("THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
topBox.add( lblLoginToThe ); // **********
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
topBox.add( panel_1 ); // *************
JButton btnLogout = new JButton("Logout");
btnLogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Menu.this.setVisible(false);
Login login = new Login ();
login.setVisible(true);
}
});
topBox.add( btnLogout ); //****************
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
topBox.add( btnExit );
add( topBox );
pack();
}
}
I have tried to create this progress bar:
public class ProgressBar extends JFrame{
private JButton fine = new JButton("Chiudi");
final JProgressBar jp;
JPanel body;
JLabel banner1;
JLabel banner2;
JPanel testo;
JTextArea areatesto;
JPanel provapannello;
JTextArea provatesto;
JPanel pannellofine;
public ProgressBar() {
super("loading");
setSize(440, 400);
setResizable(true);
Container content = getContentPane();
content.setBackground(Color.YELLOW);
body = new JPanel();
body.setLayout(new FlowLayout());
ImageIcon image1 = new ImageIcon("prova1.png");
banner1 = new JLabel();
banner2 = new JLabel();
banner1.setIcon(image1);
JTextArea prova = new JTextArea("bar", 2, 40);
prova.setBackground(Color.LIGHT_GRAY);
prova.setLineWrap(true);
body.add(banner1);
body.add(prova);
body.add(banner2);
banner.setBounds(30, 80, 120, 120);
testo = new JPanel();
areatesto = new JTextArea("Attendi Per Favore, Sto Preparando Il Tuo PDF", 2, 33);
areatesto.setLineWrap(true);
testo.add(areatesto);
ImagePanel progress_background = new ImagePanel("p.jpg");
UIManager.put("ProgressBar.background", new Color(29, 29, 29));
UIManager.put("ProgressBar.foreground", new Color(16, 95, 173));
UIManager.put("ProgressBar.selectionBackground", new Color(214, 214, 214));
UIManager.put("ProgressBar.selectionForeground", new Color(29, 29, 29));
jp = new JProgressBar();
jp.setUI(new BasicProgressBarUI());
jp.setBounds(0, 205, 434, 25);
jp.setMinimum(0);
jp.setMaximum(100);
jp.setStringPainted(true);
jp.setBorder(null);
progress_background.add(jp);
provapannello = new JPanel();
provatesto = new JTextArea("prova", 2, 70);
provatesto.setBackground(Color.LIGHT_GRAY);
provapannello.setBounds(0, 226, 500, 100);
provapannello.add(provatesto);
content.add(provapannello);
content.add(progress_background);
pannellofine = new JPanel();
pannellofine.add(fine);
pannellofine.setBounds(340, 330, 100, 100);
pannellofine.setVisible(false);
content.add(pannellofine);
content.add(testo);
content.add(body);
Thread runner;
jp.setValue(0);
setVisible(true);
public void setValue(final int j) {
Runnable target = new Runnable() {
#Override
public void run() {
jp.setValue(j);
}
};
SwingUtilities.invokeLater(target);
}
public static void main(String Args[]) {
ProgressBar p = new ProgressBar();
int i = 0;
while(true){
System.out.println("work");
try {
Thread.sleep(500);
} catch (InterruptedException ex) { }
p.setValue(i++);
}
}
I have tried to change the value of the ProgressBar with the method "setValue" but the bar does not increase, "while" cycles to infinity, but I see no change. what's wrong?
I've stripped out most of the unnecessary code (and fixed your compilation errors), and your example works (I've changed the delay and increment, because again, for reproduction purposes you shouldn't waste people's time)
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
public class ProgressBar extends JFrame {
private JProgressBar progressBar;
public ProgressBar() {
super("loading");
setSize(200, 100);
Container content = getContentPane();
content.setLayout(new BorderLayout());
progressBar = new JProgressBar();
progressBar.setMinimum(0);
progressBar.setMaximum(100);
progressBar.setStringPainted(true);
progressBar.setBorder(null);
content.add(progressBar, BorderLayout.SOUTH);
setVisible(true);
}
void updateProgress(final int newValue) {
progressBar.setValue(newValue);
}
public void setValue(final int j) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
updateProgress(j);
}
});
}
public static void main(final String Args[]) {
ProgressBar myProgressBar = new ProgressBar();
int i = 0;
while (i <= 100) {
System.out.println("" + i + "%");
myProgressBar.setValue(i);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
i = i + 5;
}
}
}
You should really have invested the time in creating an SSCCE
Also on a side note, you should follow this advice when handling InterruptedExcetions