Swing window not opening - java

I am creating a NotePad app in Java Swing but when I am trying to open a popup to set a title, it is not showing up.
The class that calls the popup:
import java.io.*;
import java.util.*;
import java.awt.event.*;
import javax.swing.*;
public class NewFile implements ActionListener{
public static String title;
public void actionPerformed(ActionEvent e){
PopupFileName popup = new PopupFileName();
/*try{
Thread.sleep(30000);
}catch (InterruptedException o){
o.printStackTrace();
}*/
JTextArea titl = popup.title;
title = titl.getText();
try{
File writer = new File(title+".txt");
if(writer.createNewFile()){
System.out.println("file created");
}else{
System.out.println("file exists");
}
}catch (IOException i) {
System.out.println("An error occurred.");
i.printStackTrace();
}
}
}
The popup class that is supposed to open:
import javax.swing.*;
public class PopupFileName{
static JFrame popup = new JFrame("File Title");
static JLabel titlel = new JLabel("Title:");
static public JTextArea title = new JTextArea();
public static void main(String[] args){
popup.setSize(200,300);
popup.setVisible(true);
popup.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
popup.add(titlel);
popup.add(title);
}
}
Is there any way I can make it visible and make it able to get the text before it is created?

Start by taking a look at:
Creating a GUI With Swing
How to Write an Action Listener
How to Use Scroll Panes
How to Use Buttons, Check Boxes, and Radio Buttons
How to Make Dialogs
You're running in an event driven environment, this means, something happens and then you respond to it.
The problem with your ActionListener is, it's trying to present a window and then, immediately, trying to get some result from it. The problem is, the window probably isn't even present on the screen yet.
What you need is some way to "stop" the code execution until after the user responds. This is where a modal dialog comes in.
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
class Main {
public static void main(String[] args) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
JButton btn = new JButton("Test");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String title = PopupFileName.getTitle(TestPane.this);
System.out.println(title);
}
});
add(btn);
}
}
public static class PopupFileName extends JPanel {
private JLabel titlel = new JLabel("Title:");
private JTextArea title = new JTextArea(20, 40);
public PopupFileName() {
setLayout(new BorderLayout());
add(titlel, BorderLayout.NORTH);
add(new JScrollPane(title));
}
public String getTitle() {
return title.getText();
}
public static String getTitle(Component parent) {
PopupFileName popupFileName = new PopupFileName();
int response = JOptionPane.showConfirmDialog(parent, popupFileName, "Title", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
switch (response) {
case JOptionPane.OK_OPTION:
return popupFileName.getTitle();
default: return null;
}
}
}
}

Related

Close a JtabbedPane with JInternalFrame Inside

How can I close a JTabbedPane with an JInternalFrame included when I click a button inside this form?
My project has 3 JForms, 1 TabbedPane, 1 JInternalFrame and 1 Main window (to register data). To create my JTabbedPanes I use the method addTab() and from that form I have the button to close which calls another window (Main registry), I used the dispose() and setVisible(false) methods but they don't do anything.
An example (there are 3 clases -Administrador, -MenuPrincipal, -ventanaRegistro) :
First Class a JFrame and on top a JTabbedPane (this is where I create my tabs)
public class MenuPrincipal extends javax.swing.JFrame
{
Administrador ventanaAdministrador = new Administrador();
void showTabs()
{
JTabbedPane.addTab("Administrador", ventanaAdministrador);
}
public MenuPrincipal()
{
initComponents();
showTabs();
}
}
Second Class a JInternalFrame with a single button
public class Administrador extends javax.swing.JInternalFrame
{
void showAdminWindow()
{
ventanaRegistro ventanaRegistro = new ventanaRegistro();
ventanaRegistro.setVisible(true);
}
void closeThisWindow()
{
this.dispose();
}
public Administrador()
{
initComponents();
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
showAdminWindow();
closeThisWindow();
}
}
Third Class a simple JFrame. This is just code to register data.
The real problem is that my method closeThisWindow() doesn't close the second Jtabbed window, and I want to make it that when I click a button (which is on the JTabbedPane) make the third class visible and the Second Class invisible/Close it.
See if the following code does what you expect. If it doesn't please elaborate so I can improve my answer.
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.WindowConstants;
public class MenuPrincipal extends javax.swing.JPanel {
Administrador ventanaAdministrador = new Administrador();
public MenuPrincipal()
{
setPreferredSize(new Dimension(290, 200));
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
ventanaAdministrador.setPreferredSize(new Dimension(350, 100));
tabbedPane.addTab("Admin", ventanaAdministrador);
tabbedPane.addTab("2nd Tab", new JPanel());
add(tabbedPane);
}
/**
* #param args
*/
public static void main(String[] args) {
JFrame testFrame = new JFrame("Main Test Window");
testFrame.setDefaultCloseOperation(WindowConstants.
DISPOSE_ON_CLOSE);
testFrame.setPreferredSize(new Dimension(450, 350));
MenuPrincipal menuP = new MenuPrincipal();
testFrame.getContentPane().add(menuP);
testFrame.pack();
testFrame.setVisible(true);
}
}
And:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class Administrador extends javax.swing.JInternalFrame {
void showAdminWindow()
{
JFrame ventanaRegistro = new JFrame("Admin Window");
ventanaRegistro.
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
ventanaRegistro.setPreferredSize(new Dimension(350, 200));
ventanaRegistro.pack();
ventanaRegistro.setVisible(true);
}
void closeThisWindow()
{
Window window = SwingUtilities.getWindowAncestor(this);
window.dispose();
}
public Administrador()
{
JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.NORTH);
JButton closeWindowBttn = new JButton("Close Window and open a new one");
closeWindowBttn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
closeWindowActionPerformed();
}
});
panel.add(closeWindowBttn);
}
private void closeWindowActionPerformed() {
showAdminWindow();
closeThisWindow();
}
}

