I am new to Java Swing. I am creating a frame with some components.
I have to close the frame and open another frame when the button is clicked. I had tried setVisible(false) but it only hides the frame, not closing it. When I use System.exit(0), it closed all the frames.
I had tried in another way, i.e. add all the components to panel, and add the panel at first. When the frame has to close I just remove those components in actionListener and add the other components for the corresponding next process.
My entire code is as follows:
package JavaApp;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.IllegalBlockSizeException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Login extends JFrame {
public static JLabel labelUser;
public static JLabel labelPass;
public static JTextField textFieldUser;
public static JPasswordField passwordField;
public static JButton clear;
public static JButton buttonLogin;
public static JButton ChangePassword;
public static JButton MasterKey;
public static JButton AppKey;
public static JPanel panelGnereate;
public static JPanel panelLogin;
public static JFrame frame;
public static JLabel UserName;
public static JTextField UserTxt;
public static JButton GenerateKey;
public static JPanel panelMaster;
private static void designUI() {
frame = new JFrame("Instalation");
frame.setLayout(new GridLayout(2, 1));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panelLogin = new JPanel();
panelLogin.setLayout(null);
labelUser = new JLabel("Enter UserName");
textFieldUser = new JTextField(10);
labelPass = new JLabel("Enter Password");
passwordField = new JPasswordField(10);
buttonLogin = new JButton("Login");
clear = new JButton("Cancel");
panelLogin.add(buttonLogin);
panelLogin.add(clear);
panelLogin.add(labelUser);
panelLogin.add(textFieldUser);
panelLogin.add(labelPass);
panelLogin.add(passwordField);
textFieldUser.setBounds(200, 120, 100, 20);
labelUser.setBounds(50, 120, 120, 20);
labelPass.setBounds(50, 150, 120, 20);
passwordField.setBounds(200, 150, 100, 20);
buttonLogin.setBounds(70, 180, 100, 20);
clear.setBounds(200, 180, 100, 20);
buttonLogin.addActionListener(actionEvent);
clear.addActionListener(actionEvent);
frame.add(panelLogin);
//Login frame ends...
//Gnereate frame starts here..
panelGnereate = new JPanel();
panelGnereate.setLayout(null);
ChangePassword = new JButton("Change Password");
MasterKey = new JButton("Create Master Key");
AppKey = new JButton("Create Application key");
panelGnereate.add(ChangePassword);
panelGnereate.add(MasterKey);
panelGnereate.add(AppKey);
ChangePassword.setBounds(150, 100, 200, 25);
MasterKey.setBounds(150, 150, 200, 25);
AppKey.setBounds(150, 200, 200, 25);
ChangePassword.addActionListener(actionEvent);
MasterKey.addActionListener(actionEvent);
AppKey.addActionListener(actionEvent);
//Gnerate Frame ends here..
//MasterKey Generate Starts Here..
panelMaster = new JPanel();
panelMaster.setLayout(null);
UserName = new JLabel("Text");
UserTxt = new JTextField(20);
GenerateKey = new JButton("Generate Key");
panelMaster.add(UserName);
panelMaster.add(UserTxt);
panelMaster.add(GenerateKey);
UserName.setBounds(150, 150, 50, 25);
UserTxt.setBounds(220, 150, 100, 25);
GenerateKey.setBounds(180, 180, 150, 25);
GenerateKey.addActionListener(actionEvent);
frame.setSize(500, 500);
frame.setVisible(true);
}
public static void main(String args[]) {
designUI();
}
private static ActionListener actionEvent = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if ("Login".equals(action)) {
System.out.println("Login action" + e.getActionCommand());
if ("".equals(textFieldUser.getText()) || "".equals(passwordField.getText())) {
JOptionPane.showMessageDialog(null,
"Enter Both UserName and Password");
} else if ("admin".equals(textFieldUser.getText()) && "admin".equals(passwordField.getText())) {
System.out.println("login value" + textFieldUser.getText() + " " + passwordField.getText());
frame.remove(panelLogin);
frame.add(panelGnereate);
frame.setVisible(true);
} else {
JOptionPane.showMessageDialog(null,
"Wrong Password");
}
} else if ("Cancel".equals(action)) {
System.out.println(e.getActionCommand());
System.exit(0);
} else if ("Change Password".equals(action)) {
} else if ("Create Master Key".equals(action)) {
frame.remove(panelGnereate);
frame.add(panelMaster);
frame.setVisible(true);
} else if ("Create Application key".equals(action)) {
System.out.println("Message " + UserTxt.getText());
frame.setVisible(false);
}else if("Generate Key".equals(action))
{
try {
new GenerateTxt(UserTxt.getText());
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalBlockSizeException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
frame.remove(panelMaster);
frame.add(panelGnereate);
frame.setVisible(true);
}
}
;
};
}
It's not working for throughout the process. When I click the master key it showing relevant textbox after clicking genearteKey it showing same panel not the previous one. But when I am moving the mouse over there it is showing the components of the both panels.
looking at your code, you'll probably need something like this:
if(frame == null)
frame = new JFrame();
else {
//remove the previous JFrame
frame.setVisible(false);
frame.dispose();
//create a new one
frame = new JFrame();
}
you'll have to put this inside the actionperformed method so that the frame can be removed..
btw, it would be a gd idea to change your class variables from public to private, in accordance with good programming practice..
EDIT: To answer the "flickering" problem.
you're accessing the swing component from outside the event thread. swing widgets arent generally thread safe. as such, u need to modify your main method:
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
designUI();
}
});
}
also, refer to Swing component flickering when updated a lot for further queries.
You can send a closing event to the frame/dialog. Like this:
WindowEvent winClosingEvent = new WindowEvent( targetFrame, WindowEvent.WINDOW_CLOSING );
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent( winClosingEvent );
I sometimes implement close() method in my frames/dialogs like this:
public void close() {
WindowEvent winClosingEvent = new WindowEvent( this, WindowEvent.WINDOW_CLOSING );
Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent( winClosingEvent );
}
Hope that helped...
Did you try calling dispose() on the frame? I think that may be what you're looking for.
Related
I am making autoclicker as a project and when i open now the window design thingy its shows me just a blank.
im trying to ask from the user to write a number in the spinner
the spinner sending it to the delay.
than you press a key to run the autoclicker and stop him
but i still didnt put the keylistener now im just trying to get output which is the delay from the spinner, not work well till now.
package autoclicker;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.InputEvent;
import java.util.*;
import javax.swing.JFormattedTextField;
public class auto {
static Scanner console = new Scanner(System.in);
private Robot robot;
private int delay;
public void AutoClicker1() {
try
{
robot = new Robot();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void clickMouse(int button)
{
try {
robot.mousePress(button);
robot.delay(10);
robot.mouseRelease(button);
robot.delay(delay);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void setDelay(int delayy)
{
this.delay = delayy;
}
}
THIS IS THE MAIN
package autoclicker;
import javax.swing.*;
import java.awt.event.InputEvent;
import java.lang.Thread;
import java.util.Scanner;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class autoclicker {
private static KeyEvent e;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner console = new Scanner(System.in);
JFrame frame = new JFrame("AutoClicker");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 500);
frame.setVisible(true);
frame.setResizable(false);
JPanel Panel = new JPanel();
Panel.setBackground(Color.DARK_GRAY);
Panel.setLayout(null);
JLabel AutoClicker = new JLabel("delay\r\n in ms");
AutoClicker.setBounds(10, 80, 151, 30);
AutoClicker.setForeground(Color.WHITE);
AutoClicker.setFont(new Font("Secular One", Font.PLAIN, 20));
JLabel label = new JLabel("AutoClicker");
label.setForeground(Color.CYAN);
label.setFont(new Font("Secular One", Font.PLAIN, 30));
label.setBounds(10, 11, 200, 57);
Panel.add(label);
JSpinner spinner = new JSpinner();
int Delayy = (int) spinner.getValue();
spinner.setBounds(128, 87, 69, 20);
Panel.add(spinner);
frame.add(Panel);
auto clicker = new auto();
System.out.println("----Auto Clicker----");
System.out.println("Enter delay in ms:");
while(Delayy==0)
{
}
clicker.setDelay(Delayy);
System.out.println("Program will start in 3 seconds.");
try {
System.out.println(3);
Thread.sleep(1000);
System.out.println(2);
Thread.sleep(1000);
System.out.println(1);
Thread.sleep(1000);
}
catch (Exception e)
{
e.printStackTrace();
}
clicker.AutoClicker1();
for(int i = 0; i<100; i++)
{
clicker.clickMouse(InputEvent.BUTTON1_DOWN_MASK);
}
}
}
You need to add your panel to your JFrame.
frame.add(Panel);
Once you add components to your JFrame you then need to setVisibility() to true in order for it to show.
frame.setVisible(true);
I was designing a program which has multiple layers(panels), and I want these panels to be keyboard sensitive so that I can press ESC to exit to the main menu (First panel) at any time.
Here is the switch panel code that I've written:
public void switchPane(JPanel jp) {
frmDavidsAppstore.getContentPane().removeAll();
frmDavidsAppstore.getContentPane().add(jp);
frmDavidsAppstore.getContentPane().repaint();
frmDavidsAppstore.getContentPane().revalidate();
jp.requestFocusInWindow();
}
I know that in order for the panel to be keyboard sensitive, it needs to be focusable.
Here's the code I have written for the initialisation of one of the panels:
panel2 = new JPanel();
panel2.setFocusable(true);
frmDavidsAppstore.getContentPane().add(panel2, "name_83147693736131");
panel2.setLayout(null);
panel2.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("panel2: " + KeyEvent.getKeyText(e.getKeyCode()));
if(e.getKeyCode()==KeyEvent.VK_ESCAPE) {
switchPane(panel1);
}
}
});
JButton btnReturnToMain = new JButton("Return to main page");
btnReturnToMain.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
switchPane(panel1);
}
});
btnReturnToMain.setBounds(279, 431, 236, 50);
panel2.add(btnReturnToMain);
I have deleted most of the unrelated functions and codes.
What I wish to accomplish is that when the switch page button is clicked, the switchPane method is executed, and the new panel automatically gets the focus with the requestFocusInWindow(); command, so that user can type ESC to return to the main menu.
When I tried to run the program, it turns out that for the first time I entered a sub-panel, it can not get the focus and does not respond to the keyboard. However, if I return to the main panel using the return button and re-enter the same sub-panel, this time it automatically gets the focus and is responding to the keyboard.
I have no idea why the program shows such behaviour. The following is the full program. Please notice that in the full program I also added a click to get focus function which works. However, I wish the newly opened panel can automatically get the focus and responding to the keys without the user actually clicking the panel.
import java.awt.*;
import javax.swing.JFrame;
import java.awt.CardLayout;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import java.awt.Font;
import javax.swing.JList;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class mainFrame {
private JFrame frmDavidsAppstore;
private JPanel panel1;
private JPanel panel2;
private JPanel panel3;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainFrame window = new mainFrame();
window.frmDavidsAppstore.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public mainFrame() {
initialize();
}
public void switchPane(JPanel jp) {
frmDavidsAppstore.getContentPane().removeAll();
frmDavidsAppstore.getContentPane().add(jp);
frmDavidsAppstore.getContentPane().repaint();
frmDavidsAppstore.getContentPane().revalidate();
jp.requestFocusInWindow();
System.out.println(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner());
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmDavidsAppstore = new JFrame();
frmDavidsAppstore.setResizable(false);
frmDavidsAppstore.setTitle("David's appstore");
frmDavidsAppstore.setBounds(100, 100, 800, 600);
frmDavidsAppstore.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmDavidsAppstore.getContentPane().setLayout(new CardLayout(0, 0));
panel1 = new JPanel();
panel1.setFocusable(true);
frmDavidsAppstore.getContentPane().add(panel1, "name_83127645466169");
panel1.setLayout(null);
panel1.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("panel1: " + KeyEvent.getKeyText(e.getKeyCode()));
}
});
JButton button2 = new JButton("Open page 2");
button2.setFont(new Font("Tahoma", Font.PLAIN, 18));
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
switchPane(panel2);
}
});
button2.setBounds(279, 344, 236, 50);
panel1.add(button2);
JButton button3 = new JButton("Open page 3");
button3.setFont(new Font("Tahoma", Font.PLAIN, 18));
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
switchPane(panel3);
}
});
button3.setBounds(279, 432, 236, 50);
panel1.add(button3);
JLabel background = new JLabel("");
background.setIcon(new ImageIcon(mainFrame.class.getResource("/images/background_main.jpg")));
background.setBounds(0, 0, 794, 565);
panel1.add(background);
panel2 = new JPanel();
panel2.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
panel2.requestFocusInWindow();
System.out.println(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner());
}
});
panel2.setFocusable(true);
frmDavidsAppstore.getContentPane().add(panel2, "name_83147693736131");
panel2.setLayout(null);
panel2.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("panel2: " + KeyEvent.getKeyText(e.getKeyCode()));
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
switchPane(panel1);
}
}
});
JScrollPane scrollPane_1 = new JScrollPane();
scrollPane_1.setBounds(130, 104, 533, 270);
panel2.add(scrollPane_1);
JTextArea txtrIAmPage = new JTextArea();
txtrIAmPage.setEditable(false);
scrollPane_1.setViewportView(txtrIAmPage);
txtrIAmPage.setText("I am page2");
JButton btnReturnToMain = new JButton("Return to main page");
btnReturnToMain.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
switchPane(panel1);
}
});
btnReturnToMain.setBounds(279, 431, 236, 50);
panel2.add(btnReturnToMain);
panel3 = new JPanel();
panel3.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
panel3.requestFocusInWindow();
System.out.println(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner());
}
});
panel3.setFocusable(true);
frmDavidsAppstore.getContentPane().add(panel3, "name_83334788966651");
panel3.setLayout(null);
panel3.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("panel3: " + KeyEvent.getKeyText(e.getKeyCode()));
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
switchPane(panel1);
}
}
});
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(130, 104, 533, 270);
panel3.add(scrollPane);
JTextArea txtrIAmPage_1 = new JTextArea();
scrollPane.setViewportView(txtrIAmPage_1);
txtrIAmPage_1.setText("I am page3");
JButton button = new JButton("Return to main page");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
switchPane(panel1);
}
});
button.setBounds(279, 431, 236, 50);
panel3.add(button);
}
}
I have been working on it for a day now and couldn't figure out why. Thank you guys so much for any help or advices.
Apreciated!
Problem solved!!! You need to add .setVisible(true); before .requestFocusInWindow(); in order for it to work!
I am having trouble replacing ImageIcon with a first ImageIcon whereupon a Jbutton is pressed. So far I have tried replacing the frame, .setIcon(myNewImage);, and .remove();. Not sure what to do now... (I'll need to replace and resize them.) Here is my code. (It is supposed to be like one of those Japanese dating games... please ignore that the pictures are local I have no site to host them yet.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import java.util.Scanner;
import javax.swing.ImageIcon;
import javax.swing.*;
import java.awt.*;
public class NestedPanels extends JPanel {
JPanel southBtnPanel = new JPanel(new GridLayout(3, 2, 1, 1)); //grid layout of buttons and declaration of panel SoutbtnPanel
JButton b = new JButton("Say Hello");//1
JButton c = new JButton("Say You Look Good");//1
JButton d = new JButton("Say Sorry I'm Late");//1
JButton e2 = new JButton("So where are we headed?");//2
JButton f = new JButton("Can we go to your place?");//2
JButton g = new JButton("I don't have any money for our date...");//2
public NestedPanels() { //implemeted class
//add action listener
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button1Clicked(e);//when button clicked, invoke method
}
});
c.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button2Clicked(e);//when button clicked, invoke method
}
});
d.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button3Clicked(e);//when button clicked, invoke method
}
});
e2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button4Clicked(e);//when button clicked, invoke method
}
});
f.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button5Clicked(e);//when button clicked, invoke method
}
});
g.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button6Clicked(e);//when button clicked, invoke method
}
});
southBtnPanel.add(b);
southBtnPanel.add(c);
southBtnPanel.add(d);
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1)); //layout of buttons "Button text"
setLayout(new BorderLayout());
add(Box.createRigidArea(new Dimension(600, 600))); //space size of text box webapp over all
add(southBtnPanel, BorderLayout.SOUTH);
}
private static void createAndShowGui() {//class to show gui
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.getContentPane().add(mainPanel);
ImageIcon icon = new ImageIcon("C:/Users/wchri/Pictures/10346538_10203007241845278_2763831867139494749_n.jpg");
JLabel label = new JLabel(icon);
mainPanel.add(label);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private void button1Clicked(ActionEvent e) {
southBtnPanel.removeAll();
southBtnPanel.add(e2);
southBtnPanel.add(f);
southBtnPanel.add(g);
southBtnPanel.revalidate();
southBtnPanel.repaint();
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "Hey there! Ready to get started?", "Christian feels good!", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button2Clicked(ActionEvent e) {
southBtnPanel.removeAll();
southBtnPanel.add(e2);
southBtnPanel.add(f);
southBtnPanel.add(g);
southBtnPanel.revalidate();
southBtnPanel.repaint();
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "Ugh... thanks! You too ready?!", "Christian is a bit... Embarrased.", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button3Clicked(ActionEvent e) {
southBtnPanel.removeAll();
southBtnPanel.add(e2);
southBtnPanel.add(f);
southBtnPanel.add(g);
southBtnPanel.revalidate();
southBtnPanel.repaint();
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "It's ok! Just make sure it doesn't happen again!", "Christian is a bit angry!", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button4Clicked(ActionEvent e) {
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.getContentPane().add(mainPanel);
JLabel label = new JLabel();
ImageIcon imageTwo = new ImageIcon("C:/Users/wchri/Documents/chrisferry.jpg");
mainPanel.add(label);
label.setIcon(imageTwo);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.getContentPane().add(mainPanel);
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "Let's take the ferry to NYC!", "Christian feels good!", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button5Clicked(ActionEvent e) {
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.getContentPane().add(mainPanel);
JLabel label = new JLabel();
ImageIcon imageThree = new ImageIcon("C:/Users/wchri/Pictures/Screenshots/chrisart.jpg");
mainPanel.add(label);
label.setIcon(imageThree);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.getContentPane().add(mainPanel);
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "Don't you think it's a bit soon for that?", "Christian is embarrassed...", JOptionPane.PLAIN_MESSAGE); //display button Action
}
private void button6Clicked(ActionEvent e) {
NestedPanels mainPanel = new NestedPanels(); //mainPanel new class of buttons instantiation
JFrame frame = new JFrame("Date Sim 1.0");//title of webapp on top
frame.getContentPane().add(mainPanel);
JLabel label = new JLabel();
ImageIcon imageFour = new ImageIcon("C:/Users/wchri/Downloads/chrismoney.jpg");
mainPanel.add(label);
label.setIcon(imageFour);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.getContentPane().add(mainPanel);
String msg = ((JButton)e.getSource()).getActionCommand() ;
JOptionPane.showMessageDialog(this, "I got money!", "Christian is ballin'", JOptionPane.PLAIN_MESSAGE); //display button Action
}
public static void main(String[] args) {
System.out.println("Welcome to Date Sim 1.0 with we1. Are you ready to play? Yes/No?");
Scanner in = new Scanner(System.in);
String confirm = in.nextLine();
if (confirm.equalsIgnoreCase("Yes")) {
System.out.println("Ok hot stuff... Let's start.");
NestedPanels mainPanel = new NestedPanels();
} else {
System.out.println("Maybe some other time!");
return;
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowGui();
}
});
}
}
Here is MCVE that demonstrates changing an icon on a JButton when it is clicked:
import java.io.IOException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class ChangeButtonIcon extends JPanel{
private URL[] urls = {
new URL("https://findicons.com/files/icons/345/summer/128/cake.png"),
new URL("http://icons.iconarchive.com/icons/atyourservice/service-categories/128/Sweets-icon.png"),
new URL("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcS_FkBgG3_ux0kCbfG8mcRHvdk1dYbZYsm2SFMS01YvA6B_zfH_kg"),
};
private int iconNumber = 0;
private JButton button;
public ChangeButtonIcon() throws IOException {
button = new JButton();
button.setIcon(new ImageIcon(urls[iconNumber]));
button.setHorizontalTextPosition(SwingConstants.CENTER);
button.addActionListener(e -> swapIcon());
add(button);
}
private void swapIcon() {
iconNumber = iconNumber >= (urls.length -1) ? 0 : iconNumber+1;
button.setIcon(new ImageIcon(urls[iconNumber]));
}
public static void main(String[] args) throws IOException{
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(new ChangeButtonIcon());
window.pack();
window.setVisible(true);
}
}
I find writting MCVE a very useful technique. Not only it makes helping much easier, it
is a powerful debugging tool. It many case, while preparing one, you are likely to find the problem.
It should represent the problem or the question asked. Not your application.
I am try to run the progress bar in my frame but it is not working. I am tried to display the visible in my second java class but set visible(true) displaying it as error.
Hope you guys can help me to solve my problem/error
Displaying error in my second java class:
"Exception in thread "main"
java.lang.Error: Unresolved compilation problem: The method
setvisible(boolean) is undefined for the type mgfinancewindow"
First java class: mgfinancewindow.java
package mgfinance;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import java.awt.Color;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
public class mgfinancewindow {
private JFrame frame;
public JProgressBar progressBar;
public JLabel lblNewLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mgfinancewindow window = new mgfinancewindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public mgfinancewindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame("MG Finances");
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 1362, 705);
frame.getContentPane().add(panel);
panel.setLayout(null);
JPanel panel_1 = new JPanel();
panel_1.setBackground(Color.DARK_GRAY);
panel_1.setBounds(0, 646, 1362, 59);
panel.add(panel_1);
panel_1.setLayout(null);
lblNewLabel = new JLabel("Loading...");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 16));
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setForeground(Color.WHITE);
lblNewLabel.setBounds(1139, 0, 114, 34);
panel_1.add(lblNewLabel);
progressBar = new JProgressBar();
progressBar.setBackground(new Color(0, 51, 51));
progressBar.setBounds(0, 34, 1362, 14);
panel_1.add(progressBar);
JLabel lblMgFinance = new JLabel("MG Finance");
lblMgFinance.setHorizontalAlignment(SwingConstants.CENTER);
lblMgFinance.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 16));
lblMgFinance.setForeground(Color.BLUE);
lblMgFinance.setBounds(0, 11, 1362, 635);
panel.add(lblMgFinance);
}
}
second java class: progressbar.java
package mgfinance;
public class progress {
public static void main(String[] args) throws InterruptedException{
mgfinancewindow load = new mgfinancewindow();
for(int i=0; i<=100; i++){
Thread.sleep(150);
load.setvisible(true);
load.lblNewLabel.setText("Loading..."+ i);
load.progressBar.setValue(i);
}
}
}
Your mgfinancewindow class is not a JComponent to support the setVisible() method itself. The JFrame inside it has the setVisible method.
In the way you wrote the code, to solve your problem quickly you must write the frame.setVisible(true); at the end (last statement) of initialize() method in mgfinancewindow class and remove load.setvisible(true); from the main method of progress class:
public class progress {
public static void main(String[] args) throws InterruptedException {
mgfinancewindow load = new mgfinancewindow();
for (int i = 0; i <= 100; i++) {
Thread.sleep(150);
//load.setvisible(true);
load.lblNewLabel.setText("Loading..." + i);
load.progressBar.setValue(i);
}
}
}
and
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.JProgressBar;
import javax.swing.SwingConstants;
public class mgfinancewindow {
private JFrame frame;
public JProgressBar progressBar;
public JLabel lblNewLabel;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mgfinancewindow window = new mgfinancewindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public mgfinancewindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame("MG Finances");
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(0, 0, 1362, 705);
frame.getContentPane().add(panel);
panel.setLayout(null);
JPanel panel_1 = new JPanel();
panel_1.setBackground(Color.DARK_GRAY);
panel_1.setBounds(0, 646, 1362, 59);
panel.add(panel_1);
panel_1.setLayout(null);
lblNewLabel = new JLabel("Loading...");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 16));
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setForeground(Color.WHITE);
lblNewLabel.setBounds(1139, 0, 114, 34);
panel_1.add(lblNewLabel);
progressBar = new JProgressBar();
progressBar.setBackground(new Color(0, 51, 51));
progressBar.setBounds(0, 34, 1362, 14);
panel_1.add(progressBar);
JLabel lblMgFinance = new JLabel("MG Finance");
lblMgFinance.setHorizontalAlignment(SwingConstants.CENTER);
lblMgFinance.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 16));
lblMgFinance.setForeground(Color.BLUE);
lblMgFinance.setBounds(0, 11, 1362, 635);
panel.add(lblMgFinance);
frame.setVisible(true);
}
}
But:
When you are creating a component like mgfinancewindow which creates a JFrame inside, most of the times it's better to extend from JFrame and then you can create an object from it and call the setVisible method on it in the main method of your program or so. It's better not to call setVisible inside that component, because in another classes sometimes you want to create and initialize the mgfinancewindow but you don't want to make it visible immediately.
Another hints:
According to Java Coding Conventions:
Your class names must follow the CamelCase style.
Variable names must follow the camelCase (first letter in lower-case) style.
You may want to take a look at other java coding conventions here.
i would like to know how can i see the components in my JDialog when calling it from another one.
I have one jDialog called Cargando1 which has a ProgressBar inside,this jDialog runs a method called iterate() when loading.
Otherwise i have another jDialog called login1, it has a button called btnIngresar, it validates some user and password stuff and then it should call Cargando1.
Also cargando1 calls a Frame called Principal after the progressbar has reach 100% but it doesn't matter.
I would like to know why when i called Cargando1 from Login1 it runs but i can't see the components on it.
Thank you for helping me!
This is the Jdialog called Login1
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Login1 extends JDialog implements ActionListener {
private JLabel lblUsuario;
private JTextField txtUsuario;
private JPasswordField jpassContrasena;
private JLabel lblContrasena;
private JButton btnIngresar;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
Login1 dialog = new Login1();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public Login1() {
setBounds(100, 100, 225, 157);
getContentPane().setLayout(null);
lblUsuario = new JLabel("Usuario:");
lblUsuario.setFont(new Font("Courier New", Font.PLAIN, 11));
lblUsuario.setBounds(10, 12, 80, 20);
getContentPane().add(lblUsuario);
txtUsuario = new JTextField();
txtUsuario.setColumns(10);
txtUsuario.setBounds(101, 11, 95, 20);
getContentPane().add(txtUsuario);
jpassContrasena = new JPasswordField();
jpassContrasena.setBounds(101, 43, 95, 20);
getContentPane().add(jpassContrasena);
lblContrasena = new JLabel("Contrase\u00F1a:");
lblContrasena.setFont(new Font("Courier New", Font.PLAIN, 11));
lblContrasena.setBounds(10, 44, 80, 20);
getContentPane().add(lblContrasena);
btnIngresar = new JButton("Ingresar");
btnIngresar.addActionListener(this);
btnIngresar.setBounds(60, 80, 90, 23);
getContentPane().add(btnIngresar);
}
public void actionPerformed(ActionEvent arg0) {
if (arg0.getSource() == btnIngresar) {
actionPerformedBtnIngresar(arg0);
}
}
protected void actionPerformedBtnIngresar(ActionEvent arg0) {
char contrasena[] = jpassContrasena.getPassword();
String contrasenadef = new String(contrasena);
if (txtUsuario.getText().equals("Administrador") && contrasenadef.equals("admin"))
{ Principal.sesion = 'A';
JOptionPane.showMessageDialog(this, "Bienvenido, administrador", "Mensaje de bienvenida", JOptionPane.INFORMATION_MESSAGE);
Cargando1 dialog = new Cargando1();
this.dispose();
dialog.setVisible(true);
dialog.iterate();
}
else if (txtUsuario.getText().equals("Vendedor") && contrasenadef.equals("vendedor"))
{ Principal.sesion = 'V';
JOptionPane.showMessageDialog(this, "Bienvenido, vendedor", "Mensaje de bienvenida", JOptionPane.INFORMATION_MESSAGE);
Cargando1 dialog = new Cargando1();
this.dispose();
dialog.setVisible(true);
dialog.iterate();
}
else
{ JOptionPane.showMessageDialog(null, "Por favor ingrese un usuario y/o contraseƱa correctos", "Acceso denegado", JOptionPane.ERROR_MESSAGE);
}
}
}
This is the JDialog called cargando1
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JProgressBar;
public class Cargando1 extends JDialog {
private final JPanel contentPanel = new JPanel();
private JProgressBar pgbCargando;
int porcentaje=0;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
Cargando1 dialog = new Cargando1();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.iterate();
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public Cargando1() {
setBounds(100, 100, 450, 154);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
pgbCargando = new JProgressBar(0,2000);
pgbCargando.setBounds(10, 11, 414, 93);
pgbCargando.setStringPainted(true);
contentPanel.add(pgbCargando);
setLocationRelativeTo(null);
setVisible(true);
setResizable(true);
setContentPane(contentPanel);
}
void iterate() {
while (porcentaje < 2000)
{ pgbCargando.setValue(porcentaje);
try {Thread.sleep(100);}
catch (InterruptedException e) { }
porcentaje += 95;
}
Principal formulario1 = new Principal();
formulario1.setLocationRelativeTo(null);
this.dispose();
formulario1.setVisible(true);
}
}
The problem is in the iterate() method. Change your iterate() method to the following and give it a try.
void iterate() {
final Thread t = new Thread(new Runnable() {
#Override
public void run() {
while (porcentaje < 2000) {
pgbCargando.setValue(porcentaje);
try {
Thread.sleep(100);
} catch (final InterruptedException e) {
}
porcentaje += 95;
}
}
});
t.setDaemon(true);
t.start();
}
This will free up the main thread to do gui updates while the ProgressBar's value is modified in the background.
Two things to fix(and a note for the future):
Use Cargando1.setVisible(true) in Cargando1
DO NOT use Thread.sleep for swing, because javax.swing is not thread-safe. Your JDialog will freeze if you use Thread.sleep. Rather, use a Timer(javax.swing) with an ActionListener, or if you really want to use Thread.sleep, look into multithreading.
3. please indent better!!!! usually a new line with an extra 4 spaces after every {