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);
}
});
}
}
Related
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;
}
}
}
}
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();
}
}
I need to know how to add a JTextField if one of the JComboBox options is selected, and if the other one is selected I don't want to have that text field there any more.
Here is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI extends JFrame{
//Not sure if this code is correct
private JTextField text;
private JComboBox box;
private static String[] selector = {"Option 1", "Option 2"};
public GUI(){
super("Title");
setLayout(new FlowLayout());
box = new JComboBox(selector);
add(box);
box.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent e){
if(){
//what should be in the if statement and what should i type down here to add the
//JTextField to the JFrame?
}
}
}
);
}
}
Try next example, that should help you:
import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TestFrame extends JFrame {
public TestFrame(){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
init();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
});
}
private void init() {
final JComboBox<String> box = new JComboBox<String>(new String[]{"1","2"});
final JTextField f = new JTextField(5);
box.addItemListener(new ItemListener() {
#Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED){
f.setVisible("1".equals(box.getSelectedItem()));
TestFrame.this.revalidate();
TestFrame.this.repaint();
}
}
});
add(box,BorderLayout.SOUTH);
add(f,BorderLayout.NORTH);
}
public static void main(String... s){
new TestFrame();
}
}
I have 4 JPanels. In one of the panel I have a combo Box.Upon selecting "Value A" in combo box Panel2 should be displayed.Similarly if I select "Value B" Panel3 should be selected....
Though action Listener should be used in this context.How to make a call to another tab with in that action listener.
public class SearchComponent
{
....
.
public SearchAddComponent(....)
{
panel = addDropDown(panelList(), "panel", gridbag, h6Box);
panel.addComponentListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ItemSelectable is = (ItemSelectable)actionEvent.getSource();
Object name=selectedString(is);
}
});
}
public static final Vector<String> panelList(){
List<String> panelList = new ArrayList<String>();
panelList.add("A");
panelList.add("B");
panelList.add("C");
panelList.add("D");
panelList.add("E");
panelList.add("F);
Vector<String> panelVector = null;
Collections.copy(panelVector, panelList);
return panelVector;
}
public Object selectedString(ItemSelectable is) {
Object selected[] = is.getSelectedObjects();
return ((selected.length == 0) ? "null" : (ComboItem)selected[0]);
}
}
Use a Card Layout. See the Swing tutorial on How to Use a Card Layout for a working example.
Try This code:
import java.awt.EventQueue;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Container;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class CardLayoutExample {
JFrame guiFrame;
CardLayout cards;
JPanel cardPanel;
public static void main(String[] args) {
//Use the event dispatch thread for Swing components
EventQueue.invokeLater(new Runnable()
{
#Override
public void run()
{
new CardLayoutExample();
}
});
}
public CardLayoutExample()
{
guiFrame = new JFrame();
//make sure the program exits when the frame closes
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("CardLayout Example");
guiFrame.setSize(400,300);
//This will center the JFrame in the middle of the screen
guiFrame.setLocationRelativeTo(null);
guiFrame.setLayout(new BorderLayout());
//creating a border to highlight the JPanel areas
Border outline = BorderFactory.createLineBorder(Color.black);
JPanel tabsPanel = new JPanel();
tabsPanel.setBorder(outline);
JButton switchCards = new JButton("Switch Card");
switchCards.setActionCommand("Switch Card");
switchCards.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
cards.next(cardPanel);
}
});
tabsPanel.add(switchCards);
guiFrame.add(tabsPanel,BorderLayout.NORTH);
cards = new CardLayout();
cardPanel = new JPanel();
cardPanel.setLayout(cards);
cards.show(cardPanel, "Fruits");
JPanel firstCard = new JPanel();
firstCard.setBackground(Color.GREEN);
addButton(firstCard, "APPLES");
addButton(firstCard, "ORANGES");
addButton(firstCard, "BANANAS");
JPanel secondCard = new JPanel();
secondCard.setBackground(Color.BLUE);
addButton(secondCard, "LEEKS");
addButton(secondCard, "TOMATOES");
addButton(secondCard, "PEAS");
cardPanel.add(firstCard, "Fruits");
cardPanel.add(secondCard, "Veggies");
guiFrame.add(tabsPanel,BorderLayout.NORTH);
guiFrame.add(cardPanel,BorderLayout.CENTER);
guiFrame.setVisible(true);
}
//All the buttons are following the same pattern
//so create them all in one place.
private void addButton(Container parent, String name)
{
JButton but = new JButton(name);
but.setActionCommand(name);
parent.add(but);
}
}
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