Closing JFrame with Button - java

I am currently using Eclipse's drag and Drop feature, I have one application window which comes with JFrame by default and is able to setVisible(false); but my other frames/panel/window I have created with JPanel and with extending JFrame.
Because of extend I am unable to setVisible(false or true); it has no effect at all on the window it still remains true.
My code :
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
LibrarianMenu frame = new LibrarianMenu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public LibrarianMenu() {
setTitle("Librarian");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 385, 230);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
.
.
. so on
Here I am trying to execute my button:
btnLogout.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
LibrarianMenu frame = new LibrarianMenu();
frame.setVisible(false);
}
});
Any solutions for it?

Because you're creating the frame inside the Runnable, its scope is limited to that of the runnable. Try declaring the variable outside of the runnable, then initializing it within the runnable, like so:
private JPanel contentPane;
private LibrarianMenu frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new LibrarianMenu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Then setvisible to false without declaring a new instance of LibrarianMenu:
btnLogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
}
});

This is happening because every time you press the button you create a new instance of that frame. Here is your code updated :
static LibrarianMenu frame ;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new LibrarianMenu();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
And the logout button event should be like this :
btnLogout.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
}
});

Related

Why is Plot2DPanel not reacting to its MouseListener's click event?

I learned recently how to switch between Jpanels in CardLayout.
The code works fine but when I attempt to change one of jPanels to Plot2DPanel I get a strange behaviour at runtime. The Plot2DPanel isn't picking up its mouse click events. What have I done wrong? (I assume that is not a bug in jmathplot).
Here's the code:
public class Window {
private JFrame frame;
private JPanel cards;
private JPanel panelOne;
private Plot2DPanel panelTwo;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window window = new Window();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Window() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 790, 483);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cards = new JPanel();
cards.setLayout(new CardLayout());
panelOne = new JPanel();
panelOne.setBackground(Color.BLACK);
panelOne.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e){
java.awt.Toolkit.getDefaultToolkit().beep(); //debug beep
CardLayout cl = (CardLayout) cards.getLayout();
cl.next(cards);
}
});
panelTwo = new Plot2DPanel();
panelTwo.setBackground(Color.WHITE);
panelTwo.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e){
java.awt.Toolkit.getDefaultToolkit().beep(); //debug beep
CardLayout cl = (CardLayout) cards.getLayout();
cl.next(cards);
}
});
cards.add(panelOne, "panel1");
cards.add(panelTwo, "panel2");
frame.getContentPane().add(cards);
}
}

java - method and passing variable from jInternalFrame to jFrame

and I have the following problem.
i am new in java and i am trying to send a variable which is user_id, from JInternalFrame to JFrame.
I can't use constructor because JFrame is the main program activated at startup and containing jDesktoPane
so i was trying to use the methods, however, can't do it (i posted the two methods, both of which I tried but did not work)
Method A)
Code in jFrame (Main_window)
public javax.swing.JTextField getID() {
return jTextField_id;
}
public void setID(javax.swing.JTextField ID)
{
jTextField_id = ID;
}
code in jInternalFrame
Main_window send = new Main_window();
send.getID().setText("123");
Method B)
Code in jFrame (Main_window)
USER_ID is a variable accesible in any place of jFrame
public void setID(String ID)
{
USER_ID = ID;
}
code in jInternalFrame
Main_window send = new Main_window();
send.setID("123");
both method don't change anything but have no errors in compilation
if there is any other way of doing it pls tell me :)
sorry for my language and grammar.
if this help i use Eclipse compilator
this code worked for me, ty for help
public void set_ID(String ID)
{
Test_JF mainWindow = (Test_JF) this.getTopLevelAncestor();;
mainWindow.setID(ID);
}
activated by set_ID("1234");
Try this in your JInternalFrame class:
JFrame mainWindow = (JFrame)this.getTopLevelAncestor();
mainWindow.setID("123");
ok so here is smaller version of my program
"Test_JF" is a main JFrame and "Test_JIF" is a JInternalFrame
here is TestJF
public class Test_JF extends JFrame {
private JPanel contentPane;
private JTextField user_id;
String USER_ID;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test_JF frame = new Test_JF();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Test_JF() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 750, 500);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
user_id = new JTextField();
user_id.setBounds(338, 11, 86, 20);
contentPane.add(user_id);
user_id.setColumns(10);
JButton button_user_id = new JButton("fill user id");
button_user_id.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
user_id.setText(USER_ID);
}
});
button_user_id.setBounds(239, 10, 89, 23);
contentPane.add(button_user_id);
JDesktopPane desktopPane = new JDesktopPane();
desktopPane.setBounds(10, 56, 714, 395);
contentPane.add(desktopPane);
addWindowListener(new WindowAdapter() {
#Override
public void windowOpened(WindowEvent arg0) {
Test_JIF Open = new Test_JIF();
desktopPane.add(Open);
Open.show();
}
});
}
public void setID(String ID)
{
USER_ID = ID;
}}
here is TestJIF
public class Test_JIF extends JInternalFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test_JIF frame = new Test_JIF();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Test_JIF() {
Test_JF mainWindow = (Test_JF)this.getTopLevelAncestor();
setBounds(100, 100, 328, 199);
getContentPane().setLayout(null);
JButton button_send = new JButton("New button");
button_send.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mainWindow.setID("123");
}
});
button_send.setBounds(111, 73, 89, 23);
getContentPane().add(button_send);
}}
i clear imports here(on web) so it will be cleaner