Java EventHandler not working, why does it create new Frame?

I am trying to create an address book for a uni project and I am trying to get the GUI to be able to save the details that are input to the form to a file. Every time I click save on the GUI it creates a new Frame rather than executing the code that I have put in the even Handler. I am still fairly new to Java and I just can't see what is wrong with it.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class AddressBook {
static AddressBookGui addressBookGui = new AddressBookGui();
static int writeCount;
File detailsFile = new File("customerDetails.txt");
public static void saveDetails() throws IOException {
String title = addressBookGui.txtTitle.getText();
FileWriter fw = new FileWriter("customerDetails.txt");
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);
out.println(title);
out.close();
writeCount++;
}
}
Above is the Handler class, below is the GUI.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class AddressBookGui {
private JLabel lblTitle;
public JTextField txtTitle;
private JButton btnSaveDetails;
private JPanel panel;
private JFrame frame;
public static void main(String[] args) {
new AddressBookGui();
}
public AddressBookGui() {
createPanel();
addLabels();
addTextFields();
addButtons();
frame.add(panel);
frame.setVisible(true);
}
public void createPanel() {
frame = new JFrame();
frame.setTitle("Address Book");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800,950);
frame.setVisible(true);
panel = new JPanel();
panel.setLayout(null);
}
public void addLabels() {
lblTitle = new JLabel("Title");
lblTitle.setBounds(90,210,140,30);
panel.add(lblTitle);
}
public void addTextFields() {
txtTitle = new JTextField("");
txtTitle.setBounds(190,210,150,30);
panel.add(txtTitle);
}
public void addButtons() {
btnSaveDetails = new JButton("Save");
btnSaveDetails.setBounds(200,600,80,30);
btnSaveDetails.addActionListener(new SaveDetailsButton());
panel.add(btnSaveDetails);
}
public class SaveDetailsButton implements ActionListener {
public void actionPerformed(ActionEvent event) {
try {
AddressBook.saveDetails();
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "File did not write correctly.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
Thanks in advance.

Java swing radioButton with changing, clickable icon

Designing a questionary, the scope of answer can be elected by radioButtons.
To display a greater clickable area (the application is for touchscreen), I layed icon_1 over the radiobuttons.
Every mouseclick can change the displayed icon to icon_2 and permantly vice versa.
I am sorry, using
jRadioButtonActionPerformed
ImageIcon o_ButtonIcon = new ImageIcon ("....")
jRadioButton.setIcon(Icon m_ButtonIcon).
I get no changing, clickable image.
Can you please give me a helping hand?
Seems to be working fine.
Post an SSCCE to show specific problems.
Here is example ( i do not recommend getScaledInstance(..) just used it for quick example)
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
public class Test {
private ImageIcon ii1;
private ImageIcon ii2;
private JRadioButton jrb = new JRadioButton("Click me :)");
private JFrame frame = new JFrame();
public Test() {
try {
ii1 = new ImageIcon(ImageIO.read(new URL("http://cdn.macrumors.com/article/2010/09/03/145454-itunes_10_icon.jpg")).getScaledInstance(48, 48, Image.SCALE_SMOOTH));
ii2 = new ImageIcon(ImageIO.read(new URL("http://www.quarktet.com/Icon-small.jpg")).getScaledInstance(48, 48, Image.SCALE_SMOOTH));
} catch (Exception ex) {
ex.printStackTrace();
}
initComponents();
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test();
}
});
}
private void initComponents() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jrb.setIcon(ii1);
jrb.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
if (jrb.getIcon() == ii1) {
jrb.setIcon(ii2);
} else {
jrb.setIcon(ii1);
}
}
});
frame.add(jrb);
frame.pack();
frame.setVisible(true);
}
}

