Block a JDialog when I open another one - java

I've got a JDialog with a button that opens a new window. What I want to do is to block this JDialog whenever the other window opens. When I say block I mean that the user cannot manipulate it, not move it or maximisize or anything.
By the way, is it recommended to use JDialog for a window with buttons and a table? I stil don't get it when I have to use which frame!
This is what I've got:
public class Platos extends JDialog {
private final JPanel contentPanel = new JPanel();
public static void main(String[] args) {
try {
Platos dialog = new Platos();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
public Platos() {
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setLayout(new FlowLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
{
JButton btnAgregarPlato = new JButton("Agregar Plato");
btnAgregarPlato.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
AgregarPlato ap = new AgregarPlato();
ap.setVisible(true);
}
});
btnAgregarPlato.setFont(new Font("Tahoma", Font.PLAIN, 11));
contentPanel.add(btnAgregarPlato);
}
}
}

JDialog is the right choice indeed.
To make it block the parent window, you would have to add a constructor to Platos, which will utilise the JDialog constructor with parent frame:
JDialog dlg = new JDialog(parentWindow, modality);
Where parentWindow is typically a JFrame.
You do it like this:
public Platos(JFrame parent) {
super(parent, ModalityType.APPLICATION_MODAL);
....
The trick is the ModalityType.APPLICATION_MODAL argument, which makes your dialog block all other dialogs and the main frame.
You can pass as parent the main window, it will work just fine even if you are opening the dialog from another one - the last one blocks all the previous ones.
For more reference, see the docs.

Related

Currency Exchange API Java GUI

I am fairly new to programming of this level and I was wondering if someone could help me with this.
So I am trying to create a currency exchange app using Java, and I have a problem updating the values on the GUI to reflect the new value on the API. Essentially ever so often the values change and it shows on the console, however, the GUI value never updates and stays the same.
I thought ActionListener would help solve this problem but either I have not implemented it properly or I haven't googled and come up with a solution properly.
Thank you in advance for any help :)
Here is my code:
GUI.java
public class GUI extends JFrame {
static Arb arb = new Arb();
private JPanel contentPane;
public static void main(String[] args) throws IOException, InterruptedException {
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
arb.runUpdate_fx("anAPI");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Timer timer = new Timer(100 ,taskPerformer);
timer.setRepeats(true);
timer.start();
Thread.sleep(5000);
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI frame = new GUI();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public GUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1121, 765);
contentPane = new JPanel();
contentPane.setBackground(Color.BLACK);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
JTextPane FXRate = new JTextPane();
FXRate.setForeground(new Color(255, 255, 255));
FXRate.setBackground(new Color(0, 0, 0));
FXRate.setEditable(false);
FXRate.setFont(new Font("Tahoma", Font.BOLD, 11));
panel_1.setLayout(new FlowLayout(FlowLayout.LEADING, 5, 5));
FXRate.setText("FX Rates\r\n\r\nEUR-AUD FX Rate: " + arb.fxEURAUD + "\r\nEUR-USD FX Rate: " + arb.fxEURUSD);
panel_1.add(FXRate);
}
}
Result:
EUR-AUD: 1.646659
after sometime
EUR-AUD: 1.646659
Expected Result:
EUR-AUD: 1.646659
after sometime
EUR-AUD: 1.80102
References are passed by value in Java.
JTextField textField = new JTextField();
String text = "Initial text";
textField.setText(text); // no displays "Initial text";
text = "Updated text"; // doesn't change what the panel displays
// the panel still holds a reference to the old text
textField.setText(text); // updates the reference the panel holds to your new text
In your event listener, you need to call setText with the updated string to actually make the textfield display that.
Your timer and event handler look good, but the update method only fetches new values into the Arb object; nothing takes those values and puts them into the GUI. You can do that explicitly in your event handler.after the update method returns. To enable that, you may want to make FXRate a member variable, so you can access it from the action listener.

JFrame setContentPane hides other components

