Java JFrame remove and repaint components not working - java

So I started to go into OOP and also started to learn about swing library but I have trouble. When I try to remove all of the JFrame components it doesnt work. What I want to do is when the user clicks a button I have to remove all the JFrame components and add new ones but it doesn't work despite that I used removeAll() repait(), revalidate() etc. Here is my code for the BankApp class:
import javax.swing.*;
public class BankApp{
public static void main(String[] args) {
BankGUI object1;
object1 = new BankGUI();
object1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
object1.setSize(700, 500);
object1.setLocationRelativeTo(null);
object1.setResizable(false);
object1.setVisible(true);
}
}
Here is the BankGUI:
import javax.swing.*;
import java.awt.*;
public class BankGUI extends JFrame{
private JButton CreateAccount;
private JButton LoginAccount;
private JButton Exit;
private JButton AboutButton;
private JButton ExitButton;
private JLabel IntroText;
public BankGUI(){
super("Banking App");
createMainMenu();
}
public void createMainMenu(){
add(Box.createRigidArea(new Dimension(0,40)));
IntroText = new JLabel("Banking Application");
IntroText.setMaximumSize(new Dimension(280,60));
IntroText.setFont(new Font("Serif", Font.PLAIN, 34));
IntroText.setAlignmentX(CENTER_ALIGNMENT);
add(IntroText);
add(Box.createRigidArea(new Dimension(0,40)));
setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS));
CreateAccount = new JButton("Register");
CreateAccount.setMaximumSize(new Dimension(200,50));
CreateAccount.setFont(new Font("Serif", Font.PLAIN, 24));
CreateAccount.setAlignmentX(CENTER_ALIGNMENT);
CreateAccount.setFocusable(false);
add(CreateAccount);
add(Box.createRigidArea(new Dimension(0,20)));
LoginAccount = new JButton("Login");
LoginAccount.setMaximumSize(new Dimension(200,50));
LoginAccount.setFont(new Font("Serif", Font.PLAIN, 24));
LoginAccount.setAlignmentX(CENTER_ALIGNMENT);
LoginAccount.setFocusable(false);
add(LoginAccount);
add(Box.createRigidArea(new Dimension(0,20)));
AboutButton = new JButton("About");
AboutButton.setMaximumSize(new Dimension(200,50));
AboutButton.setFont(new Font("Serif", Font.PLAIN, 24));
AboutButton.setAlignmentX(CENTER_ALIGNMENT);
AboutButton.setFocusable(false);
add(AboutButton);
add(Box.createRigidArea(new Dimension(0,20)));
ExitButton = new JButton("Exit");
ExitButton.setMaximumSize(new Dimension(200,50));
ExitButton.setFont(new Font("Serif", Font.PLAIN, 24));
ExitButton.setAlignmentX(CENTER_ALIGNMENT);
ExitButton.setFocusable(false);
add(ExitButton);
ButtonListener actionListener = new ButtonListener(CreateAccount, LoginAccount, AboutButton, ExitButton);
CreateAccount.addActionListener(actionListener);
LoginAccount.addActionListener(actionListener);
AboutButton.addActionListener(actionListener);
ExitButton.addActionListener(actionListener);
}
}
And here is my ButtonListener Class:
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ButtonListener implements ActionListener{
private JButton CreateAccount;
private JButton LoginAccount;
private JButton AboutButton;
private JButton ExitButton;
public ButtonListener(JButton button1,JButton button2,JButton button3,JButton button4){
CreateAccount = button1;
LoginAccount = button2;
AboutButton = button3;
ExitButton = button4;
}
#Override
public void actionPerformed(ActionEvent e) {
BankGUI bankgui = new BankGUI();
if(e.getSource() == CreateAccount){
System.out.println("This prints out");
}else if(e.getSource() == ExitButton){
bankgui.getContentPane().removeAll();
bankgui.removeAll();
bankgui.validate();
bankgui.repaint();
System.out.println("Code reaches here but it doesnt clear the screen");
}
}
}
When I try to do it nothing happens despite that I revalidate and repaint I'm not sure why.I just want to clear the JFrame. I'm 100% sure that the code reaches the methods but for some reason they don't work.
Maybe its obvious mistake but I'm not seeing it.
Any help would be appreciated.

