Selectable alternative to JOptionPane.showMessageDialog - java

Backgorund info:
I have a buddy of mine in the Navy, and he wanted to know if I could whip him up a small app that would calcualte when he has his guard duty, because apparently counting on a calendar is hard. I used JOptionPane.showMessageDialog to give him the output of the dates. Here's how I'm doing that.
GregorianCalendar knownDate = new GregorianCalendar(year,month,day);
GregorianCalendar[] futureDates = new GregorianCalendar[10];
for(int i = 0; i < 10; i++) {
futureDates[i] = new GregorianCalendar(year,month,day);
futureDates[i].add(Calendar.DAY_OF_MONTH,10*(i+1)); // duty every 10 days
}
String newline = System.getProperty("line.separator");
StringBuilder sb = new StringBuilder("Jakes duty dates:").append(newline);
for(GregorianCalendar d : futureDates) {
sb.append(months[d.get(Calendar.MONTH)]).append(" ");
sb.append(d.get(Calendar.DAY_OF_MONTH)).append(newline);
}
JOptionPane.showMessageDialog(null,sb.toString());
The 'only problem' is you can't select the text that is displayed. He'd like to select it for IM and email, because what's the point in only being half lazy, right? (Only problem is in quotes because I have a feeling he'll scope creep this to death... haha)
My question:
Is there a "one-line solution" to making a selectable showMessageDialog?

I was able to build on trashgod's answer. While he suggested using a JList, I'm instead using a JTextArea (which gives the kind of selection I need.)
Here's what I'm doing:
JTextArea text = new JTextArea(sb.toString());
JOptionPane.showMessageDialog(null,text);
And it's working like a charm!
================================================
After a little experimentation I did this:
DefaultListModel model = new DefaultListModel();
for(GregorianCalendar g : futureDates) {
String m = months[g.get(Calendar.MONTH)];
String d = String.valueOf(g.get(Calendar.DAY_OF_MONTH));
model.addElement(m + " " + d);
}
JList jlist = new JList(model);
JOptionPane.showMessageDialog(null,jlist);
JOptionPane.showMessageDialog(null,jlist.getSelectedValue());
And the second box displayed what I had selected on the first one. I was really impressed with that. Now granted, this isn't the functionality I was going for (the top section is) but that doesn't make it any less awesome! :-)

Add the dates to a DefaultListModel, create a JList, and pass the list to showMessageDialog(). It's more than one line, but the selection copies to the clipboard using the platform's copy keystroke.
private static final DateFormat df = new SimpleDateFormat("dd-MMM");
private static void createAndShowGUI() {
DefaultListModel dlm = new DefaultListModel();
for (int i = 0; i < 10; i++) {
GregorianCalendar knownDate = new GregorianCalendar();
knownDate.add(Calendar.DAY_OF_MONTH, 10 * i);
dlm.add(i, df.format(knownDate.getTime()));
}
JList list = new JList(dlm);
JOptionPane.showMessageDialog(null, list);
}

Related

How to code a function that randomly selects a quote from an array? - Android Java

