I got a java class called PleaseWait and want to call it whenever a heavy task is in progress. When my program does a heavy task, in the first row in my actionListener I set a variable of this class setVisible(true) then set setVisible(true) at the end of the actionListener.
Somehow the JPanel in this class does not appear when I call it, it's just a window with title as set and white blank content. Here's my code:
public class PleaseWait extends JFrame{
public PleaseWait(){
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenDimensions = toolkit.getScreenSize();
setSize(300,100); //set size based on screen size
setTitle("Please wait");
Container container = getContentPane();
setLocation(new Point(screenDimensions.width*1/4+200, screenDimensions.height*1/4+200)); //set location based on screen size
JPanel panel = new JPanel();
JLabel wait = new JLabel("Please wait");
Dimension buttonsSize = new Dimension(300,100);
panel.setPreferredSize(buttonsSize);
wait.setPreferredSize(buttonsSize);
panel.setLayout(new BorderLayout());
panel.add(wait, BorderLayout.CENTER);
container.add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false); //unresizable
}
The key is not in the code you've posted, but in this line:
and want to call it whenever a heavy task is in progress
You're running a "heavy" task, and while you're running it, Swing is not painting this GUI, because you're likely running that task on the Swing event thread, and doing so freezes the thread, and your GUI.
Solution: use a background thread such as is obtainable through a SwingWorker, to run the "heavy" task.
Other side issues:
This appears to be a "dependent" or "sub" window off of the main application. If so, it should not be a JFrame since an application should only have one main application window, but rather it should be a JDialog.
You're using setPreferredSize(...) and hard-coding your component sizes, something fraught with problems.
e.g.,
import java.awt.*;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class TestPleaseWait {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
MainPanel mainPanel = new MainPanel();
JFrame frame = new JFrame("Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
#SuppressWarnings("serial")
class MainPanel extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = 450;
public MainPanel() {
add(new JButton(new AbstractAction("Without Background Thread") {
{
putValue(MNEMONIC_KEY, KeyEvent.VK_O);
}
#Override
public void actionPerformed(ActionEvent e) {
final PleaseWait wait = new PleaseWait();
wait.setVisible(true);
try {
Thread.sleep(4000);
} catch (InterruptedException e1) {
}
wait.setVisible(false);
}
}));
add(new JButton(new AbstractAction("With Background Thread") {
private JDialog waitDialog = null;
private MyWaitPanel myWaitPanel = new MyWaitPanel();
{
putValue(MNEMONIC_KEY, KeyEvent.VK_W);
}
#Override
public void actionPerformed(ActionEvent e) {
if (waitDialog == null) {
Component component = MainPanel.this;
Window win = SwingUtilities.getWindowAncestor(component);
waitDialog = new JDialog(win, "Please Wait", ModalityType.APPLICATION_MODAL);
waitDialog.add(myWaitPanel);
waitDialog.pack();
waitDialog.setLocationRelativeTo(win);
}
new Thread(() -> {
try {
Thread.sleep(4000);
} catch (InterruptedException e1) {
}
SwingUtilities.invokeLater(() -> {
waitDialog.setVisible(false);
});
}).start();
waitDialog.setVisible(true);
}
}));
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
}
#SuppressWarnings("serial")
class MyWaitPanel extends JPanel {
private JProgressBar progressBar = new JProgressBar();
public MyWaitPanel() {
progressBar.setIndeterminate(true);
JLabel waitLabel = new JLabel("Please Wait", SwingConstants.CENTER);
waitLabel.setFont(waitLabel.getFont().deriveFont(Font.BOLD, 40));
int ebGap = 10;
setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
setLayout(new BorderLayout(ebGap, ebGap));
add(waitLabel, BorderLayout.PAGE_START);
add(progressBar);
}
}
#SuppressWarnings("serial")
class PleaseWait extends JFrame {
public PleaseWait() {
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenDimensions = toolkit.getScreenSize();
setSize(300, 100); // set size based on screen size
setTitle("Please wait");
Container container = getContentPane();
setLocation(new Point(screenDimensions.width * 1 / 4 + 200,
screenDimensions.height * 1 / 4 + 200));
JPanel panel = new JPanel();
JLabel wait = new JLabel("Please wait");
Dimension buttonsSize = new Dimension(300, 100);
panel.setPreferredSize(buttonsSize);
wait.setPreferredSize(buttonsSize);
panel.setLayout(new BorderLayout());
panel.add(wait, BorderLayout.CENTER);
container.add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false); // unresizable
}
}
Related
I have the main class that instantiates a GridBagLayout with a JLabel visbility set to false.
I would like to set the label visible when the program is running, I have tried this but it won't work. It will just display the default layout.
Main class:
gui = new gui();
gui.display();
gui.label.setVisible(true);
Gridbag layout class:
public JFrame frame;
public JLabel label1;
/**
* Launch the application.
*/
public static void display(){
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
gridLayout window = new gridLayout();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
* Create the application.
*/
public gridLayout() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
#SuppressWarnings("static-access")
public void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 600, 1000);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
frame.getContentPane().setLayout(gridBagLayout);
}
label1 = new JLabel(new ImageIcon("hi"));
GridBagConstraints gbc_label1 = new GridBagConstraints();
gbc_label1.insets = new Insets(0, 0, 5, 5);
gbc_label1.gridx = 1;
gbc_label1.gridy = 1;
label1.setVisible(false);
frame.getContentPane().add(label1, gbc_label1);
You want to display a label while a programme is running, right? This has nothing to do with the layout manager.
I give you an example where the label is visible as long as a dialog (representing your task/programme) is displayed; and I hope you can adopt it to your needs. Possibly you have to put the programme/task in an own thread.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Y extends JFrame {
public static final long serialVersionUID = 100L;
public Y() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 240);
JLabel lb= new JLabel("Programme is running ...");
lb.setVisible(false);
add(lb, BorderLayout.CENTER);
JButton b= new JButton("Launch programme (dialog)");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
lb.setVisible(true);
JDialog dlg= new JDialog(Y.this, "The dialog", true);
dlg.setSize(100, 100);
dlg.setVisible(true);
lb.setVisible(false);
}
});
add(b, BorderLayout.SOUTH);
setVisible(true);
}
static public void main(String args[]) {
EventQueue.invokeLater(Y::new);
}
}
I'm trying to put components into panels having different sizes. But, I realized that GridLayout divides the parts with same sizes. How can it be accomplished as explained below image
enter image description here
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class PanelDemo {
PanelDemo() {
// Create a new JFrame container. Use the default
// border layout.
JFrame jfrm = new JFrame("Use Three JPanels with Different Sizes");
// Specify FlowLayout manager.
jfrm.getContentPane().setLayout(new GridLayout(1, 3));
// Give the frame an initial size.
jfrm.setSize(900, 300);
// Terminate the program when the user closes the application.
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create the first JPanel.
JPanel jpnl = new JPanel();
jpnl.setLayout(new GridLayout(2, 4));
// Set the preferred size of the first panel.
jpnl.setPreferredSize(new Dimension(500, 300));
// Make the panel opaque.
jpnl.setOpaque(true);
// Add a blue border to the panel.
jpnl.setBorder(
BorderFactory.createLineBorder(Color.BLUE));
// Create the second JPanel.
JPanel jpnl2 = new JPanel();
//jpnl2.setLayout(new FlowLayout());
// Set the preferred size of the second panel.
jpnl2.setPreferredSize(new Dimension(300, 300));
// Make the panel opaque.
jpnl2.setOpaque(true);
jpnl2.setBorder(
BorderFactory.createLineBorder(Color.RED));
JPanel jpnl3 = new JPanel();
jpnl3.setOpaque(true);
jpnl3.setPreferredSize(new Dimension(100, 300));
jpnl3.setBorder(
BorderFactory.createLineBorder(Color.ORANGE));
// Add the panels to the frame.
jfrm.getContentPane().add(jpnl);
jfrm.getContentPane().add(jpnl3);
jfrm.getContentPane().add(jpnl2);
// Display the frame.
jfrm.setVisible(true);
}
public static void main(String args[]) {
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new PanelDemo();
}
});
}
}
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class TwoPanelWithButtonsLayout {
private JComponent ui = null;
private Insets buttonMargin = new Insets(10,10,10,10);
TwoPanelWithButtonsLayout() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new BorderLayout(4,4));
ui.setBorder(new EmptyBorder(4,4,4,4));
int gap = 5;
JPanel buttons1 = new JPanel(new GridLayout(2, 4, gap, gap));
// 50 is the gap on right, alter as needed
buttons1.setBorder(new EmptyBorder(0, 0, 0, 50));
for (int ii=1; ii<9; ii++) {
buttons1.add(getBigButton("" + ii));
}
ui.add(buttons1, BorderLayout.CENTER);
JPanel buttons2 = new JPanel(new GridLayout(2, 2, gap, gap));
for (int ii=1; ii<5; ii++) {
buttons2.add(getBigButton("" + ii));
}
ui.add(buttons2, BorderLayout.LINE_END);
}
private JButton getBigButton(String text) {
JButton b = new JButton(text);
Font f = b.getFont();
b.setFont(f.deriveFont(f.getSize()*3f));
b.setMargin(buttonMargin);
return b;
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
TwoPanelWithButtonsLayout o = new TwoPanelWithButtonsLayout();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
You could use FlowLayout but if they resize your frame then it will wrap the panels.
So I have come across a peculiar problem.
My interface is just a single label, and a JSlider.
My code(stripped):
import javax.swing.*;
import java.awt.*;
public class Broken {
JLabel value = new JLabel();
JSlider slider = new JSlider(0, 255, 0);
public Broken() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JPanel panel = new JPanel();
value.setText("Some Value");
panel.add(value);
JFrame frame = new JFrame("Frame Name");
frame.setLayout(new GridLayout(2, 1));
frame.add(panel);
frame.add(slider);
frame.pack();
frame.setVisible(true);
}
});
}
public static void main(String[] args) {
new Broken();
}
}
What happens is the label doesn't show up. If I resize the screen from the right to the smallest possible, suddenly the text appears, and it will stay there if I resize back to what it was. I have no idea what's happening, this truly seems like a bug to me.
Before and after resizing screenshots:
Despite your efforts, you're not on the EventDispatchThread when you're creating your JLabel (or JSlider, for that matter). To test, I subclassed JLabel just see if the code was on the EDT when it's constructor is called:
import java.awt.*;
import javax.swing.*;
public class Broken {
JLabel value = new XLabel(); // called before constructor, so not on EDT
JSlider slider = new JSlider(0, 255, 0); // same here
public Broken() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JPanel panel = new JPanel();
value.setText("Some Value");
panel.add(value);
JFrame frame = new JFrame("Frame Name");
frame.setLayout(new GridLayout(2, 1));
frame.add(panel);
frame.add(slider);
frame.pack();
frame.setVisible(true);
}
});
}
public static void main(String[] args) {
new Broken();
}
class XLabel extends JLabel {
public XLabel() {
super();
System.out.println("EDT? " + SwingUtilities.isEventDispatchThread());
}
}
}
To fix, place the invokeLater call in main, so as to wrap the entire construction of your class onto the EDT:
import java.awt.*;
import javax.swing.*;
public class Broken2 {
JLabel value = new JLabel();
JSlider slider = new JSlider(0, 255, 0);
public Broken2() {
JPanel panel = new JPanel();
value.setText("Some Value");
panel.add(value);
JFrame frame = new JFrame("Frame Name2");
frame.setLayout(new GridLayout(2, 1));
frame.add(panel);
frame.add(slider);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
// Generally the proper way. Create Whole app on EDT
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Broken2();
}
});
}
}
I'm kind of new to java and I experienced this little problem on every computer I run my program.
My code is
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class FrameTest2 {
public static void main(String[] args){
String s = "Catch Torchic";
MainMenu m = new MainMenu(s);
}
}
class MainMenu extends JFrame {
JButton autoa, manualb, createc, exitd;
public MainMenu(String s){
super(s);
setBackground(new Color(247,247,111));
setSize(640,600);
setVisible(true);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container contentPane = getContentPane();
setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
CustomPanel panel = new CustomPanel();
panel.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.setMinimumSize(new Dimension(600,365));
panel.setPreferredSize(new Dimension(600,365));
panel.setMaximumSize(new Dimension(600,365));
panel.setBackground(new Color(247,247,111));
contentPane.add(panel);
JPanel btnPanel = new JPanel();
btnPanel.setLayout( new BoxLayout(btnPanel, BoxLayout.Y_AXIS));
btnPanel.setBackground(new Color(247,247,111));
autoa = new JButton("AutoPlay");
autoa.setAlignmentX(Component.CENTER_ALIGNMENT);
btnPanel.add(autoa);
manualb = new JButton("Manual Play");
manualb.setAlignmentX(Component.CENTER_ALIGNMENT);
btnPanel.add(manualb);
createc = new JButton("Create Maze");
createc.setAlignmentX(Component.CENTER_ALIGNMENT);
btnPanel.add(createc);
exitd = new JButton("Exit");
exitd.setAlignmentX(Component.CENTER_ALIGNMENT);
btnPanel.add(exitd);
btnPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
contentPane.add(btnPanel);
setContentPane(contentPane);
ButtonHandler handler = new ButtonHandler(this);
autoa.addActionListener(handler);
manualb.addActionListener(handler);
createc.addActionListener(handler);
exitd.addActionListener(handler);
}
}
class ButtonHandler implements ActionListener{
MainMenu mm;
public ButtonHandler(MainMenu mm){
this.mm = mm;
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == mm.autoa)
System.out.println("Clicked on Auto");
else if(e.getSource() == mm.manualb)
System.out.println("Clicked on Manual");
else if(e.getSource() == mm.createc)
System.out.println("Clicked on Create");
else
System.exit(0);
}
}
class CustomPanel extends JPanel{
public void paintComponent (Graphics painter){
Image pic = Toolkit.getDefaultToolkit().getImage("logo.png");
if(pic != null) painter.drawImage(pic, 105, 30, this);
}
}
This code results into this: http://a3.sphotos.ak.fbcdn.net/hphotos-ak-ash4/318155_424290814251286_100000111130260_1871937_131988334_n.jpg
where there is always the extra button on the upper left corner, My question is, how do I remove this? the button appears at random intervals, sometimes it does not.
Try this variant. Many comments, the most important in SHOUTING. Note that by the time I had got it to being working code (or rather, code that worked here for loading the image), I never once saw the problem you describe.
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.net.URL;
import javax.imageio.ImageIO;
public class FrameTest2 {
public static void main(String[] args) throws Exception {
final String s = "Catch Torchic";
URL url = new URL("http://pscode.org/media/stromlo2.jpg");
final Image image = ImageIO.read(url);
//Create the frame on the event dispatching thread
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run() {
new MainMenu(s, image);
}
});
}
}
class MainMenu extends JFrame {
JButton autoa, manualb, createc, exitd;
public MainMenu(String s, Image image) {
super(s);
// do this after pack (if at all)
//setSize(640,600);
// do this after pack/setSize
//setVisible(true);
// don't do this in broken code
//setResizable(false);
// If you're going to spend space on GUI position..
// setLocationRelativeTo(null);
// ..do it like this.
setLocationByPlatform(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
CustomPanel panel = new CustomPanel(image);
panel.setAlignmentX(Component.CENTER_ALIGNMENT);
//panel.setMinimumSize(new Dimension(600,365));
//panel.setPreferredSize(new Dimension(600,365));
//panel.setMaximumSize(new Dimension(600,365));
contentPane.add(panel);
JPanel btnPanel = new JPanel();
btnPanel.setBorder(new EmptyBorder(5,5,100,5));
btnPanel.setLayout( new BoxLayout(btnPanel, BoxLayout.Y_AXIS));
// not needed for an SSCCE
//btnPanel.setBackground(new Color(247,247,111));
autoa = new JButton("AutoPlay");
autoa.setAlignmentX(Component.CENTER_ALIGNMENT);
btnPanel.add(autoa);
manualb = new JButton("Manual Play");
manualb.setAlignmentX(Component.CENTER_ALIGNMENT);
btnPanel.add(manualb);
createc = new JButton("Create Maze");
createc.setAlignmentX(Component.CENTER_ALIGNMENT);
btnPanel.add(createc);
exitd = new JButton("Exit");
exitd.setAlignmentX(Component.CENTER_ALIGNMENT);
btnPanel.add(exitd);
// you already said that
//btnPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
contentPane.add(btnPanel, BorderLayout.SOUTH);
setContentPane(contentPane);
ButtonHandler handler = new ButtonHandler(this);
autoa.addActionListener(handler);
manualb.addActionListener(handler);
createc.addActionListener(handler);
exitd.addActionListener(handler);
// CAUSE THE COMPONENTS TO BE PROPERLY LAID OUT.
pack();
setSize(640,600);
setVisible(true);
}
}
class ButtonHandler implements ActionListener{
MainMenu mm;
public ButtonHandler(MainMenu mm){
this.mm = mm;
}
public void actionPerformed(ActionEvent e){
// for clarity, even single line statements
// in these should be enclosed in {}
if(e.getSource() == mm.autoa)
System.out.println("Clicked on Auto");
else if(e.getSource() == mm.manualb)
System.out.println("Clicked on Manual");
else if(e.getSource() == mm.createc)
System.out.println("Clicked on Create");
else
System.exit(0);
}
}
class CustomPanel extends JPanel{
Image pic;
CustomPanel(Image pic) {
this.pic = pic;
}
public void paintComponent (Graphics painter){
// DO NOT TRY TO READ IMAGES IN PAINT!
//Image pic = Toolkit.getDefaultToolkit().getImage("logo.png");
if(pic != null) painter.drawImage(pic, 105, 30, this);
}
}
I think it is the missing contentPane.:
//setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));//
Also there is a superfluous setting of the content pane.
//setContentPane(contentPane);
After "nope:"
Difficult.
Move setVisible(true) to the end, to invoke only one layouting.
Try it without two panels (only one) inside the content pane:
Container contentPane0 = getContentPane();
Container contentPane = new JPanel();
contentPane0.add(contentPane);
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)