JOptionPane is getting trunkcated on only one JOptionPane but not the other - java

I have two buttons that are supposed to open JOptionPanes. One of them does not format to the right size. The code looks the same to me. What am I doing wrong here?
This one does not display all the text in the JTextArea:
public static void listAllTransactions(){
DecimalFormat fmt = new DecimalFormat("0.00");
String message = "List All Transactions \n";
message += "Name: " + ca.getName() + "\n\n";
message += "ID\tType\tAmount\n";
for (Transaction t : ca.transactions){
message += t.getTransNumber() + "\t" +
HelperTransactionIds.getTransactionName(t.getTransIdType()) + "\t$" +
fmt.format(t.getTransAmount()) + "\n";
}
JTextArea jTextArea = new JTextArea(message);
jTextArea.setEditable(false);
jTextArea.setBackground(Color.LIGHT_GRAY);
JOptionPane.showMessageDialog(null,jTextArea);
}
The other one works as intended.
The code looks the same to me but I could be missing something:
public static void listChecks(){
DecimalFormat fmt = new DecimalFormat("0.00");
String message = "List All Checks \n";
message += "Name: " + ca.getName() + "\n\n";
message += "ID\tCheck\tAmount\n";
for (Transaction t : ca.transactions){
if (t.getTransIdType() == HelperTransactionIds.CHECK){
Check myCheck = (Check) t;
message += t.getTransNumber() + "\t" +myCheck.getNumber() + "\t$" + fmt.format(t.getTransAmount()) + "\n";
}
}
JTextArea jTextArea = new JTextArea(message);
jTextArea.setEditable(false);
jTextArea.setBackground(Color.LIGHT_GRAY);
JOptionPane.showMessageDialog(null, jTextArea);
}

Related

Is it possible to use file creation code inside actionPerformed class?

I am new to JAVA. I am trying to make gui for login and registration form. at the moment, I am focusing on registration. What I want is to save data created inside actionPerformed class into text form. For this, I put the file creation code inside actionPerformed class
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == sub) {
if (term.isSelected()) {
String data1;
String data
= "Name : "
+ tname.getText() + "\n"
+ "Mobile : "
+ tmno.getText() + "\n";
if (male.isSelected())
data1 = "Gender : Male"
+ "\n";
else
data1 = "Gender : Female"
+ "\n";
String data2
= "DOB : "
+ (String)date.getSelectedItem()
+ "/" + (String)month.getSelectedItem()
+ "/" + (String)year.getSelectedItem()
+ "\n";
String data3 = "Address : " + tadd.getText();
tout.setText(data + data1 + data2 + data3);
tout.setEditable(false);
res.setText("Registration Successfully..");
String txt_path = "C:\\FMP\\Users.txt";
File file = new File(txt_path);
FileWriter filewriter = new FileWriter(file, true);
filewriter.write(data + data1 + data2 + data3);
filewriter.flush();
filewriter.close();
}
else {
tout.setText("");
resadd.setText("");
res.setText("Please accept the"
+ " terms & conditions..");
}
}
I run this code, and I got nothing by clicking sub(which is button), it's supposed to be saved in .txt (C:\FMP\Users.txt)). the data is shown on Text, but not saved.

Is there anyway to format this? The code already runs fine but the formatting will run if the value is too big