So I'm going into GUI's in Java, and am trying to create a simple main menu for a timer. All is well until I've attempted to add a background for the GUI. Adding the background works, however all other components are now gone, (the button). How could I fix this?
EDIT: Here is my new code.
public class MainMenu {
// JFrame = the actual menu / frame.
private JFrame frame;
// JLabel = provides text instructions or information on a GUI —
// display a single line of read-only text, an image or both text and an image.
private JLabel background;
// JButton = button.
private JButton alarmClockButton;
// Constructor to create menu
public MainMenu() {
frame = new JFrame("Alarm Clock");
alarmClockButton = new JButton("Timer");
// Add an event to clicking the button.
alarmClockButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// TODO: CHANGE TO SOMETHING NICER
JOptionPane.showMessageDialog(null, "This feature hasn't been implemented yet.", "We're sorry!",
JOptionPane.ERROR_MESSAGE);
}
});
// Creating the background
try {
background = new JLabel(new ImageIcon(ImageIO.read(getClass()
.getResourceAsStream("/me/devy/alarm/clock/resources/Background.jpg"))));
} catch (IOException e) {
e.printStackTrace();
}
frame.setLayout(new FlowLayout());
frame.setContentPane(background);
frame.add(alarmClockButton);
frame.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
frame.setVisible(true);
frame.setSize(450, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
alarmClockButton.setForeground(Color.RED);
}
}
Thank you!
frame.setContentPane(background);
You use the label as the content pane. The problem is that the label doesn't use a layout manager by default.
You need to add:
background.setLayout( new BorderLayout() ); // or whatever layout you want
frame.setContentPane(background);
Now you can add the button directly to the frame. You don't need the panel.
Or if you want to get fancy you can use the Background Panel which gives you the option to scale or tile the background image.
Instead of making the ContentPane as JLabel, you can wrap the JLabel in a JPanel, then add this JPanel as the ContentPane :
public class MainMenu {
public static void main(String[] args) {
new MainMenu();
}
// JFrame = the actual menu / frame.
private JFrame frame;
private JPanel panel;
private JPanel bkgPanel;
// JLabel = provides text instructions or information on a GUI —
// display a single line of read-only text, an image or both text and an
// image.
private JLabel background;
// JButton = button.
private JButton alarmClockButton;
// Constructor to create menu
public MainMenu() {
frame = new JFrame("Alarm Clock");
panel = new JPanel();
bkgPanel = new JPanel();
alarmClockButton = new JButton("Timer");
// Add an event to clicking the button.
alarmClockButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// TODO: CHANGE TO SOMETHING NICER
JOptionPane.showMessageDialog(null, "This feature hasn't been implemented yet.", "We're sorry!",
JOptionPane.ERROR_MESSAGE);
}
});
// Creating the background
try {
background = new JLabel(new ImageIcon(
ImageIO.read(getClass().getResourceAsStream("/me/devy/alarm/clock/resources/Background.jpg"))));
bkgPanel.add(background);
} catch (IOException e) {
e.printStackTrace();
}
frame.setContentPane(bkgPanel);
frame.add(panel);
panel.add(alarmClockButton);
frame.setVisible(true);
frame.setSize(450, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
alarmClockButton.setForeground(Color.RED);
}
}

How to display one Jframe at a time? [duplicate]

