I have the following code:
String firstName;
firstName = JOptionPane.showInputDialog("First Name");
String familyName;
familyName = JOptionPane.showInputDialog("Family Name");
With this code you will have 2 boxes popping up to fill in your name. However, I would like to know if there is a way of putting those two input boxes both on one popup.
Just create a panel containing two text fields and then just add the panel to the dialog :
JPanel p = new JPanel();
JTextField familyName = new JTextField(10);
JTextField firstName = new JTextField(10);
p.add(new JLabel("Family name :"));
p.add(familyName);
p.add(new JLabel("First name : "));
p.add(firstName);
JOptionPane.showConfirmDialog(null, p, "Family and first name : ", JOptionPane.OK_CANCEL_OPTION);
Here's what it looks like :
Add both of these JOptionPanel boxes to a single JFrame.
This way both of the input boxes will be on the same window.
JFrame frame = new JFrame.add(JOptionPanel);
No, You can't do this using JOptionPane library. you can write your own class using java.swing package that provide multiple input on single popup.
Related
I have a JTextArea in a JDialog. JDialog uses a GridLayout.
I would like to have 7 digits on each line of the JTextArea (each line will be a 7 int registration number). For user experience reasons, I would like the JTextArea to either add a new line or stop expanding when it reaches 7 characters on a line.
Things that didn't work :
- Specifying the number of columns in the JTextArea constructor
- matriculesText.setLineWrap(true); and matriculesText.setWrapStyleWord(true);
I'm afraid uploadDialogManager.setHgap(20); might be breaking the code. I'm wondering if the JDialog should rather have a fixed size.
This is how I construct my JDialog :
// initialization
Dialog uploadParent = null;
JDialog uploadDialog = new JDialog(uploadParent);
GridLayout uploadDialogManager = new GridLayout(UPLOAD_DIALOG_ROWS,
UPLOAD_DIALOG_COLUMNS);
// uploadDialog properties
uploadDialog.setSize(new Dimension(UPLOAD_DIALOG_WIDTH, UPLOAD_DIALOG_HEIGHT));
uploadDialog.setLayout(uploadDialogManager);
uploadDialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
//Set up the horizontal gap value
uploadDialogManager.setHgap(20);
//Set up the vertical gap value
uploadDialogManager.setVgap(20);
//Set up the layout of the buttons
//uploadDialogManager.layoutContainer();
// components initialization
JLabel exerciceLabel = new JLabel("exercice number : ");
JComboBox<Integer> exerciceNumbers = new JComboBox<Integer>
(EXERCICE_NUMBERS);
JLabel matriculeLabel = new JLabel("please enter your matricules, one per
line : ");
JTextArea matriculesText = new JTextArea(1, 1);
JButton confirm = new JButton("confirm");
JButton cancel = new JButton("cancel");
matriculesText.setLineWrap(true);
matriculesText.setWrapStyleWord(true);
I have made another solution that fills my requirements. Instead of going to a new line when 7 characters are reached, I use MATRICULE_REGEX to check if every line contains 7 digits (1\\d{6}). If it doesn't, I reject the JTextArea content.
private static final String MATRICULE_REGEX = "1\\d{6}(\\n1\\d{6})*";
Pattern matriculePattern = Pattern.compile(MATRICULE_REGEX);
Matcher matriculeMatcher = null;
matriculeMatcher = matriculePattern.matcher(text);
isValidMatricule = matriculeMatcher.matches();
The following is some code which makes multiple fields (items). I know that the parameter after new JTextField is the content of the text box, and I understand how item2, 3, and passwordField work, but do not understand item1. In the line of code:
item1 = new JTextField(10);
What does the (10) mean? I would expect there to be a default number inside that text box, but that is not the case. Any help would be appreciated.
public eventhandling(){
super("The title");
setLayout(new FlowLayout());
item1 = new JTextField(10);
add(item1); //Adds item to window
item2 = new JTextField ("Enter text here"); //Making a text box that has the words "enter text here" in it
add(item2);
item3 = new JTextField ("uneditable", 20);
item3.setEditable(false); //This text field cannot be changed now
add(item3);
passwordField = new JPasswordField ("mypass"); //Setting the password field with a default password : "mypass"
add(passwordField);
This is what i found from the Oracle Site
JTextField(int columns):
Constructs a new empty TextField with the specified number of columns.
First you need to understand that there are different ways to initialize a component. Then you also need to notice that there is a difference between "10" and 10. The first is a string, the second is an integer. That being said, if you want the number 10 to show in the JTextField box then you need to pass "10" in the constructor. If you pass 10 that is telling the constructor to set the 10 columns in the JTextField, that is, it restricts the number of characters that can be entered to 10. Check the API ...
http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextField.html
Thanks in advance for any help. So I've used input from JOptionPane many times before but this is confusing me. I only want to use the input from the paymentField which takes in ($0.00) a value from the user. Do I use an action listener for this and if so how or is there another way?
At the minute Im using showInputDialog but it brings up an extra unwanted text field. Also tried showConfirmDialog but couldnt seem to use what was entered.
//method used to display dialog box required add funds to wallet
public void getWalletBox() {
String[] cTypes = {"Maestro", "Visa Debit", "Mastercard", "American Express"};
JComboBox cardType = new JComboBox(cTypes);
cardType.setFont(new Font("Serifs", Font.BOLD, 16));
JTextField cardNumField = new JTextField(20); //width of text fields = 25
cardNumField.setFont(new Font("Serifs", Font.BOLD, 16));
//formats payment field using dollar prefix
NumberFormat paymentFormat = NumberFormat.getCurrencyInstance(Locale.US);
paymentField = new JFormattedTextField(paymentFormat);
paymentField.setValue(new Double(0.00));
paymentField.setFont(new Font("Serifs", Font.BOLD, 25));
paymentField.setEditable(true);
paymentField.setForeground(Color.green);
//array of objects used to add labels and fields to joptionpane
Object[] fields = {
"Card Type: ", cardType,
"Card Number: ", cardNumField,
"Add: ", paymentField
};
JOptionPane.showInputDialog(null, fields, "Wallet", JOptionPane.OK_CANCEL_OPTION);
}`
You have to define your own JDialog for that as that is much simple as compared to cutomize it using this method.
So I want to add some text to a window.
I added the text in a ArraList like this:
ArrayList<String> Text = new ArrayList<String>();
Text.add("text1");
Text.add("text2");
...
Text.add("text*n*");
I now want to add these items into a JFrame. Now, I am pretty new to programming, so there is probably a better solution than this. But here is what I tried (I am using a for loop, because I think this is also the easiest way for me to manage the bounds of the labels:
for(int i = 0; i<Text.size();i++){
JLabel jl = new JLabel(names.get(i));
jl.setBounds(50,100+20*i,200,50);
this.add(jl);
}
But only the last element in the ArrayList is added to the JFrame (text*n*). Not all of them.
How can I get every element in the arraylist to show in the jframe? Maybe I shouldn't use JFrame?
It sounds like you want to use a JList, not a grid of JLabel.
i.e.,
DefaultListModel<String> listModel = new DefaultListModel<String>();
JList<String> myJList = new JList<String>(listModel);
// assuming you have an array of String or ArrayList<String> called texts
for (String text : texts) {
listModel.addElement(text);
}
JScrollPane listScrollPane = new JScrollPane(myJList);
// then add the listScrollPane to your GUI
Also:
Please learn and follow Java naming rules. Variable names should begin with a lower case letter, so "text" not Text.
And you should know that every time someone uses a null layout and setBounds(...) a puppy dies. Please don't be cruel to puppies, and don't create rigid hard to maintain and upgrade GUI's. Learn and use the Swing layout managers. You won't regret this, and neither will the puppies.
You need a layout, otherwise they are added on top of each other. Try adding everything to a JPanel and only add the panel to the frame at the end.
JFrame frame = new JFrame("title");
JPanel panel = new JPanel();
// Y_AXIS means each component added will be added vertically
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
for (String str : Text) {
JLabel j1 = new JLabel(str);
panel.add(j1);
}
frame.add(panel);
frame.pack();
frame.setVisible(true);
Try with Replace names.get(i) as Text.get(i)
OR Try,
for(String str : Text){
JLabel jl = new JLabel(str);
}
Try this:
String output = "";
for(int i = 0; i<Text.size();i++)
{
output += Text.get[i] + "\n";
}
JLabel jl = new JLabel(output);
This will create a string named output that will add the text from each index, followed by creating a new line. Then at the end, the full string will be added to the JLabel. The only downside to this method is that one label will contain ALL of the text.
JLabel jl = new JLabel(names.get(i));
Here you always construct a new object for j1, and after the loop you just have the latest object.
So I've been learning Java for the very first time and it's time for me to attempt my first project. And I'm stuck at the "first hurdle" haha.
The issue I have is the fact that I don't actually know how to space J Items apart.
I have a 250,350 window for a Log In form with a JLabel, a JTextField for username and JLabel JPassword for Password with a JButton at the bottom.
What I want to do now is style it so that the spacing between the top and the bottom of the form makes it so that the form is centered as well as adding a line's height space between the JLabel and the JTextField. (Basically a \n type deal but that isn't working.)
Hopefully this makes sense, if not, I apologise and I'll try to rephrase/add code!
public Game() {
this.setSize(250,350);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Sticket Cricket - Login");
JPanel loginMenuPanel = new JPanel();
loginButton = new JButton("Login");
usernameField = new JTextField();
usernameField.setColumns(10);
passwordField = new JPasswordField();
passwordField.setColumns(10);
passwordField.requestFocus();
usernameLabel = new JLabel("Username: ");
passwordLabel = new JLabel("Password: ");
this.add(loginMenuPanel);
loginMenuPanel.add(usernameLabel);
loginMenuPanel.add(usernameField);
loginMenuPanel.add(passwordLabel);
loginMenuPanel.add(passwordField);
loginMenuPanel.add(loginButton);
this.setVisible(true);
}
Short Answer:
Create a JPanel, set the layoutmanger of the panel (some examples, GridLayout, BorderLayout, Check out the tutorial here where more of these are explained)
Then add your components to this panel accordingly
For the layout you are looking for it would possibly be easier to use an IDE to create this, I find Net Beans to be the easiest for doing this.
My recommendation would be for you to create a JPanel with a grid layout of 2 columns and 2 rows, to this add you JLabels and Text fields for the logon name and password.
Then create another JPanel possibly BorderLayout or Flow Layout and add the above panel to this then add this parent panel to the frame.