I know that I can just use printf to format it but printf is used to print. I want to use the formatting to store the data then call the data to print it outside the do while loop.
#Override
public String toString() {
Scanner input = new Scanner(System.in);
String enter = "", data = "";
double totalCommission = 0.0;
DecimalFormat df = new DecimalFormat();
do {
setTransaction();
setSalesNum();
setName();
setAmount();
setCommission();
setRate();
do {
//prompt user to enter another
System.out.println("Would you like to enter another? [Y/N]");
boolean error = false;
//error prompt if y or n is not entered
enter = input.next();
if (!(enter.equals("n") || enter.equals("N") || enter.equals("y") || enter.equals("Y"))) {
error = true;
System.out.println("Invalid input! Please enter again.\n Would you like to enter another student's mark? [Y/N]");
} else {
error = false;
}
} while (false);
//setting the decimal places
df.setMaximumFractionDigits(2);
df.setMinimumFractionDigits(2);
//transaction details saved here
data += getTransaction() + "\t" + getSalesNum() + "\t\t" + getName() + "\t\t" + (df.format(getAmount())) + "\t" + " " + getRate() + "%" + "\t\t" + (df.format(getCompute())) + "\n";
totalCommission = totalCommission + getCompute();
} while (enter.equalsIgnoreCase("Y"));
System.out.println("Sales\tCommission");
System.out.println("TNO#\tSALESNO#\tNAME\t\tAMOUNT\t\t" + " " + "COMM RATE\tCOMMISSION");
return String.format(data + "\t\t\t\t\t\t" + " " + "TOTAL COMMISSION\t" + (df.format(totalCommission)));
}
So what I wanted to do is for this part data += getTransaction() + "\t" + getSalesNum() + "\t\t" + getName() + "\t\t" + (df.format(getAmount())) + "\t" + " " + getRate() + "%" + "\t\t" + (df.format(getCompute())) + "\n"; to be formatted inside while (enter.equalsIgnoreCase("Y")); then send data here: return String.format(data + "\t\t\t\t\t\t" + " " + "TOTAL COMMISSION\t" + (df.format(totalCommission)));
I'm sorry but I don't understand what you want to achieve. You may add an input and desired output example.
First of all:
if (!(enter.equals("n") || enter.equals("N") || enter.equals("y") || enter.equals("Y"))) {
if (!(enter.equalsIgnoreCase("n")|| enter.equalsIgnoreCase("y"))) {
You talked about print so you may want to take a look into: https://www.javatpoint.com/java-string-format
Because you mentioned String.format already I guess I misunderstood your question. If you reply back to me I will try to help you.
You wrote that you want to store your data inside that while loop and return it later. In this case, I would add every data to a list and return this list.

Adding all lines of output to one JOptionPane window after while loop

I am trying to add all of the output records from a regex parsed txt file to one JOptionPane window. I have created a string to capture, but mine continues to print individual windows. Any ideas? Thanks
while ((line = br.readLine()) != null) {
if (Pattern.matches(titlePattern, line)) {
String name = "", price="";
String patternName = "title=\".*?(\")";
Pattern r = Pattern.compile(patternName);
Matcher m = r.matcher(line);
if (m.find( )) {
name = m.group(0);
//System.out.println("Title: " + name.substring(7, name.length()-1));
}
String patternPrice = "Suggested Retail Price:.*?\"";
String strOutput;
r = Pattern.compile(patternPrice);
m = r.matcher(line);
if (m.find( )) {
price = m.group(0);
//System.out.println("Title: " + name.substring(7, name.length()-1) + ", " + price.substring(0, price.length()-1));
//JOptionPane.showMessageDialog(null, "Title: " + name.substring(7, name.length()-1) + ", " + price.substring(0, price.length()-1));
final_list.addElement("Title: " + name.substring(7, name.length()-1) + ", " + price.substring(0, price.length()-1));
strOutput = "Title: " + name.substring(7, name.length()-1) + ", " + price.substring(0, price.length()-1);
JOptionPane.showMessageDialog(null, strOutput);
}
}
}
Try to use java.swing.TextArea to build message and JOptionPane to display it. Here is short demo:
public static void main(String[] args) {
TextArea textView = new TextArea();
textView.append("dsddd");
textView.append("jsdjsd");
textView.append("qwoqwo");
JOptionPane.showMessageDialog(null, textView);
}

Netbeans - Trying to get jCombobox selected item into another JFrame TextArea

Hello wonderful people!
I've relatively new to this java and I'm practicing by creating an online booking system with multiple JFrames (I've heard this could be an issue).
In short, I want to retrieve the value of this jComboBox and display it in a text area on a separate frame. The problem is: How do I undergo this?
private void filmSelecterActionPerformed(java.awt.event.ActionEvent evt) {
if (filmSelecter.getSelectedIndex() == 0)
continueButton.setEnabled(false);
else {
continueButton.setEnabled(true);
}
Second JFrame
private void jQty2ActionPerformed(java.awt.event.ActionEvent evt) {
}
private void reviewButtonActionPerformed(java.awt.event.ActionEvent evt) {
// -------Review Order Button----
double Qty1 = Double.parseDouble(jQty1.getText());
double Qty2 = Double.parseDouble(jQty2.getText());
double Qty3 = Double.parseDouble(jQty3.getText());
double Qty4 = Double.parseDouble(jQty4.getText());
double total, subTotal, ticket1, ticket2, ticket3, ticket4;
String adultPrice = String.format("%.2f", adultprice);
subTotal1.setText(adultPrice);
String studentPrice = String.format("%.2f", studentprice);
subTotal2.setText(studentPrice);
String childPrice = String.format("%.2f", childprice);
subTotal3.setText(childPrice);
String seniorPrice = String.format("%.2f", seniorprice);
subTotal4.setText(seniorPrice);
ticket1 = Qty1 * adultprice;
ticket2 = Qty2 * studentprice;
ticket3 = Qty3 * childprice;
ticket4 = Qty4 * seniorprice;
//subTotal
String sub1 = String.format("£%.2f", ticket1);
subTotal1.setText(sub1);
String sub2 = String.format("£%.2f", ticket2);
subTotal2.setText(sub2);
String sub3 = String.format("£%.2f", ticket3);
subTotal3.setText(sub3);
String sub4 = String.format("£%.2f", ticket4);
subTotal4.setText(sub4);
subTotal = ticket1 + ticket2 + ticket3 + ticket4;
// Total ticket price
String subTotalAll = String.format("£%.2f", subTotal);
jTotalPrice.setText(subTotalAll);
// Receipt
String Title = "\tGreenwich Peninsula Cinema\n\n\n";
String Movie = "Movie Name: " + "\n";
//String MovieDay = "Movie Day" + filmSelecter.getSelectedItem() + "\n";
String MovieTime = "Movie Time: \n";
String Barrier = "=========================================" + "\n";
String Adult = "Adult:" + subTotal1.getText() + "\nNumber of Tickets: " + Qty1 + "\n";
String Student = "Student:" + subTotal2.getText() + "\nNumber of Tickets: " + Qty2 + "\n";
String Child = "Child:" + subTotal3.getText() + "\nNumber of Tickets: " + Qty3 + "\n";
String Senior = "Senior:" + subTotal4.getText() + "\nNumber of Tickets: " + Qty4 + "\n";
String Thanks = "\n\n\tEnjoy the film!";
String ShowReceipt = Barrier + Title + Movie + /*MovieDay +*/ MovieTime + Barrier + Adult + Student + Child + Senior + Thanks + "\n" + Barrier;
filmReceipt.append(ShowReceipt);
}
I hope this helps in anyway.

Java Bukkit coding: cannot kick players

Situation and question:
I want to kick players when they type swear words (case-insensitive).
Below is my attempt, but it doesn't kick the player. What did I do wrong?
Does not display any errors at all.
Source code:
#EventHandler
public void onPlayerChat(AsyncPlayerChatEvent e) {
Player player = e.getPlayer();
if (muted.contains(player.getUniqueId())) {
e.setCancelled(true);
player.sendMessage(ChatColor.DARK_BLUE + "[TC]" + ChatColor.DARK_RED + "You are muted and cannot chat.");
} else {
String message = e.getMessage();
if (message.contains("(?i)fuck") || message.contains("(?i)shit") || message.contains("(?i)ass") || message.contains("(?i)porno") || message.contains("(?i)porn") || message.contains("(?i)crap") || message.contains("(?i)dumb")) {
player.kickPlayer(ChatColor.DARK_RED + "Watch your language, please!");
e.setCancelled(true);
}
message = ChatColor.translateAlternateColorCodes('§', message);
message = ChatColor.translateAlternateColorCodes('&', message);
String text = ChatColor.DARK_BLUE + "[Chat]" + ChatColor.YELLOW + player.getName() + " " + ChatColor.DARK_RED + "Says: " + ChatColor.AQUA + message;
player.playNote(player.getLocation(),Instrument.PIANO, Note.natural(1, Tone.A));
text.replace("(?i)", "");
text = text.replace("<3", "❤");
text = text.replace(":)", "☺");
text = text.replace(":-)", "☺");
text = text.replaceAll("(?i)fuck", "****");
text = text.replaceAll("(?i)ass", "***");
text = text.replaceAll("(?i)shit", "****");
text = text.replaceAll("(?i)porno", "*****");
text = text.replaceAll("(?i)porn", "****");
text = text.replaceAll("(?i)dumb", "****");
text = text.replaceAll("(?i)crap", "****");
e.setFormat(text);
e.setMessage(text);
}
}
Use String.matches to match a regexp. Also, you can add all your swear words to some array/collection and use Java 8 features to simplify your code, e.g.
public static void main(String[] args) {
String message = "hello fuck world ass shit here i am";
final String[] swearWords = {"ass", "fuck", "shit", "porno", "porn"};
final boolean hasSwearWords = Stream.of(swearWords).anyMatch(w -> message.matches("(?i).*\\s" + w + "\\s.*"));
if (hasSwearWords) {
System.out.printf("Bad user!");
}
final String cleanMessage = Stream.of(swearWords).reduce(message,
(msg, w) -> msg.replaceAll(
"(?i)(\\s)" + w + "(\\s)",
"$1" + new String(new char[w.length()]).replace("\0", "*")+ "$2"));
System.out.println(cleanMessage);
}
Here is the code that doesn't require Java 8:
#EventHandler
public void onPlayerChat(AsyncPlayerChatEvent e) {
Player player = e.getPlayer();
if (muted.contains(player.getUniqueId())) {
e.setCancelled(true);
player.sendMessage(ChatColor.DARK_BLUE + "[TC]" + ChatColor.DARK_RED + "You are muted and cannot chat.");
} else {
String message = e.getMessage();
String[] swearWords = {"fuck", "shit", "ass", "porno", "porn", "crap", "dumb"};
for (String word : swearWords) {
if (message.matches("(?i).*\\s" + word + "\\s.*")) {
player.kickPlayer(ChatColor.DARK_RED + "Watch your language, please!");
e.setCancelled(true);
break;
}
}
message = ChatColor.translateAlternateColorCodes('§', message);
message = ChatColor.translateAlternateColorCodes('&', message);
String text =
ChatColor.DARK_BLUE + "[Chat]" + ChatColor.YELLOW + player.getName() + " " + ChatColor.DARK_RED + "Says: " +
ChatColor.AQUA + message;
player.playNote(player.getLocation(), Instrument.PIANO, Note.natural(1, Tone.A));
text = text.replace("<3", "❤")
.replace(":)", "☺")
.replace(":-)", "☺");
for (String word : swearWords) {
text = text.replaceAll(
"(?i)(\\s)" + word + "(\\s)",
"$1" + new String(new char[word.length()]).replace("\0", "*")+ "$2");
}
e.setFormat(text);
e.setMessage(text);
}
}

Categories