I am following an android coding tutorial and am try to make the quote selection random. Below is the unaltered code.
final ArrayList<Quote> quoteList = new ArrayList<Quote>();
Quote quote1 = new Quote("Would I rather be feared or loved? Easy. Both. I want people to fear how much they love me.", "Michael Scott");
quoteList.add(quote1);
Quote quote2 = new Quote("I'm not superstitious. But I am a little stitious.", "Michael Scott");
quoteList.add(quote2);
Quote quote3 = new Quote("I like waking up to the smell of bacon.", "Michael Scott");
quoteList.add(quote3);
Quote quote4 = new Quote("Wikipedia is the best thing ever. Anyone in the world can write anything they want about any subject. So you know you are getting the best possible information.", "Michael Scott");
quoteList.add(quote4);
Quote quote5 = new Quote("Mo' money, mo' problems.", "Michael Scott");
quoteList.add(quote5);
Quote quote6 = new Quote("SWAG! Stuff We All Get.", "Michael Scott");
quoteList.add(quote6);
Quote quote7 = new Quote("You just gots to get your freak on.", "Michael Scott");
quoteList.add(quote7);
Quote quote8 = new Quote("We're all homos. Homo sapiens.", "Michael Scott");
quoteList.add(quote8);
Quote quote9 = new Quote("Hate to see you leave but love to watch you go. 'Cause of your butt.", "Michael Scott");
quoteList.add(quote9);
Quote quote10 = new Quote("If a baby were president, there would be no taxes, there would be no war.", "Michael Scott");
quoteList.add(quote10);
//Add more quotes here
touch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (count < quoteList.size()) {
Quote q = quoteList.get(count);
quoteText.setText(q.getQuote());
personText.setText(q.getPerson());
count = count + 1;
} else{
count = 0;
}
}
});
}
If anyone could explain how to make the app randomly select a quotew when the screen is touched, instead og going through them one by one, I would really appreciate it.
You have to generate a random number between 0 and however long your list is
Random rand = new Random()
int n = rand.nextInt(quoteList.size() - 1);
Then use get the quote at that index
Quote random = quoteList.get(n);
Random random = new Random();
int randomNum = random.nextInt(quoteList.size() - 1);
Quote randomQuote = quoteList.get(randomNum);
String yourString = quoteList[new Random().nextInt(quoteList.length)];
To randomly select a quote:
int randomNum = (int)(Math.random()*(quoteList.size() - 1));
Quote randomQuote = quoteList.get(randomNum);

Returning object name with object values

Im really not sure as how to word this question. But im gonna try my best here. Bear with me if you could :)
I have a database with 3 tables (that i am dealing with right now). Fortunately they all have the same amount of columns. Im trying to input values into them using a "popup" form. (Not sure how to do that, but im using this link here as a guideline, and hoping it works)
Here is the code i have written for that method so far..
public form(int option, String val1, String val2, String val3, String val4, String val5)
{
val1 = null;
val2 = null;
val3 = null;
val4 = null;
val5 = null;
JTextField val1Field = new JTextField(20);
JTextField val2Field = new JTextField(20);
JTextField val3Field = new JTextField(20);
JTextField val4Field = new JTextField(20);
JTextField val5Field = new JTextField(20);
String name;
String lbl1 = null;
String lbl2 = null;
String lbl3 = null;
String lbl4 = null;
String lbl5 = null;
switch(option)
{
case 1: //if customer
name = "Customer Information";
lbl1 = "Customer No:";
lbl2 = "Customer Name:";
lbl3 = "Company Name:";
lbl4 = "Contact Number: ";
lbl5 = "Discount Rate:";
case 2: //if item
name = "Item Information";
lbl1 = "Item No:";
lbl2 = "Item Name:";
lbl3 = "Cost Price:";
lbl4 = "Selling Price: ";
lbl5 = "Stock:";
case 3: //if user
name = "Staff Information";
lbl1 = "Staff ID:";
lbl2 = "Full Name:";
lbl3 = "Username:";
lbl4 = "Password: ";
lbl5 = "adminusercheck:";
default:
JOptionPane.showMessageDialog(alphaPOS,
"Something went wrong! Try again!",
"ERROR",
JOptionPane.ERROR_MESSAGE);
}
JPanel formPanel = new JPanel();
formPanel.add(new JLabel(lbl1));
formPanel.add(val1Field);
formPanel.add(Box.createHorizontalStrut(15)); // a spacer
formPanel.add(new JLabel(lbl2));
formPanel.add(val2Field);
formPanel.add(Box.createHorizontalStrut(15)); // a spacer
formPanel.add(new JLabel(lbl3));
formPanel.add(val3Field);
formPanel.add(Box.createHorizontalStrut(15)); // a spacer
formPanel.add(new JLabel(lbl4));
formPanel.add(val4Field);
formPanel.add(Box.createHorizontalStrut(15)); // a spacer
formPanel.add(new JLabel(lbl5));
formPanel.add(val5Field);
formPanel.add(Box.createHorizontalStrut(15)); // a spacer
int result = JOptionPane.showConfirmDialog(null, formPanel,
name, JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION)
{
val1 = val1Field.getText();
val2 = val2Field.getText();
val3 = val3Field.getText();
val4 = val4Field.getText();
val5 = val5Field.getText();
}
return(option, val1, val2, val3, val4, val5);
}
Now.. it took me a while to realize that i cannot return values like that, and that i could instead return the object instead. I have a class made for each of these "tables" (Item, Customer and Staff).
But.. the thing is in the method above i need to use a switch so that i can have the labels made according to the type of Table.
So my question is, is there a way to pass the object and its name into the method? Or do i have it all wrong?
Any help is much appreciated.
It looks to me like you don't really need to return option since you never change it. Also, it looks like you were trying to have the caller pass variables into the method and let the method fill in the values of those variables. But Java doesn't have "output" or "reference" parameters the way C++ and PHP do, so this doesn't work. (You can pass in a reference to a mutable object and have a method set a field in that object, but you can't do that with String since it's immutable.)
If that's the case, then since the 5 things you want to return are all the same type, you could just make your method return a String[]:
public String[] form(int option)
{
String[] values = new String[] (5);
//values[0] = null; // not necessary since the array elements will already be null
//values[1] = null; ...
...
if (result == JOptionPane.OK_OPTION)
{
values[0] = val1Field.getText();
values[1] = val2Field.getText();
values[2] = val3Field.getText();
values[3] = val4Field.getText();
values[4] = val5Field.getText();
}
return values;
}
P.S. I recommend using arrays or ArrayList instead of separate variables like val1Field, val2Field, etc., so that you don't have to repeat code like this.
While there is a way to kind of do this, I would like to point out that this is not a good design! Don't generalize methods! I think that you need to try to redesign your code instead. If one of your classes changes, you will end up breaking them up anyway. Create a handler for each form type. You can do this using Factory pattern and then get the appropriate form, based on that. Might be a bit more work, but you will thank me later :)
If you need help on design, then that is something that we can definitely discuss.