Changing JDialog from MODELESS to APPLICATION_MODAL opens JDialog twice [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I have a pretty strange behavior which I can only conclude must be a Java bug somewhere.
I changed one line in my constructor
super(parent, "Production Plan Export", ModalityType.MODELESS);
to
super(parent, "Production Plan Export", ModalityType.APPLICATION_MODAL);
and suddenly when I click on the button to open my JDialog, it opens it twice, the first time, its not responsive at all. I need to click the X button to close the window, and then when I do, then the same JDialog appears, and suddenly all my buttons opens.
Has anyone seen this behavior before?
I am using Java 1.6.0_33
Edit
What is very very strange, is when I try to debug it in eclipse and setting a break point at my constuctor, and I go to next line, then it suddenly jumps to my variable in the class and starts to go through my variables instead of the next line in the constructor.
I have tried to restart my computer and eclipse, but that didn't work.
I will see if I can create a small test case
Edit2:
Ok, so I have created a small application that can reproduce it for me.
Please note that I have tried to remove the part of the code that is not relevant, so there is alot of code that isn't valid for this test case.
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
#SuppressWarnings("serial")
public class ProductionPlanExportDialog extends JDialog {
private JProgressBar progressbar;
private JLabel message;
private JButton exportButton;
private JButton helpButton;
private int state = JOptionPane.CANCEL_OPTION;
private final Action closeAction = new CloseAction();
private final Action enableExport = new EnableExport();
private boolean updating = false;
private JButton closeButton;
public ProductionPlanExportDialog(Window parent) {
super(parent, "Test", ModalityType.APPLICATION_MODAL); //The JDialog is not centered, and the close button doesn't work
// super(parent, "Test", ModalityType.MODELESS); //The close button works and the jdialog is centered
initGUI();
bindModel();
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
close();
}
});
}
public static void main(String args[]) {
new ProductionPlanExportDialog(null);
}
public void initGUI() {
JTabbedPane mainTabbedPane = new JTabbedPane(JTabbedPane.TOP);
JPanel yAxisPanel = new JPanel();
yAxisPanel.setLayout(new BoxLayout(yAxisPanel, BoxLayout.Y_AXIS));
JPanel progressPanel = new JPanel(new FlowLayout());
progressPanel.add(getProgressbar());
yAxisPanel.add(progressPanel);
yAxisPanel.add(getMessage());
JPanel buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(getExportButton());
closeButton = new JButton("Close");
buttonPanel.add(closeButton);
buttonPanel.add(getHelpButton());
yAxisPanel.add(buttonPanel);
setSize(937, 605);
getContentPane().add(yAxisPanel);
setVisible(true);
setLocationRelativeTo(null);
}
private void bindModel() {
closeButton.setAction(closeAction);
}
public int getExitStatus() {
return state;
}
private JProgressBar getProgressbar() {
if (progressbar == null) {
progressbar = new JProgressBar();
progressbar.setPreferredSize(new Dimension(1000, 22));
progressbar.setName("progressbar");
progressbar.setStringPainted(true);
progressbar.setVisible(false);
}
return progressbar;
}
private JLabel getMessage() {
if (message == null) {
message = new JLabel();
message.setName("message");
}
return message;
}
private void setUIState() {
updating = true;
assert SwingUtilities.isEventDispatchThread();
try {
closeButton.setEnabled(false);
} finally {
updating = false;
}
}
private void setTextFieldValue(JFormattedTextField textField, long value) {
if(value == Long.MAX_VALUE || value == -Long.MAX_VALUE) {
textField.setText("");
} else {
textField.setValue(value);
}
}
public JButton getExportButton() {
if (exportButton == null) {
exportButton = new JButton();
exportButton.setToolTipText("Preview production plan");
exportButton.setName("exportButton");
exportButton.setText("Preview");
exportButton.setBounds(305, 640, 72, 21);
exportButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
}
});
}
return exportButton;
}
private JButton getHelpButton() {
if (helpButton == null) {
helpButton = new JButton();
helpButton.setBounds(470, 640, 72, 21);
helpButton.setName("helpButton");
helpButton.setText("Help");
helpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
String helpText = "This dialog is used to preview and export a production plan.<br/>" +
"<h1>Preview</h1>"
+ "After pressing 'Export', the production plan will be generated. This can take a few minutes.";
JEditorPane helpEditorPane = new JEditorPane("text/html", helpText);
helpEditorPane.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 12));
helpEditorPane.setEditable(false);
JScrollPane scrollPane = new JScrollPane(helpEditorPane,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
helpEditorPane.setCaretPosition(0);
scrollPane.setPreferredSize(new Dimension(640,445));
JOptionPane.showMessageDialog(helpButton, scrollPane, "Production Plan Export Dialog Help", JOptionPane.INFORMATION_MESSAGE);
}
});
}
return helpButton;
}
private final class EnableExport extends AbstractAction {
#Override
public void actionPerformed(final ActionEvent e) {
if(isAllCheckboxSelected()) {
getExportButton().setText("Export");
getExportButton().setToolTipText("Export production plan");
} else {
getExportButton().setText("Preview");
getExportButton().setToolTipText("Preview production plan");
}
}
}
boolean enableExport() {
return isAllCheckboxSelected();
}
boolean isAllCheckboxSelected() {
return false;
}
private final class CloseAction extends AbstractAction {
public CloseAction() {
super("Close");
}
#Override
public void actionPerformed(final ActionEvent e) {
close();
}
}
private void close() {
state = JOptionPane.OK_OPTION;
setVisible(false);
dispose();
}
}
not able to ...., can you please (descriptions about Bug) to test
import java.awt.Cursor;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Main {
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setSize(new Dimension(500, 500));
final JDialog dialog = new JDialog(frame, "Production Plan Export",
ModalityType.MODELESS);
dialog.setSize(300, 300);
final JDialog dialog1 = new JDialog(dialog, "Production Plan Export",
ModalityType.APPLICATION_MODAL);
dialog1.setSize(200, 200);
frame.add(new JButton(new AbstractAction("Dialog") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
Runnable doRun = new Runnable() {
public void run() {
dialog.setVisible(true);
dialog1.setVisible(true);
}
};
SwingUtilities.invokeLater(doRun);
}
}));
frame.setVisible(true);
}
}
I found the problem.
It was because I had setVisible(true) twice. Once in my initGUI() method, and once where I initialize my JDialog.
Also thanks to MKorbel, I moved the setAction call in my initGUI() which made the button work when having APPLICATION_MODAL