I'm trying to make a little game that will first show the player a simple login screen where they can enter their name (I will need it later to store their game state info), let them pick a difficulty level etc, and will only show the main game screen once the player has clicked the play button. I'd also like to allow the player to navigate to a (hopefully for them rather large) trophy collection, likewise in what will appear to them to be a new screen.
So far I have a main game window with a grid layout and a game in it that works (Yay for me!). Now I want to add the above functionality.
How do I go about doing this? I don't think I want to go the multiple JFrame route as I only want one icon visible in the taskbar at a time (or would setting their visibility to false effect the icon too?) Do I instead make and destroy layouts or panels or something like that?
What are my options? How can I control what content is being displayed? Especially given my newbie skills?
A simple modal dialog such as a JDialog should work well here. The main GUI which will likely be a JFrame can be invisible when the dialog is called, and then set to visible (assuming that the log-on was successful) once the dialog completes. If the dialog is modal, you'll know exactly when the user has closed the dialog as the code will continue right after the line where you call setVisible(true) on the dialog. Note that the GUI held by a JDialog can be every bit as complex and rich as that held by a JFrame.
Another option is to use one GUI/JFrame but swap views (JPanels) in the main GUI via a CardLayout. This could work quite well and is easy to implement. Check out the CardLayout tutorial for more.
Oh, and welcome to stackoverflow.com!
Here is an example of a Login Dialog as #HovercraftFullOfEels suggested.
Username: stackoverflow Password: stackoverflow
import java.awt.*;
import java.awt.event.*;
import java.util.Arrays;
import javax.swing.*;
public class TestFrame extends JFrame {
private PassWordDialog passDialog;
public TestFrame() {
passDialog = new PassWordDialog(this, true);
passDialog.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new TestFrame();
frame.getContentPane().setBackground(Color.BLACK);
frame.setTitle("Logged In");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
});
}
}
class PassWordDialog extends JDialog {
private final JLabel jlblUsername = new JLabel("Username");
private final JLabel jlblPassword = new JLabel("Password");
private final JTextField jtfUsername = new JTextField(15);
private final JPasswordField jpfPassword = new JPasswordField();
private final JButton jbtOk = new JButton("Login");
private final JButton jbtCancel = new JButton("Cancel");
private final JLabel jlblStatus = new JLabel(" ");
public PassWordDialog() {
this(null, true);
}
public PassWordDialog(final JFrame parent, boolean modal) {
super(parent, modal);
JPanel p3 = new JPanel(new GridLayout(2, 1));
p3.add(jlblUsername);
p3.add(jlblPassword);
JPanel p4 = new JPanel(new GridLayout(2, 1));
p4.add(jtfUsername);
p4.add(jpfPassword);
JPanel p1 = new JPanel();
p1.add(p3);
p1.add(p4);
JPanel p2 = new JPanel();
p2.add(jbtOk);
p2.add(jbtCancel);
JPanel p5 = new JPanel(new BorderLayout());
p5.add(p2, BorderLayout.CENTER);
p5.add(jlblStatus, BorderLayout.NORTH);
jlblStatus.setForeground(Color.RED);
jlblStatus.setHorizontalAlignment(SwingConstants.CENTER);
setLayout(new BorderLayout());
add(p1, BorderLayout.CENTER);
add(p5, BorderLayout.SOUTH);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
jbtOk.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (Arrays.equals("stackoverflow".toCharArray(), jpfPassword.getPassword())
&& "stackoverflow".equals(jtfUsername.getText())) {
parent.setVisible(true);
setVisible(false);
} else {
jlblStatus.setText("Invalid username or password");
}
}
});
jbtCancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setVisible(false);
parent.dispose();
System.exit(0);
}
});
}
}
I suggest you insert the following code:
JFrame f = new JFrame();
JTextField text = new JTextField(15); //the 15 sets the size of the text field
JPanel p = new JPanel();
JButton b = new JButton("Login");
f.add(p); //so you can add more stuff to the JFrame
f.setSize(250,150);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Insert that when you want to add the stuff in. Next we will add all the stuff to the JPanel:
p.add(text);
p.add(b);
Now we add the ActionListeners to make the JButtons to work:
b.addActionListener(this);
public void actionPerforemed(ActionEvent e)
{
//Get the text of the JTextField
String TEXT = text.getText();
}
Don't forget to import the following if you haven't already:
import java.awt.event*;
import java.awt.*; //Just in case we need it
import java.x.swing.*;
I hope everything i said makes sense, because sometimes i don't (especially when I'm talking coding/Java) All the importing (if you didn't know) goes at the top of your code.
Instead of adding the game directly to JFrame, you can add your content to JPanel (let's call it GamePanel) and add this panel to the frame. Do the same thing for login screen: add all content to JPanel (LoginPanel) and add it to frame. When your game will start, you should do the following:
Add LoginPanel to frame
Get user input and load it's details
Add GamePanel and destroy LoginPanel (since it will be quite fast to re-create new one, so you don't need to keep it memory).

java.awt.Container.checkNotAWindow error in simple gui

I am trying to draw a simple GUI (created with windowbuilder in eclipse), I want to have 2 buttons and a scrollable text area between them. I have created the following code to achieve the above:
public class Main extends JFrame implements ActionListener{
public Font font; //used for the font file
public JTextArea txtDataWillBe;
public Main() throws FontFormatException, IOException{
setTitle("Main title ");
setBounds(100, 100, 1200, 600);
getContentPane().setLayout(null);
txtDataWillBe = new JTextArea();
txtDataWillBe.setText("Your data will display here");
txtDataWillBe.setFont(new Font("Droid Sans", Font.BOLD, 18));
txtDataWillBe.setEditable(false);
txtDataWillBe.setColumns(1);
txtDataWillBe.setBounds(0, 40, 919, 484);
getContentPane().add(txtDataWillBe);
JButton button = new JButton("CLICK TO OPEN");
button.setBounds(0, 0, 940, 40);
button.setFont(new Font("Coalition", Font.PLAIN, 18));
getContentPane().add(button);
JButton btnPrint = new JButton("PRINT");
btnPrint.setBounds(0, 531, 940, 40);
btnPrint.setFont(new Font("Coalition", Font.PLAIN, 18));
getContentPane().add(btnPrint);
}
private final String JTextFile = null;
JFileChooser chooser;
String choosertitle;
public static File deletefile;
EDIT:
public static void main(String s[]) {
JFrame frame = new JFrame("Reader");
Main panel = null;
try {
panel = new Main();
} catch (FontFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
frame.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
File deleteme = new File (deletefile + "mx.txt");
deleteme.delete();
System.exit(0);
}
}
);
frame.getContentPane().add(panel,"Center");
frame.setSize(panel.getPreferredSize());
frame.setVisible(true);
}
I originally had the JTextarea inside of a JScrollPane (thinking that was the best way to get the scrolling I want working). I removed the JScrollPane thinking that was causing the console error, but I am still getting the error.
Console output is:
Exception in thread "main" java.lang.IllegalArgumentException: adding a window to a container
at java.awt.Container.checkNotAWindow(Container.java:439)
at java.awt.Container.addImpl(Container.java:1035)
at java.awt.Container.add(Container.java:923)
EDIT: Main added above.
What I am doing wrong with my GUI?
Do I need a JScrollPane and JTextArea to enable vertical scrolling of the loaded text?
Thanks for your help;
Andy
EDIT:
I have edited as per the suggestions below so my code now reads:
public Main() throws FontFormatException, IOException{
JFrame frame = new JFrame("Reader ");
frame.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
File deleteme = new File (deletefile + "mx.txt");
deleteme.delete();
System.exit(0);
}
}
);
frame.getContentPane().add(panel,"Center");
frame.setSize(getPreferredSize());
frame.setVisible(true);
The rest of the code is as before but all I am getting displayed is a blank grey frame without any of my components (although they are all showing in windowbuilder).
Thanks for the continued help.
The console output is describing exactly what is wrong here.
IllegalArgumentException: adding a window to a container
In the line frame.getContentPane().add(panel,"Center"); you add panel into your content pane, but panel itself is an instance of Main extends JFrame.
You should remove any reference to the outer frame at all and just add the window listener to the Main frame, i.e. the main code reduces to something like
JFrame frame = new Main();
frame.addWindowListener( ... );
frame.setVisible(true);
You may also want to move the addWindowListener part inside class Main.

