I have a dialog for a client-GUI that asks for the IP and Port of the server one wants to connect to. I have everything else, but how would I make it so that when the user clicks "OK" on my dialog box, that it runs something? Here's what I have so far:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class ClientDialog {
JTextField ip = new JTextField(20);
JTextField port = new JTextField(20);
GUI gui = new GUI();
Client client = new Client();
JOptionPane optionPane;
public void CreateDialog(){
Object msg[] = {"IP: ", ip, "\nPort: ", port};
optionPane = new JOptionPane();
optionPane.setMessage(msg);
optionPane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
JDialog dialog = optionPane.createDialog(null, "Connect to a server");
dialog.setVisible(true);
if(dialog == JOptionPane.OK_OPTION){
System.out.println(ip);
String ipMsg = ip.getText();
int portMsg = Integer.parseInt(port.getText());
gui.CreateConsole(client, ipMsg, portMsg);
}
}
} //End class
I know that the code isn't correct, but what I want is that when the user hits "OK" on the dialog, I can run some code. Thanks!
I'd suggest to use showConfirmDialog instead
int result = JOptionPane.showConfirmDialog(myParent, "Narrative",
"Title", JOptionPane.INFORMATION_MESSAGE);
and there you can test for various returns value from JDialog/JOptionPane
if (result == JOptionPane.OK_OPTION,
JOptionPane.CANCEL_OPTION,
JOptionPane.CLOSED_OPTION, etc..
I'd suggest creating a JPanel and using JOptionpane.showConfirmDialog() (or even JOptionPane.showOptionDialog() to display the dialog and retrieve the option. Here's a modification of your code as an example:
import java.awt.*;
import javax.swing.*;
class ClientDialog {
private JTextField ip = new JTextField(20);
private JTextField port = new JTextField(20);
private JOptionPane optionPane;
private JPanel panel;
public void CreateDialog(){
panel = new JPanel(new GridLayout(2, 2));
panel.add(new JLabel("IP"));
panel.add(ip);
panel.add(new JLabel("Port"));
panel.add(port);
int option = JOptionPane.showConfirmDialog(null, panel, "Client Dialog", JOptionPane.DEFAULT_OPTION);
if (option == JOptionPane.OK_OPTION) {
System.out.println("OK!"); // do something
}
}
}
public class Test {
public static void main(String args[])
{
ClientDialog c = new ClientDialog();
c.CreateDialog();
}
}
Damn, took too long to post. Anyway just design the layout of the JPanel as you would for any other sort of frame.
Please understand that the 2nd parameter in a JOptionPane, the object parameter, can be any Swing component including a JPanel that holds a simple or complex GUI.
Consider creating a JPanel, placing a few components in it including JLabels and two JTextFields, one for IP, one for port, and then displaying this JPanel in a JOptionPane. Then you can easily check if OK has been pressed and act accordingly.
import javax.swing.*;
public class OptionEg {
public static void main(String[] args) {
final JTextField ipField = new JTextField(10);
final JTextField portField = new JTextField(10);
JPanel panel = new JPanel();
panel.add(new JLabel("IP:"));
panel.add(ipField);
panel.add(Box.createHorizontalStrut(15));
panel.add(new JLabel("Port:"));
panel.add(portField);
int result = JOptionPane.showConfirmDialog(null, panel,
"Enter Information", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
System.out.println("IP: " + ipField.getText());
System.out.println("Port: " + portField.getText());
}
}
}
Good solutions.
If you want not to use something else, this is a working example:
1) set DO_NOTHING_ON_CLOSE to ensure user MUST press OK
2) verify if the JDialog is still visible.
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dialog.setModal(false);
dialog.setVisible(true);
dialog.setAlwaysOnTop(true);
while(dialog.isVisible())try{Thread.sleep(50);}
catch(InterruptedException e){}
This can be a solution if you want to implement a non-modal dialog box.
Related
I'm trying to create a name generator that generates names by random.
Now when i click the button, it generates a name, but it shows up in the Eclipse console and not in the same window as the button, which is what I want it to do.
Eventually I would like to be able to have a specific picture for for the button and for the background (window/frame). Also, as a bonus I'm hoping to add a bit of music to it that can play in the background once you open the app.
Now, I'm fairly new to java and I've only watched a couple of tutorials, but it's gotten me this far and hopefully I can learn a thing or two from one of you guys.
So please be kind, Best regards leal.
import javax.swing.*;
import javax.swing.JFrame;
import java.awt.*;
import java.awt.event.*;
public class ClanNameGenerator {
public static void main (String[] args){
JFrame frame = new JFrame("ExETesT");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,350);
JPanel panel = new JPanel ();
frame.add(panel);
JButton button = new JButton("Click me");
panel.add(button);
button.addActionListener(new Action());
}
static class Action implements ActionListener{
public void actionPerformed (ActionEvent e){
String[] names = {"test", "Zero", "Club", "Moonkys", "znakes", "SeamOnster", "dnktwhm", "Rambo", "OmG", "siste"};
String[] names2 = {"Ylos", "zzzzz", "sdsd", "OK"};
String[] names3 = {"Hei", "ok", "jadd", "så drar vi", "det var det"};
int random = (int) (Math.random()*names.length);
int random2 = (int) (Math.random()*names2.length);
int random3 = (int) (Math.random()*names3.length);
System.out.println("Your clan name is: " + names[random] +" "+ names2[random2] +" "+ names3[random3]);
}
}
}
if you do something like this, the name will appear in JFrame:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ClanNameGenerator {
private static JLabel label;
public static void main (String[] args){
JFrame frame = new JFrame("ExETesT");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,350);
JPanel panel = new JPanel ();
frame.add(panel);
JButton button = new JButton("Click me");
panel.add(button);
label = new JLabel();
panel.add(label);
button.addActionListener(new Action());
}
static class Action implements ActionListener{
public void actionPerformed (ActionEvent e){
String[] names = {"test", "Zero", "Club", "Moonkys", "znakes", "SeamOnster", "dnktwhm", "Rambo", "OmG", "siste"};
String[] names2 = {"Ylos", "zzzzz", "sdsd", "OK"};
String[] names3 = {"Hei", "ok", "jadd", "så drar vi", "det var det"};
int random = (int) (Math.random()*names.length);
int random2 = (int) (Math.random()*names2.length);
int random3 = (int) (Math.random()*names3.length);
label.setText("Your clan name is: " + names[random] +" "+ names2[random2] +" "+ names3[random3]);
}
}
}
There's a lot going on in your question without you actually asking any questions. As for your text problem though, System.out.println(); will always print to the console, wherever it may be. To add it to the JFrame, you have a variety of options. The one you probably want is to use a JLabel, unless you have a lot of text, in which case a JTextArea may be better suited, or if you intend to do something a little fancier than regular text you may want to draw it directly using the Graphics class and drawString(String).
How to add text to JFrame?
As for the other parts of your... "question," do some research and try things before asking for help on the Stack. This community is for assisting you when things don't work, not for writing your projects for you.
Add a JLabel to your UI, then call the setText method of that JLabel object.
jLabelObject.setText("Your clan name is: " +
names[random] +" "+ names2[random2] +" "+ names3[random3);
Hello I have a problem with my comboBox. In app that im making my panel has a combo box with two choices and a button next to the combo box to proceed to the choice selected in the combo box but instead both if Statements run and no I have no idea why.
Combo box code is simple private JComboBox mainChoice = new JComboBox();
mainChoice.addItem("") etc...
class mainPanelGoButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
String choice = (String)mainChoice.getSelectedItem();
System.out.printf(choice);
if(choice == "View Passenger Details");
{
JTextField first = new JTextField();
JTextField last = new JTextField();
Object[] message = {
"First Name:", first,
"Last Name:", last
};
int option = JOptionPane.showConfirmDialog(null, message, "Enter passenger name", JOptionPane.PLAIN_MESSAGE);
if (option == JOptionPane.OK_OPTION)
{
// Load passenger data
p = dataHandler.getPassengerData(first.getText(), last.getText());
if(p != null)
{
updateTextfields( p);
// Display passenger data
getContentPane().removeAll();
getContentPane().add(passengerDetailsPanel);
setSize(400,340);
setLocationRelativeTo(null);
validate();
repaint();
printAll(getGraphics());
}
}
}
if(choice == "Add New Passenger")
{
if(displayPassengerInputForm());
{
// Display passenger data
getContentPane().removeAll();
getContentPane().add(passengerDetailsPanel);
setSize(400,340);
setLocationRelativeTo(null);
validate();
repaint();
printAll(getGraphics());
}
}
}
}
// EXAMPLE OF MY PROGRAM THAT RETURNS BOTH WINDOW A and WINDOW B
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Frame extends JFrame
{
private JPanel mainPanel = new JPanel();
private JComboBox<String> mainChoice = new JComboBox<String>();
private JButton goButton = new JButton("GO");
public Frame()
{
createMainPanel();
this.add(mainPanel);
}
private void createMainPanel()
{
// Fill choice box
mainChoice.addItem("Find Passenger");
mainChoice.addItem("Add New Passenger");
// Set button
goButton.addActionListener(new mainPanelGoButtonListener());
goButton.setPreferredSize(new Dimension(5,5));
// Add to main panel
mainPanel.setLayout(new GridLayout(1,2,4,4));
mainPanel.add(mainChoice);
mainPanel.add(goButton);
}
class mainPanelGoButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
if(mainChoice.getSelectedItem().equals("Find Passenger"));
{
// DISPLAYS WINDOW FOR INPUT
System.out.printf(" WINDOW A ");
}
if(mainChoice.getSelectedItem().equals("Add New Passenger"));
{
// DISPLAYS WINDOW FOR INPUT
System.out.printf(" WINDOW B ");
}
}
}
public static void main(String args[])
{
Frame frame = new Frame();
frame.setTitle("SSD Project");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setSize(400,50);
frame.setVisible(true);
}
}
Each time I press a button it prints out both Window A and Window B instead of one
One problem I see is that you use == to compare Strings.
Don't use == to compare Strings as this compares if two String objects are the same, something that you are not interested in testing. Use the equals(...) or equalsIgnoreCase(...) method which tests if two Strings contain the same characters, in the same order, with or without the same case respectively, and this is what you are really interested in.
Next: be sure you use if (something) { xxxx } else if (somethingElse) { xxxx } to be sure that only one if block gets performed.
Next: look up the CardLayout which will allow your GUI to change views much more cleanly.
Edit
You ask:
do you mean: mainChoice.getSelectedItem().equals("Add New Passenger") ?? cause im still getting the same result ;
Yes, exactly. But on further reflection, your code above cannot be causing both if blocks to fire as the String == can't be true for both test Strings. Something else is causing your problem.
could you give me some quick example?
Actually it would be better if you could create and post a minimal runnable program that reproduces your problem for us.
im training with GUI in Java. So I started creating pet game prototype or smth similar like game.
I have created menu to choose what to do, Register, Info, or Exit aplication.
Created fields and dorpdownBox to choose everything for register.
Also made sumbit button(its very start so i added just max characters validation on petName).
Now im stucked, i dont know how to take all information from dropdownBox and textbox that has been chosen and sent to other class Pet. I have googled but havent found anything that would be clear.
Maybe someone could give me some tips or write part for my code.
I want to take selected PetName , PetType, PetGender to other class pet.
P.s. i have copied many lines from google so I understand only 80-90% my code.
Main.java
import javax.swing.*;
import java.awt.Choice;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.*;
public class Main extends JFrame implements ActionListener {
public static void main (String []args){
new Main("Meniu"); // Create title
}
// Main class constructor
public Main(String title) {
super(title);
setMenu(); //create menu
setSize(300, 400);// size
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // close running program if window are closed
setLocationRelativeTo(null); // set window position at center
setResizable(false); //resizable or not
show();
}// Main class constructor
// menu choices
JMenuItem Registration, Apie, Exit;
// menu method for creation and style
private void setMenu() {
JMenuBar barObj = new JMenuBar(); // create menuBar obj
JMenu messagesObj = new JMenu("Meniu"); //create menu bar menu object
barObj.setBackground(Color.YELLOW); // set menu bar bg color
Registration = new JMenuItem("Registration");
Registration.setToolTipText("Push to register"); // write text when u hang mouse over
Registration.addActionListener(this);
Registration.setBackground(Color.WHITE); // set menu bar menu options bg color
messagesObj.add(Registration); // add Registration into messages
Apie = new JMenuItem("Apie");
Apie.setToolTipText("Push for information");
Apie.addActionListener(this);
Apie.setBackground(Color.WHITE);
messagesObj.add(Apie);
Exit = new JMenuItem("Exit");
Exit.setToolTipText("Here you will exit");
Exit.addActionListener(this);
Exit.setBackground(Color.WHITE);
messagesObj.add(Exit);
barObj.add(messagesObj);
setJMenuBar(barObj);
} //create menu end
// implemented method
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == Registration){
int registReply = JOptionPane.showConfirmDialog(this, "Norite registruotis?",
"Išeiti", JOptionPane.YES_NO_OPTION);
if(registReply == JOptionPane.YES_OPTION){ //registReply is what u have choosen
petRegistration ();
}
}else if (e.getSource() == Apie)
JOptionPane.showMessageDialog(this, "Jus esate informacijos lange.", "Apie", JOptionPane.PLAIN_MESSAGE);
else if (e.getSource() == Exit){
int exitReply = JOptionPane.showConfirmDialog(this, "Ar norite Exit?",
"Išeiti", JOptionPane.YES_NO_OPTION);// exitReply is what u have choosen
if(exitReply == JOptionPane.YES_OPTION){// if its has been chose/ program will shutdown
System.exit(0);
}
} // if end
}// actionPerformed
public void petRegistration(){
Container container = getContentPane();
// petName textbox and label
JTextField jtfRegLabel = new JTextField("***Registration***", 25);
jtfRegLabel.setHorizontalAlignment(JTextField.CENTER);
jtfRegLabel.setEditable(false);
JTextField jtfText1 = new JTextField(7);
JTextField jtfNameLabel = new JTextField("Pet Name (min 3, max 16 letters)", 17);
jtfNameLabel.setEditable(false);
jtfText1.setDocument(new JTextFieldLimit(16)); // add limit to text box
// pettype combobox and label
Frame frame = new Frame("Choice");
Label label = new Label("What is your Choice:");
Choice choice = new Choice();
frame.add(choice);
choice.add("Cat ");
choice.add("Dog ");
choice.add("Fish ");
choice.add("Mouse ");
choice.add("Bird ");
choice.add("Horse ");
JTextField jtfTypeLabel = new JTextField("Pet Type, Choose one ", 17);
jtfTypeLabel.setEditable(false);
// petGender combobox and label
Choice choice1 = new Choice();
frame.add(choice1);
choice1.add("Male ");
choice1.add("Female ");
JTextField jtfGenderLabel = new JTextField("Pet Gender, Choose one ", 17);
jtfGenderLabel.setEditable(false);
// submit registration
JButton submitRegObj = new JButton("Submit");
container.add(jtfRegLabel);
container.add(jtfText1);
container.add(jtfNameLabel);
container.add(choice);
container.add(jtfTypeLabel);
container.add(choice1);
container.add(jtfGenderLabel);
container.add(submitRegObj);
container.setLayout(new FlowLayout());
setSize(300, 400); // set size of window
setVisible(true);// set it visible
}
}// Main clases end
Pet.java
public class Pet {
private String petName;
private String petType;
private String petGender;
public Pet(String petName, String petType, String petGender) {
super();
this.petName = petName;
this.petType = petType;
this.petGender = petGender;
}
}
I think JTextFieldLimit class is necessary. Its just make max characters validation.
Thanks.
Firstly, you are mixing frameworks. Swing and AWT components don't play well together. I'd highly recommend against using AWT components and stick to the Swing framework.
Secondly, don't use JTextFields for labels, that's what JLabel is for
Start by taking the fields that are used for registriation and add them to their own JPanel as class instance fields...
public class RegistrationPanel extends JPanel {
JTextField jtfName;
JComboBox cbType;
JComboBox cbSex;
// Constructor and other code //
}
Then, in your RegistrationPanel, provide appropriate setters and getters...
public String getPetName() {
return jtfName.getText();
}
public void setPetName(String name) {
jtfName.setText(name);
}
// Other setters and getters //
This way, when you need it, you can retrieve the values from the panel.
When the user selects the registration menu, you would create a new instance of this panel and add it to your frame. You could even make use of a CardLayout to help switch between views
To make life easier, use enum types for restricted values like type and sex.
I highly recommend that you take the time to read through
Creating a GUI with Swing
Enum Types
SO i am working on a project and i was trying to disable the frame and the field from the program so that only the window is front is this one being active
here is my code :
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class password
{
private static String password = "pass";
public static void main(String[]args) {
JFrame frame = new JFrame("Password");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,100);
JLabel label = new JLabel("Enter password");
JPanel panel = new JPanel();
frame.add(panel);
JPasswordField pass = new JPasswordField(10);
pass.setEchoChar('*');
pass.addActionListener(new AL());
panel.add(label, BorderLayout.WEST);
panel.add(pass, BorderLayout.WEST);
}
static class AL implements ActionListener
{
public void actionPerformed(ActionEvent e) {
JPasswordField input = (JPasswordField) e.getSource();
char [] passy = input.getPassword();
String p = new String(passy);
if (p.equals(password)){
JOptionPane.showMessageDialog(null, "Correct");
System.out.print("Welcome to Adam's Quirky program.");
}
else
JOptionPane.showMessageDialog(null, "Incorrect");
}
}
}
the program i am currently using to program is Eclipse.
I'd take a look at a modal dialog.
Either use a JOptionPane or roll your own.
If these don't suit your needs, try taking a look at JLayer (Java 7) or JXLayer (Java 6 and below)
Have a look at LockableUI (It's a little out of date, but the basic idea is the same)
If that doesn't appeal, you could use a "blocking glass pane"
Take a look at
glassPane is not blocking input
Is there a problem with this blocking GlassPane?
as some examples
I'm learning Java and GUI. I have some questions, and the first is if there are any major difference between creating a subclass of JFrame and an instance of JFrame. It seems like like a subclass is more powerful? I also wonder if it's necessary to use this code when creating a GUI:
Container contentPane = getContentPane();
contentPane.setLayot(new Flowlayout());
I add my GUI class, it's a simple test so far, to a task that I have to hand in. When a user has entered some text in the textfield and press the button to continue to the next step, how do I do to clear the frame and show a new content or is there a special way to do this is in Java? I guess there must be better to use the same window instead of creating a new!? Help id preciated! Thanks
// Gui class
import java.awt.FlowLayout; // layout
import java.awt.event.ActionListener; // listener
import java.awt.event.ActionEvent; // event
import javax.swing.JFrame; // windows properties
import javax.swing.JLabel; // row of text
import javax.swing.JTextField; // enter text
import javax.swing.JOptionPane; // pop up dialog
import javax.swing.JButton; // buttons
// import.javax.swing.*;
public class Gui extends JFrame {
private JLabel text1;
private JTextField textInput1;
private JTextField textInput2;
private JButton nextButton;
// constructor creates the window and it's components
public Gui() {
super("Bank"); // title
setLayout(new FlowLayout()); // set default layout
text1 = new JLabel("New customer");
add(text1);
textInput1 = new JTextField(10);
add(textInput1);
nextButton = new JButton("Continue");
add(nextButton);
// create object to handle the components (action listener object)
frameHandler handler = new frameHandler();
textInput1.addActionListener(handler);
nextButton.addActionListener(handler);
}
// handle the events (class inside another class inherits contents from class outside)
private class frameHandler implements ActionListener {
public void actionPerformed(ActionEvent event){
String input1 = "";
// check if someone hits enter at first textfield
if(event.getSource() == textInput1){
input1 = String.format(event.getActionCommand());
JOptionPane.showMessageDialog(null, input1);
}
else if(event.getSource() == nextButton){
// ??
}
}
}
}
This small code might help you explain things :
import java.awt.event.*;
import javax.swing.*;
public class FrameDisplayTest implements ActionListener
{
/*
* Creating an object of JFrame instead of extending it
* has no side effects.
*/
private JFrame frame;
private JPanel panel, panel1;
private JTextField tfield;
private JButton nextButton, backButton;
public FrameDisplayTest()
{
frame = new JFrame("Frame Display Test");
// If you running your program from cmd, this line lets it comes
// out of cmd when you click the top-right RED Button.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel1 = new JPanel();
tfield = new JTextField(10);
nextButton = new JButton("NEXT");
backButton = new JButton("BACK");
nextButton.addActionListener(this);
backButton.addActionListener(this);
panel.add(tfield);
panel.add(nextButton);
panel1.add(backButton);
frame.setContentPane(panel);
frame.setSize(220, 220);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
JButton button = (JButton) ae.getSource();
if (tfield.getText().length() > 0)
{
if (button == nextButton)
{
/*
* this will remove the first panel
* and add the new panel to the frame.
*/
frame.remove(panel);
frame.setContentPane(panel1);
}
else if (button == backButton)
{
frame.remove(panel1);
frame.setContentPane(panel);
}
frame.validate();
frame.repaint(); // prefer to write this always.
}
}
public static void main(String[] args)
{
/*
* This is the most important part ofyour GUI app, never forget
* to schedule a job for your event dispatcher thread :
* by calling the function, method or constructor, responsible
* for creating and displaying your GUI.
*/
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new FrameDisplayTest();
}
});
}
}
if you want to switch (add then remove) JComponents, then you have to
1) add/remove JComponents and then call
revalidate();
repaint()// sometimes required
2) better and easiest choice would be implements CardLayout
If your requirement is to make a wizard, a panel with next and prev buttons, and on clicking next/prev button showing some component. You could try using CardLayout.
The CardLayout manages two or more components (usually JPanel instances) that share the same display space. CardLayout let the user choose between the components.
How to Use CardLayout
If your class extends JFrame, you can do:
getContentPane().removeAll();