how to call this code from gui(jframe)

i wanna to call youtubeviewer from a window by actionlistener
public class YouTubeViewer {
public YouTubeViewer(){
NativeInterface.open();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("YouTube Viewer");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(getBrowserPanel(), BorderLayout.CENTER);
frame.setSize(800, 600);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
});
NativeInterface.runEventPump();
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
#Override
public void run() {
NativeInterface.close();
}
}));
}
public JPanel getBrowserPanel() {
JPanel webBrowserPanel = new JPanel(new BorderLayout());
JWebBrowser webBrowser = new JWebBrowser();
webBrowserPanel.add(webBrowser, BorderLayout.CENTER);
webBrowser.setBarsVisible(false);
webBrowser.navigate("www.youtube.com/embed/sKeCX98U29M");
return webBrowserPanel;
}
}
jframe example(for testing)
public class trailerPlayer extends JPanel implements ActionListener
{
private JButton press;
public trailerPlayer ()
{
setLayout(new BorderLayout());
press = new JButton("press");
press.addActionListener(this);
add(press);
}
public void actionPerformed(ActionEvent actionEvent)
{
YouTubeViewer a = new YouTubeViewer();
}
public static void main(String args[ ])
{
trailerPlayer p = new trailerPlayer();
JFrame test = new JFrame();
test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test.add(p);
test.setSize(500,500);
test.setVisible(true);
}
}
YouTubeViewer include class of DJ Native Swing api library.
if i call directly by main function,it will work.but if i call from actionlistener it will stop responding at the time i press it~ i guess it is the problem of running issue~ how to solve ? any idea? thanks
any idea??
Your code blocks the EDT (NativeInterface.runEventPump();). So you should do it in a different thread.
public void actionPerformed(ActionEvent actionEvent)
{
Thread t = new Thread(new Runnable() {
public void run() {
YouTubeViewer a = new YouTubeViewer();
}
});
t.start();
}

Java: WindowAdapter windowClosed method not running