Should open new window while clicking a button?

I know that it is very simple question, but I can't find a solution.
I have a main swing dialog and other swing dialog. Main dialog has a button.
How can I make that after clicking a button the other dialog opens?
EDIT:
When I try this:
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
NewJDialog okno = new NewJDialog();
okno.setVisible(true);
}
I get an error:
Cannot find symbol NewJDialog
The second window is named NewJDialog...
You'll surely want to look at How to Make Dialogs and review the JDialog API. Here's a short example to get started. You might compare it with what you're doing now.
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class DialogTest extends JDialog implements ActionListener {
private static final String TITLE = "Season Test";
private enum Season {
WINTER("Winter"), SPRING("Spring"), SUMMER("Summer"), FALL("Fall");
private JRadioButton button;
private Season(String title) {
this.button = new JRadioButton(title);
}
}
private DialogTest(JFrame frame, String title) {
super(frame, title);
JPanel radioPanel = new JPanel();
radioPanel.setLayout(new GridLayout(0, 1, 8, 8));
ButtonGroup group = new ButtonGroup();
for (Season s : Season.values()) {
group.add(s.button);
radioPanel.add(s.button);
s.button.addActionListener(this);
}
Season.SPRING.button.setSelected(true);
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
this.add(radioPanel);
this.pack();
this.setLocationRelativeTo(frame);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
JRadioButton b = (JRadioButton) e.getSource();
JOptionPane.showMessageDialog(null, "You chose: " + b.getText());
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new DialogTest(null, TITLE);
}
});
}
}

Categories