In your actionPerformed method, you are creating another instance of BankGUI, this is, in no way, connected to the instance which is been displayed to the user...
#Override
public void actionPerformed(ActionEvent e) {
BankGUI bankgui = new BankGUI();
//...
}
There are a few ways you "might" correct this, most of them aren't pretty.
You could pass a reference of BankGUI to the ButtonListener along with the buttons. I don't like this idea, as it provides the means for ButtonListener to start doing things to BankGUI it really has no responsibility for doing.
You could use SwingUtilities.getWindowAncestor, passing a reference of the button which was triggered, to get a reference to the window. This has the sam problem as the previous idea, but it also makes assumptions about the structure of the UI, which, ButtonListener shouldn't care about.
In both cases, this couples ButtonListener to BankGUI.
A better solution would be to provide some kind of "navigation manager". The ButtonListener would take a reference of it and when one of the buttons is actioned, would notify the "navigation manager", asking it to perform the actual task.
This de-couples the ButtonListener from the implementation of the UI.
This is all about concepts of "isolation of responsibility", "code reusability" and "model-view-controller"
Overall, a simpler and more practical solution would be to use a CardLayout, which will further de-couple the UI and make it easier to isolate functionality to their own classes/components and allow the primary UI to switch between them
import java.awt.CardLayout;
import static java.awt.Component.CENTER_ALIGNMENT;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class JavaApplication101 {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
BankGUI object1;
object1 = new BankGUI();
object1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
object1.pack();
object1.setLocationRelativeTo(null);
object1.setVisible(true);
}
});
}
public interface BankNavigationController {
public void setView(String command);
}
public static class CardLayoutBankNavigationController implements BankNavigationController {
private Container parent;
private CardLayout layout;
public CardLayoutBankNavigationController(Container parent, CardLayout layout) {
this.parent = parent;
this.layout = layout;
}
#Override
public void setView(String command) {
layout.show(parent, command);
}
}
public static class BankGUI extends JFrame {
private CardLayoutBankNavigationController controller;
public BankGUI() {
super("Banking App");
CardLayout layout = new CardLayout();
setLayout(layout);
controller = new CardLayoutBankNavigationController(getContentPane(), layout);
add("Main Menu", createMainMenu());
add("Register", otherView("Register"));
add("Login", otherView("Login"));
add("About", otherView("About"));
add("Exit", otherView("Exit"));
controller.setView("Main Menu");
}
public JPanel otherView(String named) {
JPanel view = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
view.add(new JLabel(named), gbc);
JButton mainMenu = new JButton("Main Menu");
view.add(mainMenu, gbc);
ButtonListener actionListener = new ButtonListener(controller);
mainMenu.addActionListener(actionListener);
return view;
}
public JPanel createMainMenu() {
JPanel menu = new JPanel();
menu.setLayout(new BoxLayout(menu, BoxLayout.PAGE_AXIS));
menu.add(Box.createRigidArea(new Dimension(0, 40)));
JLabel IntroText = new JLabel("Banking Application");
IntroText.setMaximumSize(new Dimension(280, 60));
IntroText.setFont(new Font("Serif", Font.PLAIN, 34));
IntroText.setAlignmentX(CENTER_ALIGNMENT);
menu.add(IntroText);
menu.add(Box.createRigidArea(new Dimension(0, 40)));
JButton CreateAccount = new JButton("Register");
CreateAccount.setMaximumSize(new Dimension(200, 50));
CreateAccount.setFont(new Font("Serif", Font.PLAIN, 24));
CreateAccount.setAlignmentX(CENTER_ALIGNMENT);
CreateAccount.setFocusable(false);
menu.add(CreateAccount);
menu.add(Box.createRigidArea(new Dimension(0, 20)));
JButton LoginAccount = new JButton("Login");
LoginAccount.setMaximumSize(new Dimension(200, 50));
LoginAccount.setFont(new Font("Serif", Font.PLAIN, 24));
LoginAccount.setAlignmentX(CENTER_ALIGNMENT);
LoginAccount.setFocusable(false);
menu.add(LoginAccount);
menu.add(Box.createRigidArea(new Dimension(0, 20)));
JButton AboutButton = new JButton("About");
AboutButton.setMaximumSize(new Dimension(200, 50));
AboutButton.setFont(new Font("Serif", Font.PLAIN, 24));
AboutButton.setAlignmentX(CENTER_ALIGNMENT);
AboutButton.setFocusable(false);
menu.add(AboutButton);
menu.add(Box.createRigidArea(new Dimension(0, 20)));
JButton ExitButton = new JButton("Exit");
ExitButton.setMaximumSize(new Dimension(200, 50));
ExitButton.setFont(new Font("Serif", Font.PLAIN, 24));
ExitButton.setAlignmentX(CENTER_ALIGNMENT);
ExitButton.setFocusable(false);
menu.add(ExitButton);
ButtonListener actionListener = new ButtonListener(controller);
CreateAccount.addActionListener(actionListener);
LoginAccount.addActionListener(actionListener);
AboutButton.addActionListener(actionListener);
ExitButton.addActionListener(actionListener);
return menu;
}
}
public static class ButtonListener implements ActionListener {
private BankNavigationController controller;
public ButtonListener(BankNavigationController controller) {
this.controller = controller;
}
#Override
public void actionPerformed(ActionEvent e) {
controller.setView(e.getActionCommand());
}
}
}

Related

How do I use JLabel in ActionListener?