I'm currently running this in a class that extends a JFrame. When I close the window, I don't see RAN EVENT HANDLER in the console. This is not the main window, and more than one instance of this window can exist at the same time.
this.addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent e) {
System.out.println("RAN EVENT HANDLER");
}
});
This method is inside a method called initialiseEventHandlers() which is called in the constructor, so I'm sure the code is running.
What am I doing wrong?
Thank you!
EDIT: Here's the full (summarised) code:
public class RacesWindow extends JFrame {
private JPanel mainPanel;
private JLabel lblRaceName;
private JTable races;
private DefaultTableModel racesModel;
public RacesWindow() {
this.lblRaceName = new JLabel("<html><strong>Race: " + race.toString()
+ "</strong></html>");
initialiseComponents();
this.setMinimumSize(new Dimension(500, 300));
this.setMaximumSize(new Dimension(500, 300));
initialiseEventHandlers();
formatWindow();
pack();
setVisible(true);
}
public void initialiseComponents() {
mainPanel = new JPanel(new BorderLayout());
races = new JTable();
racesModel = new DefaultTableModel();
races.setModel(racesModel);
}
public void initialiseEventHandlers() {
System.out.println("EVENTHANDLER CODE IS CALLED"); //for debugging
this.addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent e) {
System.out.println("RAN EVENT HANDLER");
appManager.removeOpenWindow(race.toString());
}
});
}}
public void formatWindow() {
mainPanel.add(lblRaceName, BorderLayout.NORTH);
mainPanel.add(new JScrollPane(races), BorderLayout.CENTER);
mainPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
this.add(mainPanel);
}
}
I found out I was using the wrong method: windowClosed(). I should use windowClosing()!
This should work
this.addWindowListener(new WindowListener() {
#Override
public void windowClosed(WindowEvent e) {
System.out.println("RAN EVENT HANDLER");
}
});
Add this to your constructor.
setDefaultCloseOperation(EXIT_ON_CLOSE);
The code below worked for me.
// parent class {
// constructor {
...
this.addWindowListener(new GUIFrameListener());
...
}
class GUIFrameListener extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.out.println("Window Closed");
}
}
} // end of parent class

changing color of the JLABEL with a link

how can i change the color of a JLABEL with a link in java?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class XXX extends JFrame {
XXX(){
final JLabel lab1=new JLabel("Username:");
final JTextField text1=new JTextField(20);
lab1.setBounds(20,140,65,20);
text1.setBounds(85,141,185,20);
add(lab1);
add(text1);
lab1.setForeground(Color.white);
final JLabel lab2=new JLabel("Password:");
final JPasswordField text2=new JPasswordField(20);
lab2.setBounds(20,165,65,20);
text2.setBounds(85,166,185,20);
add(lab2);
add(text2);
lab2.setForeground(Color.white);
final JButton a=new JButton("Sign In");
a.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//Code
}
});
a.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent me) {
a.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
public void mouseExited(MouseEvent me) {
a.setCursor(Cursor.getDefaultCursor());
}
public void mouseClicked(MouseEvent me)
{
a.setEnabled(false);
text1.setEditable(false);
text2.setEditable(false);
try {
}
catch(Exception e) {
System.out.println(e);
}
}
});
a.setBounds(85,192,80,20);
add(a);
final String strURL = "http://www.yahoo.com";
final JLabel lab3 = new JLabel("<html>Register</html>");
lab3.setBounds(170,192,52,20);
add(lab3);
lab3.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent me) {
lab3.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
public void mouseExited(MouseEvent me) {
lab3.setCursor(Cursor.getDefaultCursor());
}
public void mouseClicked(MouseEvent me)
{
text2.setEditable(false);
try {
}
catch(Exception e) {
System.out.println(e);
}
}
});
final JLabel map = new JLabel(new ImageIcon(getClass().getResource("XXXBG.png")));
map.setBounds(0,0,300,250);
add(map);
setTitle("XXX");
setSize(300,250);
setResizable(false);
setCursor(DEFAULT_CURSOR);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(8, 8);
setLayout(null);
toFront();
setVisible(true);
}
public static void main(String[] args)
{
new XXX();
}
}
as you can see, i cant change the foreground color of JLABEL lab3.
if posible, i want also to change color of border-like of the jframe.
anyone can help?
Yes, it's possible. Simple supply the foreground color you want to use...
lab3.setForeground(Color.BLUE);
You also don't need the mouse listener. Simply using lab3.setCursor(new Cursor(Cursor.HAND_CURSOR)); will change the mouse cursor automatically when the mouse is moved over the label for you...magically :D
Updated
public class TestLabel01 {
public static void main(String[] args) {
new TestLabel01();
}
public TestLabel01() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JLabel link = new JLabel("Linked in");
link.setForeground(Color.BLUE);
link.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(link);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}

Categories

Resources