This is a tutorial example and pnl.add(field); pnl.add(txtArea); not compiling. Why not?
import javax.swing.*;
import java.awt.event.*;
class KeyStrokes extends JFrame implements KeyListener {
JPanel pnl = new JPanel();
public static void main (String[] args) {
KeyStrokes gui = new KeyStrokes();
}
JTextField field = new JTextField(38);
JTextArea txtArea = new JTextArea(5, 38);
pnl.add(field);
pnl.add(txtArea);
public KeyStrokes() {
super("Swing Window");
setSize(500, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(pnl);
setVisible(true);
field.addKeyListener(this);
}
public void keyPressed (KeyEvent event){
txtArea.setText("Key Pressed");
}
public void keyTyped(KeyEvent event){
txtArea.append("\nCharacter :" + event.getKeyChar());
}
public void keyReleased (KeyEvent event){
int keyCode = event.getKeyCode();
txtArea.append("\nKey Code :" + event.getKeyText(keyCode));
}
}
That's because you can not make those statements outside of a method, note that you can declare variables in the global scope you are in. Move it to the KeyStrokes() method, just before the setVisible(true) statement. And then KeyStrokes() would be something like this:
public KeyStrokes() {
super("Swing Window");
setSize(500, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(pnl);
pnl.add(field);
pnl.add(txtArea);
setVisible(true);
field.addKeyListener(this);
}
Related
I am trying to get the mouse coordinates display in the panel but each time I move the cursor the message and new coordinates are being displayed on the previous one.I am using MouseMotionListener with JPanel. I can't figure out the problem.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.event.MouseMotionListener;
public class Main extends JPanel implements MouseMotionListener {
public JLabel label;
public static void main(String[] args) {
new Main();
JFrame frame = new JFrame();
frame.setTitle("MouseCoordinates");
frame.setSize(400, 400);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
Container contentPane = frame.getContentPane();
contentPane.add(new Main());
frame.setVisible(true);
}
public Main() {
setSize(400, 400);
label = new JLabel("No Mouse Event Captured", JLabel.CENTER);
add(label);
addMouseMotionListener(this);
}
public void mouseMoved(MouseEvent e) {
label.setText("Mouse Cursor Coordinates => X:" + e.getX() + " |Y:" + e.getY());
}
public void mouseDragged(MouseEvent e) {}
}
You're creating Main twice.
public class Main extends JPanel implements MouseMotionListener {
public JLabel label;
public static void main(String[] args) {
Main m = new Main();// create an object and reference it
JFrame frame = new JFrame();
frame.setTitle("MouseCoordinates");
frame.setSize(400, 400);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
Container contentPane = frame.getContentPane();
contentPane.add(m);
frame.setVisible(true);
}
//...
your problem was creating the Main object twice (which is a jpanel) and then the writing appeared twice. if you give the Main object a reference, then your problem should be fixed.
I am making my first game, and the last time I asked this question, I kinda didn't explain it very well. Basically, below is the opening screen of the game. I know, not very good, but it is just a rough draft. Then I also built the game.
There are two buttons in the opening screen, for it is a 2 player game. Both players must click ready, and then I want to program to end, and to start the second program. However I'm not sure how to do that.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class OpeningScreen {
JFrame frame;
JPanel main;
JButton ready1;
JButton ready2;
JPanel bottom;
JLabel label;
public OpeningScreen(){
UIManager.put("Button.background", Color.cyan);
UIManager.put("Button.foreground", Color.magenta);
UIManager.put("ToolTip.background", Color.magenta);
frame=new JFrame("Super Tuesday");
main=new JPanel();
ready1=new JButton("CLICK IF READY");
ready2=new JButton("CLICK IF READY");
label=new JLabel("SUPER TUESDAY");
bottom=new JPanel();
label.setFont(label.getFont().deriveFont(50.0f));
frame.setSize(480, 800);
frame.setLayout(new BorderLayout());
frame.add(main, BorderLayout.CENTER);
bottom.setLayout(new BorderLayout());
ready1.setToolTipText("CLICK ME TO START THE GAME");
ready2.setToolTipText("CLICK ME TO START THE GAME");
main.setBackground(Color.gray);
label.setForeground(Color.white);
ready1.setFont(ready1.getFont().deriveFont(20.0f));
ready2.setFont(ready2.getFont().deriveFont(20.0f));
ready1.setForeground(Color.pink);
ready2.setForeground(Color.pink);
ready1.setPreferredSize(new Dimension(240,150 ));
ready2.setPreferredSize(new Dimension(240, 150));
bottom.setPreferredSize(new Dimension(600, 150));
main.setLayout(new FlowLayout());
main.add(label, BorderLayout.NORTH);
frame.add(bottom, BorderLayout.SOUTH);
bottom.add(ready1, BorderLayout.WEST);
bottom.add(ready2, BorderLayout.EAST);
MyMouseManager1 mmm1=new MyMouseManager1();
MyMouseManager2 mmm2=new MyMouseManager2();
ready1.addMouseListener(mmm1);
ready2.addMouseListener(mmm2);
frame.setVisible(true);
}
class MyMouseManager1 implements MouseListener{
public void mouseClicked(MouseEvent e) {
ready1.setBackground(Color.green);
ready1.setForeground(Color.white);
ready1.setText("READY!");
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
}
class MyMouseManager2 implements MouseListener{
public void mouseClicked(MouseEvent e) {
ready2.setBackground(Color.green);
ready2.setForeground(Color.white);
ready2.setText("READY!");
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
}
}
public static void main(String[] args){
OpeningScreen smartie=new OpeningScreen();
}
}
Here is the second program. Please don't copy. heh.
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.applet.Applet;
public class Clickasfastasyoucan extends java.applet.Applet{
private JFrame w;
private JPanel b;
private Button p;
private JPanel d;
private int times;
private JLabel number;
JPanel n;
JFrame x;
public Clickasfastasyoucan() {
x=new JFrame(" ");
n=new JPanel();
times=0;
number=new JLabel("How fast can you click?");
w = new JFrame("My Smart Button");
w.setSize(1500, 1000);
b = new JPanel();
p = new Button("Swipe as fast as you can");
w.setSize(500, 500);
b.setPreferredSize(new Dimension(1000,1500));
d=new JPanel();
w.add(b);
b.add(p);
b.setLayout(new GridLayout(1, 1));
b.add(number, BorderLayout.CENTER);
d.setSize(500, 500);
MyMouseManager mmm = new MyMouseManager();
p.addMouseListener(mmm);
p.addMouseMotionListener(mmm);
p.setForeground(Color.white);
p.setBackground(Color.black);
p.setFont(p.getFont().deriveFont(20.0f));
p.setFont(p.getFont().deriveFont(20.0f));
b.setSize(600, 600);
w.setVisible(true);
}
class MyMouseManager implements MouseListener, MouseMotionListener {
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
n.setBackground(Color.blue);
x.add(n);
x.setSize(500, 500);
n.setSize(500, 500);
x.setVisible(true);
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
n.setBackground(Color.blue);
}
public void mouseExited(MouseEvent e) {
n.setBackground(Color.white);
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {times++;
number.setFont(number.getFont().deriveFont(100.0f));
number.setText(" "+times+" ");
if (times>=100&×<999){
b.setBackground(Color.red);
number.setFont(number.getFont().deriveFont(80.0f));
times=times+1;
}
if(times>=1000&×<10000){
b.setBackground(Color.green);
number.setFont(number.getFont().deriveFont(70.0f));
times=times+4;
}
if(times>=10000&×<50000){
b.setBackground(Color.yellow);
number.setFont(number.getFont().deriveFont(70.0f));
times=times+100;
}if(times>=50000&×<500000){
b.setBackground(Color.blue);
number.setFont(number.getFont().deriveFont(70.0f));
times=times+500;
}
if(times>=500000&×<4999999){
b.setBackground(Color.pink);
number.setFont(number.getFont().deriveFont(40.0f));
times=times+1000;
}
if(times>=5000000){
b.setBackground(Color.orange);
number.setFont(number.getFont().deriveFont(20.0f));
number.setText("WOW! YOU WON. CHECK THE OUTPUT TO SEE HOW YOU SCORED!");
System.out.println("1 day: Are you still there?");
System.out.println("24 hour: Snail speed");
System.out.println("15 hours: Fail");
System.out.println("5 hours: Slow Fingers");
System.out.println("1 hour: Fast Fingers");
System.out.println("30 minutes: Champion");
System.out.println("15 minutes: You beat me!");
System.out.println("2 minutes: Cheater");
System.out.println("1 minute: Speed of Light");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("___________________________-");
}
}
}
public static void main(String[] args) {
Clickasfastasyoucan clickgame= new Clickasfastasyoucan();
}
}
I want this one to replace the first program. I'm not sure how to even start with this though, since this is my first attempt at any game, or anything beyond a one class program.
No, you really don't want a java.awt.Applet to replace a JFrame, trust me. They're both used in two vastly different situations, and while the Swing library that underlies JFrames is about 4 years out of date, the AWT library that underlies java.awt.Applet is about 20 years out of date. Just stay clear of Applet.
Instead your GUI classes should be geared towards creating JPanels, which can then be placed into JFrames or JDialogs, or JTabbedPanes, or swapped via CardLayouts, wherever needed. This will greatly increase the flexibility of your GUI coding, and in fact this is what I recommend -- that you swap views via a CardLayout.
Also -- don't use MouseListeners for your JButton listeners but instead use ActionListeners. MouseListeners won't respond to space bar presses, won't be disabled if the button becomes disabled, and can be capricious if you base behavior on the mouseClicked method. Use the proper tool for the job: ActionListeners, or even better, Actions.
For example:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.geom.AffineTransform;
import javax.swing.*;
public class MainGui extends JPanel {
private CardLayout cardLayout = new CardLayout();
private StartUpPanel startUpPanel = new StartUpPanel(this);
private GamePanel gamePanel = new GamePanel(this);
public MainGui() {
setLayout(cardLayout);
add(startUpPanel, startUpPanel.getName());
add(gamePanel, gamePanel.getName());
}
public void nextCard() {
cardLayout.next(this);
}
private static void createAndShowGui() {
MainGui mainPanel = new MainGui();
JFrame frame = new JFrame("MainGui");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class StartUpPanel extends JPanel {
public static final String CLICK_IF_READY = "Click If Ready";
public static String SUPER_TUESDAY = "SUPER TUESDAY";
public static final String READY = "READY";
public static final int MAX_READY = 2;
private static final float TITLE_FONT_POINTS = 40f;
public static final String START_UP_PANEL = "Startup Panel";
private static final int PREF_W = 600;
private static final int PREF_H = PREF_W;
private int readyCount = 0;
private MainGui mainGui;
public StartUpPanel(MainGui mainGui) {
this.mainGui = mainGui;
setName(START_UP_PANEL);
JLabel titleLabel = new JLabel(SUPER_TUESDAY, SwingConstants.CENTER);
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, TITLE_FONT_POINTS));
JButton button1 = new JButton(new StartupAction());
JButton button2 = new JButton(new StartupAction());
button1.setFont(button1.getFont().deriveFont(Font.BOLD, TITLE_FONT_POINTS));
button2.setFont(button1.getFont());
JPanel southPanel = new JPanel(new GridLayout(1, 0));
southPanel.add(button1);
southPanel.add(button2);
setLayout(new BorderLayout());
add(titleLabel, BorderLayout.CENTER);
add(southPanel, BorderLayout.PAGE_END);
}
#Override
public Dimension getPreferredSize() {
Dimension superSize = super.getPreferredSize();
if (isPreferredSizeSet()) {
return superSize;
}
int prefW = Math.max(superSize.width, PREF_W);
int prefH = Math.max(superSize.height, PREF_H);
return new Dimension(prefW, prefH);
}
private class StartupAction extends AbstractAction {
public StartupAction() {
super(CLICK_IF_READY);
}
#Override
public void actionPerformed(ActionEvent e) {
if (getValue(NAME).equals(CLICK_IF_READY)) { // check if button active
putValue(NAME, READY); // swap button's name
((AbstractButton) e.getSource()).setFocusable(false); // lose focus
readyCount++; // increment ready count.
if (readyCount >= MAX_READY) { // if all buttons pushed
mainGui.nextCard(); // tell main GUI to swap cards
}
}
}
}
}
// simple mock class to represent the game
class GamePanel extends JPanel {
public static final String GAME = "Game";
private static final float FONT_POINTS = 30F;
private MainGui mainGui;
public GamePanel(MainGui mainGui) {
this.mainGui = mainGui;
setName(GAME);
JLabel label = new JLabel(GAME, SwingConstants.CENTER);
label.setFont(label.getFont().deriveFont(Font.BOLD, FONT_POINTS));
setLayout(new GridBagLayout());
add(label);
}
}
I want to increase the value of my counter to 10 when I click on a button.
It works so far, but I don't know how to get the new counted value globally to
use it in other methods.
Here is a simple code:
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
public class Test {
public JTextPane textpane=new JTextPane();
public JPanel panel;
public JButton button = new JButton("count!");
public static int counter=10;
Test() {
addListener();
panel = new JPanel(new BorderLayout());
panel.add(textpane, BorderLayout.CENTER);
panel.add(button, BorderLayout.SOUTH);
createFrame();
}
private void addListener() {
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
counter=counter+10;
textpane.setText("counter is set to -> "+counter);
}
});
System.out.println("new value >> "+counter);
}
private void createFrame() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setSize(400, 200);
frame.setVisible(true);
}
public static void main(String[] args) { new Test(); }
}
How can I get the new counter value globally?
When I pressed the ENTER my JTextArea starts a new row and I only want do to the doClick() method nothing else.
How should I do that?
textarea.addKeyListener(new KeyListener(){
#Override
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_ENTER){
button.doClick();
}
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
});
Use .consume():
Consumes this event so that it will not be processed in the default
manner by the source which originated it.
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_ENTER){
e.consume();
button.doClick();
}
}
Documentation
You should use KeyBindings with any JTextComponent in question. KeyListeners are way too low level from Swing's perspective. You are using the concept which was related to AWT, Swing uses KeyBindings to do the same task with more efficiency and provides desired results :-)
A small program for your help :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class KeyBindingExample {
private static final String key = "ENTER";
private KeyStroke keyStroke;
private JButton button;
private JTextArea textArea;
private Action wrapper = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent ae) {
button.doClick();
}
};
private void displayGUI() {
JFrame frame = new JFrame("Key Binding Example");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel contentPane = new JPanel(new BorderLayout(5, 5));
textArea = new JTextArea(10, 10);
keyStroke = KeyStroke.getKeyStroke(key);
Object actionKey = textArea.getInputMap(
JComponent.WHEN_FOCUSED).get(keyStroke);
textArea.getActionMap().put(actionKey, wrapper);
button = new JButton("Click Me!");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
System.out.format("Button Clicked :-)%n");
}
});
contentPane.add(textArea, BorderLayout.CENTER);
contentPane.add(button, BorderLayout.PAGE_END);
frame.setContentPane(contentPane);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
new KeyBindingExample().displayGUI();
}
};
EventQueue.invokeLater(r);
}
}
i'm developing a JFrame which has a button to show another JFrame. On the second JFrame i want to override WindowsClosing event to hide this frame but not close all the application. So i do like this:
On second JFrame
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
private void formWindowClosing(java.awt.event.WindowEvent evt) {
this.dispose();
}
but application still close when i click x button on the windows. why? can you help me?
I can't use
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
because i need to show again that JFrame with some information added in it during operations from first JFrame. So i init second JFrame with attribute visible false. if i use dispose i lose the information added in a second moment by the other JFrame. so i use
private void formWindowClosing(java.awt.event.WindowEvent evt) {
this.setVisible(false);
}
but it still continue to terminate my entire app.
don't create a new JFrame, for new container use JDialog, if you want to hide the JFrame then better would be override proper e.g DefaultCloseOperations(JFrame.HIDE_ON_CLOSE), method JFrame.EXIT_ON_CLOSE teminating current JVM instance simlair as calll for System.exit(int)
EDIT
but it still continue to terminate my entire app.
1) then there must be another issue, your code maybe call another JFrame or formWindowClosing <> WindowClosing, use implemented method from API
public void windowClosing(WindowEvent e) {
2) I'b preferred DefaultCloseOperations(JFrame.HIDE_ON_CLOSE),
3) use JDialog instead of JFrame
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ClosingFrame extends JFrame {
private JMenuBar MenuBar = new JMenuBar();
private static JFrame frame = new JFrame();
private static JFrame frame1 = new JFrame("DefaultCloseOperation(JFrame.HIDE_ON_CLOSE)");
private static final long serialVersionUID = 1L;
private JMenu File = new JMenu("File");
private JMenuItem Exit = new JMenuItem("Exit");
public ClosingFrame() {
File.add(Exit);
MenuBar.add(File);
Exit.addActionListener(new ExitListener());
WindowListener exitListener = new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
frame.setVisible(false);
/*int confirm = JOptionPane.showOptionDialog(frame,
"Are You Sure to Close this Application?",
"Exit Confirmation", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
if (confirm == JOptionPane.YES_OPTION) {
System.exit(1);
}*/
}
};
JButton btn = new JButton("Show second JFrame");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame1.setVisible(true);
}
});
frame.add(btn, BorderLayout.SOUTH);
frame.addWindowListener(exitListener);
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setJMenuBar(MenuBar);
frame.setPreferredSize(new Dimension(400, 300));
frame.setLocation(100, 100);
frame.pack();
frame.setVisible(true);
}
private class ExitListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
int confirm = JOptionPane.showOptionDialog(frame,
"Are You Sure to Close this Application?",
"Exit Confirmation", JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, null, null);
if (confirm == JOptionPane.YES_OPTION) {
System.exit(1);
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
ClosingFrame cf = new ClosingFrame();
JButton btn = new JButton("Show first JFrame");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.setVisible(true);
}
});
frame1.add(btn, BorderLayout.SOUTH);
frame1.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame1.setPreferredSize(new Dimension(400, 300));
frame1.setLocation(100, 400);
frame1.pack();
frame1.setVisible(true);
}
});
}
}
Adding a New Code with no WindowListener part as explained by #JBNizet, the very right thing. The default behaviour just hides the window, nothing is lost, you simply have to bring it back, every value inside it will remain as is, below is the sample program for further help :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TwoFrames
{
private SecondFrame secondFrame;
private int count = 0;
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("JFRAME 1");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
secondFrame = new SecondFrame();
secondFrame.createAndDisplayGUI();
secondFrame.tfield.setText("I will be same everytime.");
JPanel contentPane = new JPanel();
JButton showButton = new JButton("SHOW JFRAME 2");
showButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
secondFrame.tfield.setText(secondFrame.tfield.getText() + count);
count++;
if (!(secondFrame.isShowing()))
secondFrame.setVisible(true);
}
});
frame.add(contentPane, BorderLayout.CENTER);
frame.add(showButton, BorderLayout.PAGE_END);
frame.setSize(200, 200);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TwoFrames().createAndDisplayGUI();
}
});
}
}
class SecondFrame extends JFrame
{
private WindowAdapter windowAdapter;
public JTextField tfield;
public void createAndDisplayGUI()
{
setLocationByPlatform(true);
JPanel contentPane = new JPanel();
tfield = new JTextField(10);
addWindowListener(windowAdapter);
contentPane.add(tfield);
getContentPane().add(contentPane);
setSize(300, 300);
}
}
Is this what you want, try this code :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TwoFrames
{
private SecondFrame secondFrame;
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("JFRAME 1");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
secondFrame = new SecondFrame();
secondFrame.createAndDisplayGUI();
secondFrame.tfield.setText("I will be same everytime.");
JPanel contentPane = new JPanel();
JButton showButton = new JButton("SHOW JFRAME 2");
showButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (!(secondFrame.isShowing()))
secondFrame.setVisible(true);
}
});
frame.add(contentPane, BorderLayout.CENTER);
frame.add(showButton, BorderLayout.PAGE_END);
frame.setSize(200, 200);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TwoFrames().createAndDisplayGUI();
}
});
}
}
class SecondFrame extends JFrame
{
private WindowAdapter windowAdapter;
public JTextField tfield;
public void createAndDisplayGUI()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationByPlatform(true);
JPanel contentPane = new JPanel();
tfield = new JTextField(10);
windowAdapter = new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
}
};
addWindowListener(windowAdapter);
contentPane.add(tfield);
getContentPane().add(contentPane);
setSize(300, 300);
}
}
You could avoid the listener completely and use
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
Note that the default value is HIDE_ON_CLOSE, so the behavior you want should be the default behavior. Maybe you registered another listener that exits the application.
See http://docs.oracle.com/javase/6/docs/api/javax/swing/JFrame.html#setDefaultCloseOperation%28int%29
It's hard to pinpoint exactly why you are experiencing the behavior stated without seeing a little more of the set-up code, however it may be due to defaultCloseOperation set to EXIT_ON_CLOSE.
Here's a link to a demo displaying the properties you are looking for although the structure is a bit different. Have a look: http://docs.oracle.com/javase/tutorial/uiswing/examples/components/FrameworkProject/src/components/Framework.java