I am trying to show a text saying "The background is (color)" whenever I press a button that has the name of the color written on it but the text doesn't show up.
How it is supposed to be:
but mine is like this:
Here is my code:
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ThreeBtn extends JFrame {
private JButton btnRed;
private JButton btnGreen;
private JButton btnBlue;
public class ButtonListener implements ActionListener {
public void actionPerformed (ActionEvent e) {
if (e.getSource() == btnRed) {
(getContentPane()).setBackground(Color.red);
JLabel label = new JLabel("빨간색 배경입니다."); //it means "The background is red" in Korean label.setFont(new Font("Serif", Font.BOLD, 25));
label.setForeground(Color.yellow);
(getContentPane()).add(label);
}
else if(e.getSource()==btnGreen) {
(getContentPane()).setBackground(Color.green);
JLabel label = new JLabel("초록색 배경입니다."); //it means "The background is green" in Korean
label.setFont(new Font("Serif", Font.BOLD, 25));
label.setForeground(Color.yellow);
(getContentPane()).add(label);
}
else if(e.getSource()==btnBlue) {
(getContentPane()).setBackground(Color.blue);
JLabel label = new JLabel("파란색 배경입니다."); //it means "The background is blue" in Korean
label.setFont(new Font("Serif", Font.BOLD, 25));
label.setForeground(Color.yellow);
(getContentPane()).add(label);
}
}
}
public ThreeBtn() {
setSize(300, 200);
setTitle("Three Button Example");
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container cPane = getContentPane();
cPane.setLayout(new FlowLayout());
btnRed = new JButton("RED");
btnGreen = new JButton("GREEN");
btnBlue = new JButton("Blue");
ButtonListener listener = new ButtonListener();
btnRed.addActionListener(listener);
btnGreen.addActionListener(listener);
btnBlue.addActionListener(listener);
cPane.add(btnRed);
cPane.add(btnGreen);
cPane.add(btnBlue);
}
public static void main(String[] args) {
(new ThreeBtn()).setVisible(true);
}
}
I am wondering if I used JLabel in a wrong way in the ActionListener but I can't figure it out.
I would really appreciate your help.
When adding or deleting components to your GUI on runtime, you have to tell Swing that you did so. To do this, you should use revalidate() and repaint() on the container where the modification happened.
However, in your case, you don't actually need to always add a new JLabel on runtime, as you can simply do that when setting up the GUI, and only modifying the label that is already there. By doing it this way, you avoid having to revalidate() and repaint() (and it is also easier and cleaner this way).
I updated your code and did the following modificiations:
Moved the declaration and initialization of the JLabel out of the actionPerformed(), so you don't have to create a new JLabel each time a button is pressed. Now, only the text is changed. (A side effect of this change is, that the revalidate() and repaint() are actually not needed anymore, as no more component is added during runtime)
Started the GUI on the Event Dispatch Thread via SwingUtilities.invokeLater().
Usually it is also good practice in Swing to not create a subclass of JFrame if this is not specifically needed (like in your case). The better approach is to subclass JPanel, add the necessary components there, override getPreferredSize() and then add this to the JFrame. I have not included this change here, since it might have caused too much confusion.
Updated code:
public class ThreeBtn extends JFrame {
private JButton btnRed;
private JButton btnGreen;
private JButton btnBlue;
private JLabel label;
public class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
Container contentPane = getContentPane();
if (e.getSource() == btnRed) {
contentPane.setBackground(Color.red);
label.setText("red in korean");
} else if (e.getSource() == btnGreen) {
contentPane.setBackground(Color.green);
label.setText("green in korean");
} else if (e.getSource() == btnBlue) {
contentPane.setBackground(Color.blue);
label.setText("blue in korean");
}
}
}
public ThreeBtn() {
setSize(300, 200);
setTitle("Three Button Example");
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container cPane = getContentPane();
cPane.setLayout(new FlowLayout());
btnRed = new JButton("RED");
btnGreen = new JButton("GREEN");
btnBlue = new JButton("BLUE");
label = new JLabel("");
label.setFont(new Font("Serif", Font.BOLD, 25));
label.setForeground(Color.yellow);
ButtonListener listener = new ButtonListener();
btnRed.addActionListener(listener);
btnGreen.addActionListener(listener);
btnBlue.addActionListener(listener);
cPane.add(btnRed);
cPane.add(btnGreen);
cPane.add(btnBlue);
cPane.add(label);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> (new ThreeBtn()).setVisible(true));
}
}
Output:
This now works as per your requirements with the used FlowLayout. However, you may use another layout manager (or combine different ones) if you plan on doing more with it.
The Dimensions of the frame and panel where small so they did not show the text when you pressed the buttons.
Dimension size = label.getPreferredSize();
label.setBounds(150, 100, size.width, size.height);
I dont know if there are any rules for your program, but I would suggest, just limiting your if statements in ActionListener to the point where you set the foreground. Then make your JLabel object a class variable, and add the JLabel in the constructor. Here is the full edited code:
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ThreeBtn extends JFrame {
private static final long serialVersionUID = 1L;
private JButton btnRed;
private JButton btnGreen;
private JButton btnBlue;
private JLabel text = new JLabel();
public class ButtonListener implements ActionListener {
public void actionPerformed (ActionEvent e) {
if (e.getSource() == btnRed) {
(getContentPane()).setBackground(Color.red);
text.setText("red"); //it means "The background is red" in Korean
text.setFont(new Font("Serif", Font.BOLD, 25));
text.setForeground(Color.yellow);
}
else if(e.getSource()==btnGreen) {
(getContentPane()).setBackground(Color.green);
text.setText("green"); //it means "The background is green" in Korean
text.setFont(new Font("Serif", Font.BOLD, 25));
text.setForeground(Color.yellow);
}
else if(e.getSource()==btnBlue) {
(getContentPane()).setBackground(Color.blue);
text.setText("blue"); //it means "The background is blue" in Korean
text.setFont(new Font("Serif", Font.BOLD, 25));
text.setForeground(Color.yellow);
(getContentPane()).add(text);
}
}
}
public ThreeBtn() {
setSize(300, 200);
setTitle("Three Button Example");
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container cPane = getContentPane();
cPane.setLayout(new FlowLayout());
btnRed = new JButton("RED");
btnGreen = new JButton("GREEN");
btnBlue = new JButton("Blue");
ButtonListener listener = new ButtonListener();
btnRed.addActionListener(listener);
btnGreen.addActionListener(listener);
btnBlue.addActionListener(listener);
cPane.add(btnRed);
cPane.add(btnGreen);
cPane.add(btnBlue);
cPane.add(text);
}
public static void main(String[] args) {
(new ThreeBtn()).setVisible(true);
}
}

