user2449865
user2449865

Reputation: 1

Cannot Display JOptionPane When Button Is Pressed

So I have the following Code:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextPane;

@SuppressWarnings("serial")
public class Window extends JPanel implements ActionListener {

public static JTextPane text = new JTextPane();
public static BorderLayout layout = new BorderLayout();
public static JButton debug = new JButton("Debug");
public static boolean isDebugPressed = false;
public static JFrame frame = new JFrame();

public Window(){
    debug.addActionListener(this);
    this.setLayout(layout);
    this.add(debug,BorderLayout.NORTH);
    this.add(text,BorderLayout.CENTER);


}

public static void main(String[] args){
    Window window = new Window();
    frame.setLayout(layout);
    frame.setSize(new Dimension(600,600));
    frame.setTitle("QuickScript Compiler");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setResizable(false);
    frame.setVisible(true);
    frame.setLocationRelativeTo(null);
    frame.add(window);
    debug.setActionCommand("debug");
    if (isDebugPressed){
        JOptionPane.showMessageDialog(frame, "Output: " + text.getText().toString() , "Debugging", JOptionPane.PLAIN_MESSAGE);
    }
}

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equals("debug")){
        isDebugPressed = true;
        System.out.println("true");
    }

}

and when I press the debug button a box should pop up and display whatever I typed inside of the text pane, but there is nothing that shows up. How do I fix this? I have a feeling that I may have missed something very important, but I just can't figure out what it is. Thanks to anybody who can help :D

Upvotes: 0

Views: 316

Answers (1)

camickr
camickr

Reputation: 324197

//if (isDebugPressed){
        JOptionPane.showMessageDialog(frame, "Output: " + text.getText().toString() , "Debugging", JOptionPane.PLAIN_MESSAGE);

The code to display the option pane needs to be added to the ActionListener.

The variable isDebugPressed is false when the GUI is created and that statement is never executed again.

Also, because the ActionListener is only ever added to the Debug button you don't need to set an action command and check the command in the ActionListener. The source button will always be the Debug button so you can just display the option pane.

Upvotes: 3

Related Questions