I am trying to set a new text into a button when you press on it. However it does not seem to work, I am doing something wrong, and I do not know what...
EDIT -----I attach the code for easier comprehension of what I mean
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GrowAndShrinkSquareGUItest {
JFrame frame;
SquareDrawPanel bigGreen;
SquareDrawPanel smallGreen;
JButton button;
growAndShrinkListener listener;
public class SquareDrawPanel extends JPanel {
int width;
int height;
SquareDrawPanel(int w, int h) {
width = w;
height = h;
}
public void paintComponent(Graphics g) {
g.setColor(Color.green);
g.fillRect(frame.getWidth() / 2 - (width / 2), frame.getHeight()
/ 2 - (height / 2) - 15, width, height);
}
}
public class growAndShrinkListener implements ActionListener {
// JButton button;
growAndShrinkListener(JButton button) {
button = new JButton("Click me to grow the Square");
frame.add(button, BorderLayout.NORTH);
button.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
button.setText("Unselect all");
}
}
public static void main(String[] args) {
GrowAndShrinkSquareGUItest test = new GrowAndShrinkSquareGUItest();
test.go();
}
private void createPanels() {
bigGreen = new SquareDrawPanel(400, 400);
smallGreen = new SquareDrawPanel(100, 100);
}
private void drawPanel(JPanel panel) {
frame.add(panel);
panel.setVisible(true);
frame.add(panel, BorderLayout.CENTER);
}
private void createListenerButton() {
listener = new growAndShrinkListener(button);
}
private void loop(){}
public void go() {
frame = new JFrame();
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createPanels();
drawPanel(smallGreen);
createListenerButton();
frame.setVisible(true);
}
}
It is because you use the button variable that is not defined in the scope of actionPerformed method. Java variables have scope and they are available inside curly braces where they're defined. The actionPerformed method is out of the curly braces of growAndShrinkListener method. The fixed code:
public class growAndShrinkListener implements ActionListener {
growAndShrinkListener(JButton button) {
button = new JButton("Click me to grow the Square");
frame.add(button, BorderLayout.NORTH);
button.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source instanceof JButton) {
button = (JButton) source;
button.setText("Click to shrink square");
}
}
}
Alternatively, you can use a private variable:
public class growAndShrinkListener implements ActionListener {
private JButton button;
growAndShrinkListener() {
button = new JButton("Click me to grow the Square");
frame.add(button, BorderLayout.NORTH);
button.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
button.setText("Click to shrink square");
}
}
Note: You should not overwrite the content of the argument in the constructor. The argument that you got is not a "pointer" to the callee's variable, but just a simple reference to that. If you overwrite, then the content will be lost for you and calle will not know that.
change like this..
public class YourSuperClass{
private JButton button;
public YourSuperClass(){
// your logics
button = new JButton();
button.addActionListener(new GrowAndShrinkListener(button));
frame.add(button, BorderLayout.NORTH);
}
class GrowAndShrinkListener implements ActionListener {
GrowAndShrinkListener(JButton button) {
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button){
button.setText("Click to shrink square");
}
}
}
}
Try This :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class frame extends JFrame
{
JButton b;
public frame()
{
setLayout(new BorderLayout());
b=new JButton("Press");
add(b,BorderLayout.SOUTH);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
b.setText("Clicked");
}
});
}
public static void main (String[] args) {
frame f=new frame();
f.setExtendedState(MAXIMIZED_BOTH);
f.setVisible(true);
}
}
Related
I'm trying to move around jframe on the window through an event triggered from an external jpanel class, my code is below, but the doesn't achieve this. Instead the panel is the one that's moving around.
What am I doing wrong here? I am new programming in general.
package casuls_app;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Titlebar extends JPanel {
public Titlebar() {
btnClose =new JButton("X");
btnClose.setFocusable(false);
btnClose.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
closeButtonPressed(e);
}
}
);
controlBox =new JPanel(new GridLayout(1,1));
controlBox.setPreferredSize(new Dimension(150,40));
controlBox.add(btnClose);
controlBox.setBackground(new Color(255,255,255));
setLayout(new BorderLayout());
add(controlBox,BorderLayout.EAST);
setPreferredSize(new Dimension(0,40));
setBackground(new Color(60, 173, 205));
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
mousePressedOnTitlebar(e);
}
}
);
addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
mouseDraggedOnTitlebar(e);
}
}
);
}
private void mousePressedOnTitlebar(MouseEvent e) {
posX= e.getX();
posY=e.getY();
}
private void mouseDraggedOnTitlebar(MouseEvent e) {
setLocation(e.getXOnScreen() -posX, e.getYOnScreen() -posY);
}
private void closeButtonPressed(ActionEvent e){
System.exit(0);
}
//Variables declaration
private int posX,posY;
private JButton btnClose;
private JPanel controlBox;
}
setLocation() sets the location of your JPanel (because your class extends JPanel).
If you have a reference to the JFrame, you can call the setLocation method on that object.
frame.setLocation(x, y);
If you don't have the reference, then you can follow this post which accesses the frame via SwingUtilities:
JFrame topFrame = (JFrame) SwingUtilities.getWindowAncestor(this);
I have a program that will make a JFrame with a JTextField. How do I get it to wait for text to be in the JTextField / the enter key is pressed?
public static void main(String[] args) {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int width = (int) screenSize.getWidth();
int height = (int) screenSize.getHeight();
JFrame frame = new JFrame();
frame.getContentPane().add(new Text());
JTextField field = new JTextField(10);
frame.add(field, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(width,height-55);
frame.setVisible(true);
// There is a keylistener here called listener. It was 100 lines. Did not want to copy
frame.addKeyListener(listener);
double x = 0;
x = Double.parseDouble(field.getText());
System.out.println(x);
I want
x = Double.parseDouble(field.getText());
to run only when someone types something in the JTextField in the JFrame.
Don't use a KeyListener
Add a DocumentListener to your JTextField's Document.
Inside of this listener check to see if the Document is empty or not.
If not empty, change the state of your program to allow the calculation, perhaps by enabling or disabling a JButton or Action.
For example:
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.Document;
public class DisbleButton extends JPanel {
private JTextField field = new JTextField(10);
private ButtonAction buttonAction = new ButtonAction();
private JButton button = new JButton(buttonAction);
public DisbleButton() {
add(field);
add(button);
buttonAction.setEnabled(false);
field.getDocument().addDocumentListener(new FieldDocListener());
}
private class FieldDocListener implements DocumentListener {
#Override
public void changedUpdate(DocumentEvent dEvt) {
testDoc(dEvt);
}
#Override
public void insertUpdate(DocumentEvent dEvt) {
testDoc(dEvt);
}
#Override
public void removeUpdate(DocumentEvent dEvt) {
testDoc(dEvt);
}
private void testDoc(DocumentEvent dEvt) {
Document doc = dEvt.getDocument();
buttonAction.setEnabled(doc.getLength() > 0);
}
}
private class ButtonAction extends AbstractAction {
public ButtonAction() {
super("Press Me");
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO do calculation here!
}
}
private static void createAndShowGui() {
DisbleButton mainPanel = new DisbleButton();
JFrame frame = new JFrame("DisbleButton");
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();
}
});
}
}
I have a program which at the moment I am trying to find the position of co-ordinates on the panel when clicked. So far I'm currently get 0,0. Any suggestions?
P.S - Sorry about the lack of comments...
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.lang.Math;
public class ShapePanel extends JPanel{
private JButton startButton, stopButton;
private JTextField textField;
private JLabel label;
private Timer timer;
private final int DELAY = 5;
ArrayList<Shape> obj = new ArrayList<Shape>();
public static void main(String[] args){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new ShapePanel());
frame.pack();
frame.setVisible(true);
}
public ShapePanel(){
DrawingPanel dpanel = new DrawingPanel();
JPanel cpanel = new JPanel();
startButton = new JButton("Start");
stopButton = new JButton("Stop");
cpanel.setLayout(new GridLayout(2,1));
cpanel.add(startButton);
cpanel.add(stopButton);
dpanel.addMouseListener(new MouseListen());
TimerListener tListen = new TimerListener();
startButton.addActionListener(tListen);
stopButton.addActionListener(tListen);
add(cpanel);
add(dpanel);
timer = new Timer(DELAY, tListen);
timer.start();
}
private class TimerListener implements ActionListener{
public void actionPerformed(ActionEvent e){
if (e.getSource() == timer){
for (int i = 0; i < obj.size(); i++){
obj.get(i).move();
}
}else if (e.getSource() == startButton){
timer.start();
}else if (e.getSource() == stopButton){
timer.stop();
}
repaint();
}
}
private class MouseListen implements MouseListener {
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
System.out.println(getX());
}
}
private class DrawingPanel extends JPanel{
DrawingPanel(){
setPreferredSize(new Dimension(400,400));
setBackground(Color.pink);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
for(int i = 0; i < obj.size(); i++){
obj.get(i).display(g);
}
}
}
}
Check the following portion of your code:
public void mouseClicked(MouseEvent e) {
System.out.println(getX());
// you are putting here only getX() which get the postion of panel
// put e.getX() instead
}
You need to implement the mouselistener correctly. The MouesEvent carries the position of the MouseClick.
public void mouseClicked(MouseEvent e) {
System.out.println(e.getPoint().x);
}
I want to thank Andrew Thompson for helping me get this far in the code.
How do I access each individual button's actionPerformed listener?
The code is supposed to move the "ball" on the screen based on the button you press.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Lab2a extends JFrame {
Lab2a(){
setTitle("Lab 1b - Application #2");
Lab2Panel p = new Lab2Panel();
add(p);
}
public static void main(String[] args){
Lab2 frame = new Lab2();
frame.setTitle("Lab2 Application # 1");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 400);
frame.setVisible(true);
}
}
class Lab2Panel extends JPanel{
Lab2Button canvas = new Lab2Button();
JPanel panel = new JPanel();
Lab2Panel () {
setLayout(new BorderLayout());
JButton leftButton = new JButton("left");
JButton rightButton = new JButton("right");
JButton upButton = new JButton("up");
JButton downButton = new JButton("down");
panel.add(leftButton);
panel.add(rightButton);
panel.add(upButton);
panel.add(downButton);
this.add(canvas, BorderLayout.CENTER);
this.add(panel, BorderLayout.SOUTH);
leftButton.addActionListener(new Lab2MoveBallListener(canvas));
rightButton.addActionListener(new Lab2MoveBallListener(canvas));
}
}
class Lab2Button extends JPanel {
int radius = 5;
int x = -1;
int y = -1;
protected void paintComponent(Graphics g){
if (x<0 || y<0) {
x = getWidth() / 2 - radius;
y = getHeight() / 2 - radius;
}
super.paintComponent(g);
g.drawOval(x,y, 2 * radius, 2 * radius);
}
public void moveLeft(){
x -= 5;
this.repaint();
}
public void moveRight(){
x += 5;
this.repaint();
}
public void moveUp(){
y += 5;
this.repaint();
}
public void moveDown(){
y -= 5;
this.repaint();
}
}
class Lab2MoveBallListener implements ActionListener{
private Lab2Button canvas;
Lab2MoveBallListener(Lab2Button canvas) {
this.canvas = canvas;
}
public void actionPerformed(ActionEvent e){
canvas.moveLeft();
}
}
Since you are using 1 action listener class with 2 buttons you will have to have a way to tell which button was pressed. You can try something like this in the actionPerformed method:
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().matches("left"))
System.out.print("left button pressed");
else if(e.getActionCommand().matches("right"))
System.out.print("right button pressed");
}
another way would be to do this is to create an anonymous class by doing this:
buttonLeft.addActionListener(new ActionListener(){
public void actionPerformed(){
//left button code
}
});
buttonRight.addActionListener(new ActionListener(){
public void actionPerformed(){
//right button code
}
});
In the ActionListener's actionPerformed(...) method, you can get the text of the button that's been pressed via the ActionEvent's getActionCommand() method.
Just test it to see the results:
public void actionPerformed(ActionEvent e){
String actionCommand = e.getActionCommand();
System.out.println("actionCommand is: " + actionCommand);
}
Now you can use this information inside of this method to do more than just write to the standard out, but I'll let you figure out the rest.
I have a button in a java frame that when pressed it reads a value from a text field and uses that string as a port name attempting to connect to a serial device.
If this connection is successful the method returns true if not it returns false. If it returns true I want the frame to disappear. A series of other frames specifed in other classes will then appear with options to control the serial device.
My problem is: the button is connected to an action listener, when pressed this method is invoked. If I try to use the frame.setVisible(true); method java throws a abstract button error because I'm effectively telling it to disappear the frame containing the button before the button press method has exited. Removing the frame.setVisible(true); allow the program to run correctly however I am left with a lingering connection frame that is no longer any use.
How to I get the frame to disappear upon pressing a the button?
package newimplementation1;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
*
* #author Zac
*/
public class ConnectionFrame extends JPanel implements ActionListener {
private JTextField textField;
private JFrame frame;
private JButton connectButton;
private final static String newline = "\n";
public ConnectionFrame(){
super(new GridBagLayout());
textField = new JTextField(14);
textField.addActionListener(this);
textField.setText("/dev/ttyUSB0");
connectButton = new JButton("Connect");
//Add Components to this panel.
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
add(textField, c);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
add(connectButton, c);
connectButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
boolean success = Main.mySerialTest.initialize(textField.getText());
if (success == false) {System.out.println("Could not connect"); return;}
frame.setVisible(false); // THIS DOES NOT WORK!!
JTextInputArea myInputArea = new JTextInputArea();
myInputArea.createAndShowGUI();
System.out.println("Connected");
}
});
}
public void actionPerformed(ActionEvent evt) {
// Unimplemented required for JPanel
}
public void createAndShowGUI() {
//Create and set up the window.
frame = new JFrame("Serial Port Query");
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
//Add contents to the window.
frame.add(new ConnectionFrame());
frame.setLocation(300, 0);
//Display the window.
frame.pack();
frame.setVisible(true);
frame.addComponentListener(new ComponentAdapter() {
#Override
public void componentHidden(ComponentEvent e) {
System.out.println("Exiting Gracefully");
Main.mySerialTest.close();
((JFrame)(e.getComponent())).dispose();
System.exit(0);
}
});
}
}
Running your snippet (after removing/tweaking around the custom classes), throws an NPE. Reason is that the frame you'r accessing is null. And that's because it's never set. Better not rely on any field, let the button find its toplevel ancestor and hide that, like in
public void actionPerformed(final ActionEvent e) {
boolean success = true;
if (success == false) {
System.out.println("Could not connect");
return;
}
Window frame = SwingUtilities.windowForComponent((Component) e
.getSource());
frame.setVisible(false); //no problem :-)
}
Your problem is with this line:
frame.add(new ConnectionFrame());
You're creating a new ConnectionFrame object, and so the frame that your button tries to close on is not the same as the one being displayed, and this is the source of your problem.
If you change it to,
//!! frame.add(new ConnectionFrame());
frame.add(this);
so that the two JFrames are one and the same, things may work more smoothly.
But having said that, your whole design smells bad and I'd rethink it in a more OOP and less static fashion. Also, use dialogs where dialogs are needed, not frames, and rather than dialogs consider swapping views (JPanels) via CardLayout as a better option still.
Myself, I'd create a "dumb" GUI for this, one that creates a JPanel (here in my example it extends a JPanel for simplicity, but I'd avoid extending if not necessary), and I'd let whoever is calling this code decide what to do with the information via some control. For e.g.,
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class ConnectionPanel extends JPanel {
private JTextField textField;
private JButton connectButton;
private ConnectionPanelControl control;
public ConnectionPanel(final ConnectionPanelControl control) {
super(new GridBagLayout());
this.control = control;
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (control != null) {
control.connectButtonAction();
}
}
};
textField = new JTextField(14);
textField.addActionListener(listener);
textField.setText("/dev/ttyUSB0");
connectButton = new JButton("Connect");
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.HORIZONTAL;
add(textField, c);
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0;
c.weighty = 1.0;
add(connectButton, c);
connectButton.addActionListener(listener);
}
public String getFieldText() {
return textField.getText();
}
}
Again, something outside of the simple GUI would make decisions on what to do with the text that the textfield contains and what to do with the GUI that is displaying this JPanel:
public interface ConnectionPanelControl {
void connectButtonAction();
}
Also, you will likely do any connecting in a background thread so as to not freeze your GUI, probably a SwingWorker. Perhaps something like this:
import java.awt.event.ActionEvent;
import java.util.concurrent.ExecutionException;
import javax.swing.*;
#SuppressWarnings("serial")
public class MyMain extends JPanel {
public MyMain() {
add(new JButton(new ConnectionAction("Connect", this)));
}
private static void createAndShowGui() {
JFrame frame = new JFrame("My Main");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MyMain());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class ConnectionAction extends AbstractAction {
private MyMain myMain;
private ConnectionPanel cPanel = null;
private JDialog dialog = null;
public ConnectionAction(String title, MyMain myMain) {
super(title);
this.myMain = myMain;
}
#Override
public void actionPerformed(ActionEvent e) {
if (dialog == null) {
dialog = new JDialog(SwingUtilities.getWindowAncestor(myMain));
dialog.setTitle("Connect");
dialog.setModal(true);
cPanel = new ConnectionPanel(new ConnectionPanelControl() {
#Override
public void connectButtonAction() {
final String connectStr = cPanel.getFieldText();
new MySwingWorker(connectStr).execute();
}
});
dialog.getContentPane().add(cPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
}
dialog.setVisible(true);
}
private class MySwingWorker extends SwingWorker<Boolean, Void> {
private String connectStr = "";
public MySwingWorker(String connectStr) {
this.connectStr = connectStr;
}
#Override
protected Boolean doInBackground() throws Exception {
// TODO: make connection and then return a result
// right now making true if any text in the field
if (!connectStr.isEmpty()) {
return true;
}
return false;
}
#Override
protected void done() {
try {
boolean result = get();
if (result) {
System.out.println("connection successful");
dialog.dispose();
} else {
System.out.println("connection not successful");
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
}
Your code would be much more readable if you named JFrame instances xxxFrame, and JPanel instances xxxPanel. Naming JPanel instances xxxFrame makes things very confusing.
It would also help if you pasted the stack trace of the exception.
I suspect the problem comes from the fact that frame is null. This is due to the fact that the frame field is only initialized in the createAndShowGUI method, but this method doesn't display the current connection panel, but a new one, which thus have a null frame field:
ConnectionFrame firstPanel = new ConnectionFrame();
// The firstPanel's frame field is null
firstPanel.createAndShowGUI();
// the firstPanel's frame field is now not null, but
// the above call opens a JFrame containing another, new ConnectionFrame,
// which has a null frame field
The code of createAndShowGUI should contain
frame.add(this);
rather than
frame.add(new ConnectionFrame());
for Swing GUI is better create only once JFrame and another Top-Level Containers would be JDialog or JWindow(un-decorated by default),
simple example here
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SuperConstructor extends JFrame {
private static final long serialVersionUID = 1L;
public SuperConstructor() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(300, 300));
setTitle("Super constructor");
Container cp = getContentPane();
JButton b = new JButton("Show dialog");
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
FirstDialog firstDialog = new FirstDialog(SuperConstructor.this);
}
});
cp.add(b, BorderLayout.SOUTH);
JButton bClose = new JButton("Close");
bClose.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
System.exit(0);
}
});
add(bClose, BorderLayout.NORTH);
pack();
setVisible(true);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
SuperConstructor superConstructor = new SuperConstructor();
}
});
}
private class FirstDialog extends JDialog {
private static final long serialVersionUID = 1L;
FirstDialog(final Frame parent) {
super(parent, "FirstDialog");
setPreferredSize(new Dimension(200, 200));
setLocationRelativeTo(parent);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setModalityType(Dialog.ModalityType.DOCUMENT_MODAL);
JButton bNext = new JButton("Show next dialog");
bNext.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
SecondDialog secondDialog = new SecondDialog(parent, false);
}
});
add(bNext, BorderLayout.NORTH);
JButton bClose = new JButton("Close");
bClose.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
setVisible(false);
}
});
add(bClose, BorderLayout.SOUTH);
pack();
setVisible(true);
}
}
private int i;
private class SecondDialog extends JDialog {
private static final long serialVersionUID = 1L;
SecondDialog(final Frame parent, boolean modal) {
//super(parent); // Makes this dialog unfocusable as long as FirstDialog is visible
setPreferredSize(new Dimension(200, 200));
setLocation(300, 50);
setModal(modal);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setTitle("SecondDialog " + (i++));
JButton bClose = new JButton("Close");
bClose.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
setVisible(false);
}
});
add(bClose, BorderLayout.SOUTH);
pack();
setVisible(true);
}
}
}
better would be re-use Top-Level Containers, as create lots of Top-Level Containers on Runtime (possible memory lack)