Printing multiple user entries.
Hi there guys. Was hoping someone could give me some ideas on how to work this segment of code.
I am basically trying to print 2 user inputs. 1 is a textbox and the other is a jcombobox.
Code:
import java.awt.print.*;
import javax.swing.*;
import java.awt.event.*;
import java.text.*;
public class PrintingTest extends javax.swing.JFrame implements Printable{
JPanel mainPanel = new JPanel();
String text = "Write something here :D";
JTextField txtTest = new JTextField(text, 20);
String[] choiceFormat = {"Open Format", "Importance Format", "Dichotomous Format", "Choice Format"};
JComboBox jcbChoice = new JComboBox(choiceFormat);
/** Creates new form PrintingTest */
public PrintingTest() {
initComponents();
displayPanel();
}
public void displayPanel()
{
JButton btnTest = new JButton("Test !");
mainPanel.add(txtTest);
mainPanel.add(jcbChoice);
mainPanel.add(btnTest);
btnTest.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnTestActionPerformed(evt);
}
});
this.add(mainPanel);
mainPanel.setSize(400,200);
mainPanel.setBackground(Color.YELLOW);
}
private void btnTestActionPerformed(java.awt.event.ActionEvent evt) {
JTextField txtChoice = new JTextField(jcbChoice.getSelectedItem().toString());
MessageFormat question = createFormat(txtTest);
MessageFormat choice = createFormat(txtChoice);
PrintingTask task = new PrintingTask(question, choice);
task.execute();
}
private class PrintingTask extends SwingWorker<Object, Object> {
private final MessageFormat questionFormat;
private final MessageFormat choiceFormat;
private volatile boolean complete = false;
public PrintingTask(MessageFormat question, MessageFormat choice){
this.questionFormat = question;
this.choiceFormat = choice;
}
@Override
protected Object doInBackground() {
try {
complete = mainPanel.print(questionFormat, choiceFormat,
true, null, null, null);
} catch (PrinterException ex) {
JOptionPane.showMessageDialog(null, "Unable to print + Error : "
+ ex);
} catch (SecurityException ex) {
JOptionPane.showMessageDialog(null, "Unable to access selected printer ! ");
}
return null;
}
@Override
protected void done() {
JOptionPane.showMessageDialog(null, "Printing Done !");
}
}
private MessageFormat createFormat(JTextField source) {
String text2 = source.getText();
if (text2 != null && text2.length() > 0) {
try {
return new MessageFormat(text2);
} catch (IllegalArgumentException e) {
JOptionPane.showMessageDialog(null,"Sorry, this format is invalid.");
}
}
return null;
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new PrintingTest().setVisible(true);
}
});
}
The following website is what I am trying to do in a similar fashion but in a smaller scale. I would really appreciate any help.