JWindow does not receive events in Java 7 for Mac

See the sample code below. It simply creates a button and adds it to a window. But when *menu_item3* is selected, the ActionListener doesn't receive the event. This error only occurs on Java 7 for Mac. If I run this same code in Windows, it works fine. When I run this same code on Java 6 for Mac, it works fine. If I use a JFrame instead of JWindow, it works fine. I do not want to use a JFrame because I do not want to display the window title bar and border.
Any ideas?
public class SandBox {
public static JFrame frame = new JFrame();
public static JPopupMenu menu = new JPopupMenu();
public static JLabel button = new JLabel();
public static void main(String[] args) {
JFrame window = new JFrame();
JPanel panel = new JPanel();
JMenuItem menu_item1 = new JMenuItem("Item1");
JMenuItem menu_item2 = new JMenuItem("Item2");
JMenuItem menu_item3 = new JMenuItem("Item3");
menu.add(menu_item1);
menu.add(menu_item2);
menu.add(menu_item3);
menu.setEnabled(true);
button.setText("Button");
button.setBorder(BorderFactory.createMatteBorder(4, 4, 4, 4, new Color(255,0,0)));
button.setSize(100, 24);
button.add(menu);
button.setVisible(true);
button.setEnabled(true);
panel.add(button);
panel.setVisible(true);
window.add(panel);
window.setVisible(true);
window.setLocation(100, 100);
window.setAlwaysOnTop(true);
window.setFocusable(true);
window.setFocusableWindowState(true);
window.pack();
frame.setVisible(false);
button.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
menu.show(button, 0, 0);
}
});
menu_item3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JOptionPane.showMessageDialog(frame, "Eggs are not supposed to be green.");
}
});
}
}
I have submitted a bug with Oracle. Still waiting for their response whether the bug will be officially filed. I will update this answer when I do hear something.
In the mean time, I did find a viable workaround. I use a JFrame instead of a JWindow. I was unaware you can remove the window title and borders of a JFrame using the method setUndecorated(). Also be aware that this method can only be called while the frame isn't displayable.

Categories