How to connect a JButton with a group of JRadioButtons?

I am creating a basic GUI frame. The frame has 10 radio buttons and a Submit button. The user selects one option(JRadioButtons) and clicks on the Submit(JButton) button. On clicking the Submit button, the option selected by the user appears on a different frame.
I want the Submit button to recognize the JRadioButton selected by the user.
I have put my bit of code here for reference.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Frame2 extends JFrame{
private JFrame frame2;
private JLabel label2;
private JButton button2;
private JRadioButton r1;
private JRadioButton r2;
private JRadioButton r3;
private JRadioButton r4;
private JRadioButton r5;
private JRadioButton r6;
private JRadioButton r7;
private JRadioButton r8;
private JRadioButton r9;
private JRadioButton r10;
public ButtonGroup group;
Frame2(){
setLayout(new BorderLayout());
setSize(new Dimension(1304,690));
getContentPane().setBackground(Color.DARK_GRAY);
label2= new JLabel(" Choose a topic: ");
label2.setFont(new Font("Seriff",Font.BOLD, 14));
label2.setForeground(Color.WHITE);
button2=new JButton("Submit");
add(label2, BorderLayout.NORTH);
JPanel centerPanel = new JPanel(new GridLayout(2, 5));
centerPanel.add(r1=new JRadioButton("Introduction"));
centerPanel.add(r2=new JRadioButton("Class and Objects"));
centerPanel.add(r3=new JRadioButton("Object Oriented Programming Concepts"));
centerPanel.add(r4=new JRadioButton("JAVA literals, constants, variables"));
centerPanel.add(r5=new JRadioButton("Loops"));
centerPanel.add(r6=new JRadioButton("Functions/Methods"));
centerPanel.add(r7=new JRadioButton("Strings"));
centerPanel.add(r8=new JRadioButton("Arrays"));
centerPanel.add(r9=new JRadioButton("Time Complexity"));
centerPanel.add(r10=new JRadioButton("Data Structures"));
add(centerPanel, BorderLayout.CENTER);
group= new ButtonGroup();
group.add(r1);
group.add(r2);
group.add(r3);
group.add(r4);
group.add(r5);
group.add(r6);
group.add(r7);
group.add(r8);
group.add(r9);
group.add(r10);
add(button2, BorderLayout.SOUTH);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(e.getSource()==button2) {
Layouts l=new Layouts();
l.main(null);
dispose();
}
}
});
}
public static void main(String[] args) {
Frame2 fr2=new Frame2();
}
}`
Thanks in advance.
It's a lot easier if you put the JRadioButtons in an array.
Here are the changes I made to your code to make it easier to modify and understand.
I added a call to the SwingUtilities invokeLater method to ensure the creation and execution of the Swing components happens on the Event Dispatch Thread.
I created the individual JPanels in methods. By separating the JPanel code, I could more easily focus on one part of the GUI at a time.
The methods to construct a JFrame must be called in the proper order. You have to create all the Swing components before you make the JFrame visible.
Here's one way to connect a JButton with a group of JRadioButtons.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
public class RadioButtonTest {
private JButton button2;
private JRadioButton[] rb;
private ButtonGroup group;
public RadioButtonTest() {
JFrame frame = new JFrame("Java Tutorials");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBackground(Color.DARK_GRAY);
frame.add(createMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel(new BorderLayout());
JLabel label2 = new JLabel(" Choose a topic: ");
label2.setFont(new Font("Seriff", Font.BOLD, 14));
label2.setForeground(Color.WHITE);
panel.add(label2, BorderLayout.NORTH);
panel.add(createButtonPanel(), BorderLayout.CENTER);
button2 = new JButton("Submit");
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button2) {
for (int i = 0; i < rb.length; i++) {
if (rb[i].isSelected()) {
String text = rb[i].getText();
System.out.println(text);
// Do your second JFrame
}
}
}
}
});
panel.add(button2, BorderLayout.SOUTH);
return panel;
}
private JPanel createButtonPanel() {
JPanel centerPanel = new JPanel(new GridLayout(0, 2));
String[] titles = { "Introduction", "Class and Objects",
"Object Oriented Programming Concepts",
"JAVA literals, constants, variables", "Loops",
"Functions/Methods", "Strings", "Arrays",
"Time Complexity", "Data Structures" };
rb = new JRadioButton[titles.length];
group = new ButtonGroup();
for (int i = 0; i < titles.length; i++) {
rb[i] = new JRadioButton(titles[i]);
group.add(rb[i]);
centerPanel.add(rb[i]);
}
return centerPanel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new RadioButtonTest();
}
});
}
}

Java swing gui change background of jlabel and make it reset

I have a gui that has:
a label at the top
a JFrame at the bottom with 2 Buttons called left and right
a panel in center that is gridlayout with 2 JLabel to either display an image or change the back ground color. (currently the background color is set to black for both jLabels).
*what I would like to happen.
When you click on button "left" the image appears on lblPicture1 and lblPicture2 has a black background and no image. and vise versa for the right button. and when you click on the left again, it repeats this cycle.
I accomplish that however, when i click the left and right button I just have two images and neither one has a black background.
I belive this is due to the image not resetting.
Can you direct me to the right place on how I can get this to work?
Thank you
package gui;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.GridLayout;
import javax.swing.ImageIcon;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ExampleGUI extends JFrame {
private JPanel contentPane;
private JLabel lblPicture1;
private JLabel lblPicture2;
private int change;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ExampleGUI frame = new ExampleGUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public ExampleGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JLabel lblExampleGui = new JLabel("Example GUI");
lblExampleGui.setBorder(new EmptyBorder(8, 0, 8, 0));
lblExampleGui.setFont(new Font("Lucida Grande", Font.PLAIN, 24));
lblExampleGui.setHorizontalAlignment(SwingConstants.CENTER);
contentPane.add(lblExampleGui, BorderLayout.NORTH);
JPanel panelButton = createPanelButton();
contentPane.add(panelButton, BorderLayout.SOUTH);
JButton btnLeft = createBtnLeft();
panelButton.add(btnLeft);
JButton btnRight = createBtnRight();
panelButton.add(btnRight);
JPanel panelCenter = createPanelCenter();
contentPane.add(panelCenter, BorderLayout.CENTER);
JLabel lblPicture1 = createLblPicture1();
panelCenter.add(lblPicture1);
JLabel lblPicture2 = createPicture2();
panelCenter.add(lblPicture2);
}
public JLabel createPicture2() {
lblPicture2 = new JLabel();
lblPicture2.setOpaque(true);
lblPicture2.setBackground(Color.BLACK);
return lblPicture2;
}
public JLabel createLblPicture1() {
lblPicture1 = new JLabel();
lblPicture1.setOpaque(true);
lblPicture1.setBackground(Color.BLACK);
//lblPicture1.setIcon(new ImageIcon(ExampleGUI.class.getResource("/gui/schlange.gif")));
return lblPicture1;
}
public JPanel createPanelCenter() {
JPanel panelCenter = new JPanel();
panelCenter.setLayout(new GridLayout(0, 2, 8, 0));
return panelCenter;
}
public JButton createBtnRight() {
JButton btnRight = new JButton("right");
btnRight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//TODO
lblPicture1.setBackground(Color.BLACK);
lblPicture2.setIcon(new ImageIcon(ExampleGUI.class.getResource("/gui/schlange.gif")));
}
});
btnRight.setFont(new Font("Lucida Grande", Font.PLAIN, 14));
return btnRight;
}
public JButton createBtnLeft() {
JButton btnLeft = new JButton("left");
btnLeft.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//TODO
lblPicture2.setBackground(Color.BLACK);
lblPicture1.setIcon(new ImageIcon(ExampleGUI.class.getResource("/gui/schlange.gif")));
}
});
btnLeft.setFont(new Font("Lucida Grande", Font.PLAIN, 14));
return btnLeft;
}
public JPanel createPanelButton() {
JPanel panelButton = new JPanel();
return panelButton;
}
}
The background is painted beneath the icon, so if the icon is not reset, then it will continue to be displayed.
You can simply set the icon property by passing it null, for example
public JButton createBtnLeft() {
JButton btnLeft = new JButton("left");
btnLeft.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//TODO
lblPicture2.setIcon(null);
lblPicture2.setBackground(Color.BLACK);
lblPicture1.setIcon(new ImageIcon(ExampleGUI.class.getResource("/gui/schlange.gif")));
}
});
btnLeft.setFont(new Font("Lucida Grande", Font.PLAIN, 14));
return btnLeft;
}

How to open new window after JProgressBar is completed

I created FlashScreen.java as loading screen consist of JProgressBar.
I want that after progressbar percentage is completed current window should be closed and new window should be open.
I made it but after closing first window in next window there is no component in window. Empty window is opening.
Here is code:
FlashScreen.java
package crimeManagement;
import javax.swing.*;
import java.awt.Rectangle;
import java.awt.Font;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class FlashScreen extends JFrame{
JProgressBar jb;
JLabel lblStat;
int i=0,num=0;
FlashScreen(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setBounds(new Rectangle(400, 200, 0, 0));
jb=new JProgressBar(0,2000);
jb.setBounds(100,219,579,22);
jb.setValue(0);
jb.setStringPainted(true);
getContentPane().add(jb);
setSize(804,405);
getContentPane().setLayout(null);
lblStat = new JLabel("");
lblStat.setForeground(Color.CYAN);
lblStat.setHorizontalAlignment(SwingConstants.CENTER);
lblStat.setHorizontalTextPosition(SwingConstants.CENTER);
lblStat.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 18));
lblStat.setBounds(229, 252, 329, 14);
getContentPane().add(lblStat);
JLabel lblBackGround = new JLabel("");
lblBackGround.setHorizontalTextPosition(SwingConstants.CENTER);
lblBackGround.setHorizontalAlignment(SwingConstants.CENTER);
lblBackGround.setIcon(new ImageIcon(FlashScreen.class.getResource("/Images/FlashImage.jpg")));
lblBackGround.setBounds(0, 0, 798, 376);
getContentPane().add(lblBackGround);
}
public void iterate(){
while(i<=2000){
jb.setValue(i);
i=i+20;
try{
Thread.sleep(50);
if(i==20)
{
lblStat.setText("Loading...");
}
if(i==500)
{
lblStat.setText("Please Wait...");
}
if(i==1000)
{
Thread.sleep(100);
lblStat.setText("Loading Police Station Management System...");
}
if(i==1200)
{
lblStat.setText("Please Wait...");
}
if(i==1600)
{
lblStat.setText("Almost Done...");
}
if(i==1980)
{
lblStat.setText("Done");
}
if(i==2000)
{
this.dispose();
LoginPage lp=new LoginPage();
lp.setVisible(true);
}
}
catch(Exception e){}
}
}
public static void main(String[] args) {
FlashScreen fs=new FlashScreen();
fs.setVisible(true);
fs.iterate();
}
}
**LoginPage.java**
package crimeManagement;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.border.*;
public class LoginPage extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JFrame frame;
private JTextField txtUserName;
private JPasswordField txtPass;
public static void main(String[] args) {
LoginPage window = new LoginPage();
window.frame.setVisible(true);
}
public LoginPage() {
frame = new JFrame();
frame.setResizable(false);
frame.getContentPane().setBackground(SystemColor.inactiveCaption);
frame.getContentPane().setFont(new Font("Tahoma", Font.PLAIN, 16));
frame.setBounds(100, 100, 554, 410);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblLoginType = new JLabel("Login Type");
lblLoginType.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblLoginType.setBounds(97, 53, 99, 20);
frame.getContentPane().add(lblLoginType);
JLabel lblUsename = new JLabel("User Name");
lblUsename.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblUsename.setBounds(97, 177, 99, 26);
frame.getContentPane().add(lblUsename);
JLabel lblPaaword = new JLabel("Password");
lblPaaword.setFont(new Font("Tahoma", Font.PLAIN, 16));
lblPaaword.setBounds(97, 223, 99, 26);
frame.getContentPane().add(lblPaaword);
JPanel panel = new JPanel();
FlowLayout flowLayout = (FlowLayout) panel.getLayout();
panel.setBackground(SystemColor.inactiveCaptionBorder);
panel.setBounds(210, 47, 143, 93);
frame.getContentPane().add(panel);
TitledBorder tb=new TitledBorder( "Login");
tb.setTitleJustification(TitledBorder.CENTER);
tb.setTitlePosition(TitledBorder.CENTER);
panel.setBorder(BorderFactory.createTitledBorder(tb));
JRadioButton rdbAdmin = new JRadioButton("Admin");
rdbAdmin.setBackground(SystemColor.inactiveCaption);
rdbAdmin.setFont(new Font("Tahoma", Font.PLAIN, 13));
rdbAdmin.setSelected(true);
panel.add(rdbAdmin);
JRadioButton rdbOthers = new JRadioButton("Others");
rdbOthers.setBackground(SystemColor.inactiveCaption);
rdbOthers.setFont(new Font("Tahoma", Font.PLAIN, 13));
panel.add(rdbOthers);
txtUserName = new JTextField();
txtUserName.setBackground(UIManager.getColor("TextField.background"));
txtUserName.setBounds(210, 177, 158, 26);
frame.getContentPane().add(txtUserName);
txtUserName.setColumns(30);
JButton btnLogin = new JButton("Login");
btnLogin.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnLogin.setBounds(210, 286, 71, 23);
frame.getContentPane().add(btnLogin);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
btnExit.setFont(new Font("Tahoma", Font.PLAIN, 14));
btnExit.setBounds(297, 286, 71, 23);
frame.getContentPane().add(btnExit);
txtPass = new JPasswordField();
txtPass.setBounds(210, 226, 158, 26);
frame.getContentPane().add(txtPass);
}
}
You're displaying the wrong JFrame. Yes the LoginPage extends JFrame, and yes you display it, but you add no components to it, and instead add all components to a private JFrame field of the class named, frame.
A quick solution is to change your LoginPage class so that it doesn't extend JFrame and then give this class a public getFrame() method:
public JFrame getFrame() {
return frame;
}
and when wanting to show it, call
this.dispose();
LoginPage lp = new LoginPage();
// lp.setVisible(true);
lp.getFrame().setVisible(true);
but having said this, there are still some serious threading issues with your code that you'll eventually want to fix, including trying to avoid calling Thread.sleep() in code that risks being called on the Swing event thread.
Also please check out The Use of Multiple JFrames: Good or Bad Practice? to see why it is often a bad practice to display a bunch of JFrames in your app, and ways around this.
Other issues include use of null layouts. Yes they may seem like an easy way to create complex GUI's quickly -- until you try to show the GUI on another platform and find that they don't look so nice, or have to enhance, debug or change it, and find it very tricky and easy to mess up. Much better to use layout managers.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class FlashScreenTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame mainFrame = new JFrame("Main App");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.add(new MainAppPanel());
mainFrame.pack();
mainFrame.setLocationRelativeTo(null);
FlashScreenPanel dialogPanel = new FlashScreenPanel();
JDialog dialog = new JDialog(mainFrame, "Flash Screen", ModalityType.APPLICATION_MODAL);
dialog.add(dialogPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialogPanel.startProgress();
dialog.setVisible(true);
mainFrame.setVisible(true);
});
}
}
class FlashScreenPanel extends JPanel {
public static final String LOADING = "Loading...";
public static final String PLEASE_WAIT = "Please Wait...";
public static final String LOADING_POLICE_STATION = "Loading Police Station...";
public static final String ALMOST_DONE = "Almost Done...";
public static final String DONE = "Done";
private static final int TIMER_DELAY = 50;
private JProgressBar jb = new JProgressBar(0, 2000);
private JLabel statusLabel = new JLabel("", SwingConstants.CENTER);
public FlashScreenPanel() {
setPreferredSize(new Dimension(800, 400));
statusLabel.setForeground(Color.CYAN);
statusLabel.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 18));
jb.setStringPainted(true);
JPanel bottomPanel = new JPanel(new BorderLayout(20, 20));
bottomPanel.add(jb, BorderLayout.PAGE_START);
bottomPanel.add(statusLabel, BorderLayout.CENTER);
int eb = 40;
setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb));
setLayout(new GridLayout(0, 1));
add(new JLabel()); // dummy component to move prog bar lower
add(bottomPanel);
}
public void startProgress() {
statusLabel.setText(LOADING);
new Timer(TIMER_DELAY, new ActionListener() {
private int i = 0;
#Override
public void actionPerformed(ActionEvent e) {
i += 20;
jb.setValue(i);
if (i == 500) {
statusLabel.setText(PLEASE_WAIT);
} else
if (i == 1000) {
statusLabel.setText(LOADING_POLICE_STATION);
} else
if (i == 1200) {
statusLabel.setText(PLEASE_WAIT);
} else
if (i == 1600) {
statusLabel.setText(ALMOST_DONE);
} else
if (i == 1980) {
statusLabel.setText(DONE);
} else
if (i == 2000) {
((Timer) e.getSource()).stop();
Window win = SwingUtilities.getWindowAncestor(FlashScreenPanel.this);
win.dispose();
}
}
}).start();
}
}
class MainAppPanel extends JPanel {
public MainAppPanel() {
setPreferredSize(new Dimension(600, 400));
}
}

Oppening a new JFrame with a JButton click [duplicate]

I want to open a new JFrame by clicking a button (btnAdd); I have tried to create an actionlistener but I am having no luck; the code runs but nothing happens when the button is clicked. The methods in question are the last two in the following code. Any help is much appreciated!
package AdvancedWeatherApp;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.event.ListSelectionListener;
import weatherforecast.FetchWeatherForecast;
public class MainFrame extends JFrame implements ListSelectionListener {
private boolean initialized = false;
private Actions actions = new Actions();
private javax.swing.JScrollPane jspFavouritesList = new javax.swing.JScrollPane();
private javax.swing.DefaultListModel<String> listModel = new javax.swing.DefaultListModel<String>();
private javax.swing.JList<String> favouritesList = new javax.swing.JList<String>(
listModel);
private javax.swing.JLabel lblAcknowledgement = new javax.swing.JLabel();
private javax.swing.JLabel lblTitle = new javax.swing.JLabel();
private javax.swing.JButton btnAdd = new javax.swing.JButton();
private javax.swing.JButton btnRemove = new javax.swing.JButton();
public void initialize() {
initializeGui();
initializeEvents();
this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
/**
*
*/
private void initializeGui() {
if (initialized)
return;
initialized = true;
this.setSize(500, 400);
Dimension windowSize = this.getSize();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(screenSize.width / 2 - windowSize.width / 2,
screenSize.height / 2 - windowSize.height / 2);
Container pane = this.getContentPane();
pane.setLayout(new BorderLayout());
setLayout(new BorderLayout());
setTitle("Favourite Weather Locations");
JPanel jpSouth = new JPanel();
jpSouth.setLayout(new FlowLayout());
JPanel jpNorth = new JPanel();
jpNorth.setLayout(new FlowLayout());
JPanel jpCenter = new JPanel();
jpCenter.setLayout(new BoxLayout(jpCenter, BoxLayout.PAGE_AXIS));
JPanel jpEast = new JPanel();
JPanel jpWest = new JPanel();
getContentPane().setBackground(Color.WHITE);
jpEast.setBackground(Color.WHITE);
jpWest.setBackground(Color.WHITE);
jpCenter.setBackground(Color.WHITE);
getContentPane().add(jspFavouritesList);
jpCenter.add(jspFavouritesList);
jspFavouritesList.setViewportView(favouritesList);
favouritesList
.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
favouritesList.addListSelectionListener(this);
jpCenter.add(btnAdd);
jpCenter.add(btnRemove);
jpCenter.setAlignmentY(CENTER_ALIGNMENT);
btnAdd.setText("Add Location");
btnAdd.setAlignmentX(Component.CENTER_ALIGNMENT);
btnAdd.setFont(new Font("Calibri", Font.PLAIN, 18));
jpCenter.add(btnRemove);
btnRemove.setText("Remove Location");
btnRemove.setAlignmentX(Component.CENTER_ALIGNMENT);
btnRemove.setFont(new Font("Calibri", Font.PLAIN, 18));
getContentPane().add(jpEast, BorderLayout.EAST);
getContentPane().add(jpWest, BorderLayout.WEST);
getContentPane().add(jpSouth);
jpSouth.add(lblAcknowledgement);
add(lblAcknowledgement, BorderLayout.SOUTH);
lblAcknowledgement.setText(FetchWeatherForecast.getAcknowledgement());
lblAcknowledgement.setHorizontalAlignment(SwingConstants.CENTER);
lblAcknowledgement.setFont(new Font("Tahoma", Font.ITALIC, 12));
getContentPane().add(jpNorth);
jpNorth.add(lblTitle);
add(lblTitle, BorderLayout.NORTH);
lblTitle.setText("Your Favourite Locations");
lblTitle.setHorizontalAlignment(SwingConstants.CENTER);
lblTitle.setFont(new Font("Calibri", Font.PLAIN, 32));
lblTitle.setForeground(Color.DARK_GRAY);
getContentPane().add(jpCenter);
}
private void initializeEvents() {
// TODO: Add action listeners, etc
}
public class Actions implements ActionListener {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
command = command == null ? "" : command;
// TODO: add if...if else... for action commands
}
}
public void dispose() {
// TODO: Save settings
// super.dispose();
System.exit(0);
}
public void setVisible(boolean b) {
initialize();
super.setVisible(b);
}
public static void main(String[] args) {
new MainFrame().setVisible(true);
}
public void actionPerformed(ActionEvent evt){
if (evt.getSource() == btnAdd) {
showNewFrame();
//OPEN THE SEARCH WINDOW
}
}
private void showNewFrame() {
JFrame frame = new JFrame("Search Window" );
frame.setSize( 500,120 );
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
}
Although you have implemented the actionPerformed method as per the ActionListener interface, you class is not of that that type as you haven't implemented the interface. Once you implement that interface and register it with the JButton btnAdd,
btnAdd.addActionListener(this);
the method will be called.
A more compact alternative might be to use an anonymous interface:
btnAdd.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// handle button ActionEvent & display dialog...
}
});
Side notes:
Using more than one JFrame in an application creates a lot of overhead for managing updates that may need to exist between frames. The preferred approach is to
use a modal JDialog if another window is required. This is discussed more here.
Use this :
btnAdd.addActionListener(this);
#Override
public void actionPerformed(ActionEvent e)
{
MainFrame frame = new MainFrame();
frame.setVisible(true);
}
Type this inside the button
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
this.dispose();
ActionListener ActList = new ActionListener();
ActList.setVisible(true);
}
see my last line
{
ActList.setVisible(true);
}

Categories

Resources