Saving a JComboBox Selection to an ArrayList

I cannot retrieve the selection in the JComboBox that was selected by the user. the J ComboBox inclued a list of car registration numbers, which then the user has to select one and it will be added to the booking ArrayList. Unfortunately it is not working properly. and the booking is not being saved because of this. Please Help Me! Maybe I need to change the get Method for the combo box.
ArrayList BookingList = CarRentalSystem.BookingList;
ArrayList CarList = CarRentalSystem.CarList;
UsingFiles BookingFile = CarRentalSystem.BookingFile;
String [] regNums;
public NewBooking() {
regNums = new String[CarList.size()+1];
for (int i = 0; i< CarList.size();i++){
regNums[i] = ""+((Car)CarList.get(i)).getCarNum();
}
initComponents();
....
Booking book = new Booking();
String regNum = cmbCar.getActionCommand();
book.getRegNum();
Not easy to understand what u want can you add more code?
try this to convert your list into a String Array that u pass in as a argument to your combobox.
public String[] regNums() {
String tArray[] = null;
for (int i=0; i<carList.size(); i++){
//Convert into a String[] and put the arrayList values in it.
tArray = carList.toArray(new String[i]);
}
}

JAVA Macros for Android Use (Does such exist?)

I have been using VFP 8.0 for quite sometime and one of the most thing I enjoyed about it is the macro function;
name = "Paul James"
age = 25
result = My name is &name, I am &age years old.
I could also do,
dimension x[5];
x[0] = "box"
x[1] = "area"
text.&x[0]..text = "textbox" ---> textbox.text="textbox"
text.&x[1]..text = "textarea" ---> textarea.text="textarea"
That's with the FoxPro thing, I seem to have grown attached to it and am somewhat inclined wishing such exist with OOs Languages like Java (or it really does, im just missing some extra research?), anyway, I wanted to have something like that here's my problem;
I have a JSON Array, which I get all names of the response and store it in a temporary array by using the "names()" method provided in the android code factory.
Purposely, I want to create an array for each name in the temporary array that was created from the method;
To illustrate;
JSONArray response =
[{"name":"a","middlename":"aa","surname":"aaa"},{"name":"b","middlename":"bb","surname":"bbb"},{"name":"c","middlename":"cc","surname":"ccc"}]
temp[] = [{name,middlename,surname}];
Desired Output:
String[] name = new String[response.firstobject.length];
String[] middlename = new String[response.firstobject.length];
String[] surname = new String[response.firstobject.length];
Here's my actual code; The JSON Parser
#SuppressWarnings("null")
public ArrayList<String> parseJson(JSONArray ja) throws JSONException{
ArrayList<String> listItems = new ArrayList<String>();
String[] temp = null;
//Get all the fields first
for (int i=0; i<=0; ++i){
JSONObject jo = ja.getJSONObject(i);
if(jo.length()>0){
temp = new String[jo.names().length()];
for(int x=0; x<jo.names().length(); ++x){
temp[x] = jo.names().getString(x);
}
}
}
}
So I'm kinda stuck in the desired output, is this possible in the first place? Why I'm doing this, is that because I wanted to create a generic JSON response method; So that I don't have to remember all the names of the response just to use them. Im looking for a java/android solution (most likely the one that works with android).
Thanks in Advance!
I wouldn't necessarily try to replicate what you can do in Visual FoxPro since it's usually a good idea in that language to avoid macro substitution unless you absolutely have to use it, and you can't use a name expression instead.
Here is an example of a name expression:
STORE 'city' TO cVarCity
REPLACE (cVarCity) WITH 'Paris'
This is much faster especially in loops.
On the Java side you're probably looking at using the Reflection API.
I also work with vfp and I have some routines. Perhaps these functions serve you STRTRAN, CHRTRAN:
//--------- ejemplos :
// STRTRAN("Hola * mundo","*", "//") ==> "Hola // mundo"
public String STRTRAN(String cExpression, String cFindString, String cReplacement){
return cExpression.replace(cFindString, cReplacement);
}
//------------------ ejemplos:
// miToolkit.CHRTRAN("ABCDEF", "ACE", "XYZ"); // muestra XBYDZF. ok
// miToolkit.CHRTRAN("ABCDEF", "ACE", "XYZQRST"); // muestra XBYDZF. ok
// miToolkit.CHRTRAN("ABCD", "ABC", "YZ"); // muestra YZCD. No es como fox
public String CHRTRAN(String cString, String cFindChars, String cNewChars){
String cResult = cString;
char[] aFindChars;
char[] aNewChars;
int nLength = cFindChars.length();
aFindChars = cFindChars.toCharArray();
aNewChars = cNewChars.toCharArray();
if(cNewChars.length() < nLength){
nLength = cNewChars.length() ;
}
for(int i=0; i < nLength; i++){
cResult = cResult.replace( aFindChars[i], aNewChars[i] );
}
return cResult;
}
Saludos,
César Gómez,
Lima-Perú

How would i go about adding to my array through JOptionpanes?

At the moment I have to manually add items to my array but I would like to enable users to do this themselves perhaps through JOptionPanes, what would be the best way to go about this? Here is my current code.
public class Main {
public static void main(String[] args){
//Create new Person objects
Address p[] = new Address[3];
p[0] = new Address("27","Abbey View","Hexham","NE46 1EQ");
p[1] = new Address("15", "Chirdon Crescent", "Hexham", "NE46 1LE");
p[2] = new Address("6", "Causey Brae", "Hexham", "NE46 1DB");
Details c[] = new Details[3];
c[0] = new Details ("3", "175,000", "Terraced");
c[1] = new Details ("6", "300,000", "Bungalow");
c[2] = new Details ("4", "250,000", "Detached");
//Send some messages to the objects
c[0].setBeds("3 ");
c[1].setBeds("6");
c[2].setBeds("4");
c[0].setPrice("175,000");
c[1].setPrice("300,000");
c[2].setPrice("250,000");
c[0].setType("Terraced");
c[1].setType("Bungalow");
c[2].setType("Detached");
//Set up the association
p[0].ownsDetails(c[0]);
p[1].ownsDetails(c[1]);
p[2].ownsDetails(c[2]);
//print details
p[1].printDetails();
p[2].printDetails();
p[3].printDetails();
}
System.exit(0);
}
}
You could use the showXXXX methods on JOptionPane and keep prompting the user just as you would on the console.
However, I suggest just creating a simple JFrame that would have controls that allows the user to enter multiple items instead of showing one dialog after another.

Categories

Resources