JButtons in a JTextArea

I am hoping to add a JButton to a JTextArea, but to be completely honest, I am not sure if this is physically possible, let alone feasible.
I have written some code which I hoped would do the trick, and although it compiles, it does not display the JButton.
Any help, starting with, am I asking the impossible would be greatly appreciated.
Below is my method:
public void displayMatchedManagers(Vector vmd)
JButton jbNP[]= new JButton[vmd.size()];
JButton jbNM = new JButton("New Manager");
String details;
jtaManagerFeedback.append(" ***FEEDBACK***" +
"\n\n The system has found some possible" +
"\n matches to the criteria just entered, it" +
"\n is therefore possible that this manager" +
"\n has already registered." +
"\n\n Look at the existing managers details" +
"\n below, and if a match is found click the" +
"\n 'New Prediction' button beneath the" +
"\n relevant manager's details. This will add" +
"\n the prediction to the manager's account." +
"\n\n ***POSSIBLE MATCHES***\n\n");
for ( int i = 0; i < vmd.size(); i++ )
MD = (ManagerDetails) (vmd.elementAt(i));
details = " Manager \\ Prediction ID: " + MD.getIDNumber() +
"\n Name: " + MD.getFirstName() +
     " " + MD.getLastName() +
     "\n Address: " + MD.getAddress() +
"\n Postcode: " + MD.getPostcode() +
     "\n Area Code: " + MD.getAreaCode() +
     "\n Telephone Number: " + MD.getTelephone() +
     "\n Mobile Number: " + MD.getMobile() +
     "\n E-mail Address: " + MD.getEmail() + "\n\n";
jtaManagerFeedback.append(details);
jtaManagerFeedback.add(jbNP[i] = new JButton("New Prediction"));
details = "\n\n If none of the above managers where a" +
"\n match, click the 'New Manager' button below." +
"\n This will add the new manager to the" +
"\n database along with their predictions.";
jtaManagerFeedback.append(details);
jtaManagerFeedback.add(jbNM);
jtaManagerFeedback.setCaretPosition( 0 );
Thanks, Kris Dowse

found it..
//initialize the gridbaglayout
gridbag = new GridBagLayout();
c = new GridBagConstraints();
keuzes.setLayout(gridbag);
c.fill = GridBagConstraints.NONE;
c.gridwidth = GridBagConstraints.REMAINDER;      //end row
c.insets= new Insets(3,10,3,10);
//     c.ipadx = 20;
//     c.ipady = 5;
introtext=new JLabel("Welkom bij ZKK-DOS maak uw keuze")
     public Dimension getPreferredSize()
          return new Dimension(800,80);
introtext.setHorizontalAlignment(JLabel.CENTER);
configuratie = ZKKDOSConfigManager.getConfiguration();
if(configuratie.containsKey("HMopt"))
//some stuff to read my ini file
Vector options =(Vector)configuratie.get("HMopt");
String confItem=(String)options.elementAt(0);
System.out.println(confItem);
// the aantal variable holds the number of buttons i want
int aantal = Integer.parseInt(confItem.substring(confItem.length()-1));
//keuzes.setLayout(new GridLayout(aantal,1));
for(int i=0;i<aantal;i++) // loop as many times as we want buttons
//set the gridbag the way i wanted the buttons
c.gridwidth = GridBagConstraints.REMAINDER;
//get the buttons caption from my ini file
Button b = new Button((String)options.elementAt(i+1))
// an inner class to make sure the buttons get the size i want them to be as layoutmanager uses getPreferredSize() to get the buttons preferredSize
  public Dimension getPreferredSize()
   return new Dimension(80,30);
b.addActionListener(this);
b.addMouseListener(this);
//add the button to the gridbaglayout
gridbag.setConstraints(b, c);
keuzes.add(b);
}hope it helps you,
robert

Similar Messages

  • Embedding a JButton in a JTextArea or JLabel.

    Hi,
    I am trying to figure out how to integrate a JButton into a text block.
    The idea is that the user is presented with instructions on how to solve a problem for instance how to switch on standby electric power when operating a generator.
    The instructional text would have a colour-highlighted text string, lets say STANDBY ELECTRIC POWER "embeded" at the appropriate place and the user clicks on it to access the detailed instructions of how to switch on this case standby electric power.
    The instruction could look something like the following:
    "If the generator voltage drops below a minimum of 24 volts switch on the STANDBY ELECTRIC POWER and ensure that the voltage is 28 volts".
    Clicking on this text string would then direct the user to a detailed explanation of how he/she should proceed to get and monitor standby electric power.
    I image that using a JLabel or JTextArea and "embeding" a JButton at exactly the place indicated would do the job. Maybe there is a better way???
    Does anyone have any ideas?
    Many tks
    John

    Use a JEditorPane and add a HyperLinkListener. The API has an example.

  • Need a little help with a Jbutton not working out the way I planned

    The following code is to fulfill an assignment I am working on. The problem I am having is with the btnCalc. For some reason when the button is used, the results I get is from another button. I think the variables are set right for the program to function properly but I am really hung up on this. Do anyone have any suggestions?
    import java.awt.*;                     //Contains classes for creating GUI
    import java.awt.event.*;                //For listener events
    import javax.swing.*;                     // Imports the Main Swing Package
    import javax.swing.event.*;
    import javax.swing.text.*;           // Positions text box
    import java.text.NumberFormat;          // For number format such as currency
    import java.text.*;                     // Imports the Main Text Package
    import java.util.*;                     // Utility Package
    public class MPC extends JFrame implements ActionListener           //Creates Class for MPC
    //double dblLoanAmount, dblInterestRate, dblMonthlyPayment;
    TextField txtTotalMort;
         //JButton fixRates = new JButton("Choose Fixed Rates");
         JLabel lblTotalMort = new JLabel("How much is the loan?"); // Label for dblLoanAmount amount
         JTextField txtYears = new JTextField(10);
         JLabel lblPayment = new JLabel("Your monthly payment is "); // Label for Payment
         JTextField txtPayment = new JTextField(10);
         JLabel lblYears = new JLabel("How many years?");
                             // add(lblYears);
                   JTextField txtYearsInput = new JTextField(10);
                             //a dd(txtYears);
         JLabel lblInterestRate = new JLabel("What is the interest rate?");
                             //add(lblInterestRate);
                   JTextField txtInterestRate = new JTextField(10);
                             //add(txtInterestRate);
         //JLabel lblPayment = new JLabel("Your monthly payment is:");
                             //add(lblPayment);
                   //JTextField txtPayment = new JTextField(10);
                             //txtPayment.setEditable(false);
                                  //add(txtPayment);
         JButton btnCalc = new JButton("Calculate");
                             //add(btnCalc);
                             //btnCalc.addActionListener(this);
    JButton year7InterestRateBtn = new JButton("7 years at 5.35%");     // Mortgage Term and Interest Rate
    JButton year15InterestRateBtn = new JButton("15 years at 5.50%");
    JButton year30InterestRateBtn = new JButton("30 years at 5.75%");
    JButton reset = new JButton("Clear All");
    JTextArea boxSpace = new JTextArea(100,200);          // Morgtage table size
    JScrollPane scroll = new JScrollPane(boxSpace);     // ScrollPane
              public MPC()     // Method
         super("MPC");     // Frame Title
              JMenuBar mb = new JMenuBar();     // Menu Bar
    setJMenuBar(mb);
                        setSize(325, 500);          // Frame Size
                        JPanel pane = new JPanel();
                        pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS)); //Grid box configuration
                        Container grid = getContentPane();
                        grid.setLayout(new GridLayout(8,2,8,8));     // Grid Layout
                        pane.add(grid);                                        // Adds grid
                        pane.add(scroll);                                   // Adds scrollPane
                   grid.setBackground(Color.white);
                        Setting color of text and backgrounds
                   txtYears.setBackground(Color.white);
              txtYears.setForeground(Color.black);
                   txtYears.setFont(new Font("Arial", Font.PLAIN, 10));
                        txtPayment.setBackground(Color.white);
                   txtPayment.setForeground(Color.black);
              txtPayment.setFont(new Font("Arial", Font.PLAIN, 10));
                   boxSpace.setBackground(Color.white);
                   boxSpace.setForeground(Color.black);
                   boxSpace.setFont(new Font("Arial", Font.PLAIN, 10));
              grid.add(lblYears);
              grid.add(txtYearsInput);
              grid.add(lblInterestRate);
              grid.add (txtInterestRate);
              grid.add(lblTotalMort);          // Adds the Mortgage Amount Label
              grid.add(txtYears);               // Adds the Mortgage Amount Text Field
              grid.add(lblPayment);           // Adds the Payment Label
              grid.add(txtPayment);           // Adds the Monthly Payment Text Field
                   txtPayment.setEditable(false);          // Disables editing in this Text Field
              grid.add(btnCalc);
         grid.add(year7InterestRateBtn);               // Adds 1st Loan and Rate Button
              grid.add(year15InterestRateBtn);          // Adds 2nd Loan and Rate Button
              grid.add(year30InterestRateBtn);          // Adds the Exit Button
              grid.add(reset);                               // Adds the New Calc Button
              setContentPane(pane);                          // Enables the Content Pane
              setVisible(true);                               // Sets JPanel to be Visable
              reset.addActionListener(this);                          // Adds Action Listener to the New Calc Button
              txtYearsInput.addActionListener(this);
              txtInterestRate.addActionListener(this);
              btnCalc.addActionListener(this);
         year7InterestRateBtn.addActionListener(this);                              // Adds Action Listener to the 1st loan Button
              year15InterestRateBtn.addActionListener(this);                              // Adds Action Listener to the 2nd loan Button
              year30InterestRateBtn.addActionListener(this);                               // Adds Action Listener to the 3rd loan Button
              txtYears.addActionListener(this);                              // Adds Action Listener to the Mortgage Amount Text Field
              txtPayment.addActionListener(this);                              // Adds Action Listener to the Monthly payment Text Field
              public void actionPerformed(ActionEvent e)                               // Tests to Verify Which Button is Pressed
         Object command = e.getSource(); // Enables command to get data
         int intYears = 0;          // Declares intYears
                   double dblLoanAmount, dblInterestRate, interestRate, intRate;
         if (command == year7InterestRateBtn)                                   // Activates the 1st Loan Button
    intYears = 0;                                        // Sets 1st value of Array
         if (command == year15InterestRateBtn)                                   // Activates the 2nd Loan Button
         intYears = 1;                                        // Sets 2nd value of Array
              if (command == year30InterestRateBtn)                                   // Activates the 3rd Loan Button
                   intYears = 2;                                        // Sets 3rd value of Array
                   if (command == btnCalc)
                        //dblLoanAmount = Double.parseDouble(txtTotalMort.getText() ); // Loan amount
                        //interestRate = Double.parseDouble(txtInterestRate.getText() ); // /100 )/ 12; // Devides rate
                        intRate = (Double.parseDouble(txtInterestRate.getText() )/100 )/ 12;
                        //int intYearsMonths = Integer.parseInt(txtYearsInput.getText() );// * 12; //Multiplies loan length
                        int months = Integer.parseInt(txtYearsInput.getText() )* 12;
    dblLoanAmount = 0;                                   // Declares and Initializes dblLoanAmount
                   dblInterestRate = 0;                                        // Declares and Initializes dblInterestRate
              double [][] dblTrmLoanRate = {{7, 5.35}, {15, 5.50}, {30, 5.75},};           // Array Data for Calculation
    try
    dblLoanAmount = Double.parseDouble(txtYears.getText()); // Gets user input from txtYears Text Field
    catch (NumberFormatException nfe)                          // Checks for correct user input
                             JOptionPane.showMessageDialog(null, "You must enter a valid number.", "MPC", JOptionPane.INFORMATION_MESSAGE);
    return;
              interestRate = dblTrmLoanRate [intYears][1];
                   //dblInterestRate=interestRate;
                   intRate = (interestRate / 100) / 12;                         // Calculates Interst Rate
         double intYearsMonths = dblTrmLoanRate [intYears] [0];                    // Calculates Loan Term in Months
    int months = (int)intYearsMonths * 12;                          // Devides by months
    double interestRateMonthly = (intRate / 12); // Devides Rate
              double payment = dblLoanAmount * intRate / (1 - (Math.pow(1/(1 + intRate), months))); // Calculates monthly payment
         double dblRmnLoan = dblLoanAmount;                              //Left over balance
         double txtPaymentInterest = 0;                                   // Payment
         double txtPaymentPrincipal = 0;                                   // Payment of principal
    NumberFormat currency = NumberFormat.getCurrencyInstance(Locale.US); // Curreny format
         txtPayment.setText(currency.format(payment));
              boxSpace.setText("Month\tPrincipal\tInterest\tBalance Left\n");
              for (;months > 0 ; months -- )
              txtPaymentInterest = (dblRmnLoan * intRate);
                        txtPaymentPrincipal = (payment - txtPaymentInterest);          // Calculates monthly payment
                   dblRmnLoan = (dblRmnLoan - txtPaymentPrincipal);
                        boxSpace.setCaret (new DefaultCaret());                    // Scroll position
                        boxSpace.append(String.valueOf(months) + "\t" +               // Table data
                        currency.format(txtPaymentPrincipal) + "\t" +
                   currency.format(txtPaymentInterest) + "\t" +
                   currency.format(dblRmnLoan) + "\n");
    if(command == reset)
                             Clears fields
                        txtYearsInput.setText(null);
                        txtInterestRate.setText(null);
              txtYears.setText(null);
                        txtPayment.setText(null);
         boxSpace.setText(null);
                        public static void main(String[] args)                               //This is the signature of the entry point of all the desktop apps
              new MPC();
    }

    This portion to be exact. All the buttons work for me except this one. I need to calculate user input and also use the fixed data that can be found in the dblTrmLoanRate array. When I choos to use user input instead, the program either crashes or for some reason uses the year7InterestRateBtn instead.
                   if (command == btnCalc)
                        //dblLoanAmount = Double.parseDouble(txtTotalMort.getText() ); // Loan amount
                        //interestRate = Double.parseDouble(txtInterestRate.getText() ); // /100 )/ 12; // Devides rate
                        intRate = (Double.parseDouble(txtInterestRate.getText() )/100 )/ 12;
                        //int intYearsMonths = Integer.parseInt(txtYearsInput.getText() );// * 12; //Multiplies loan length
                        int months = Integer.parseInt(txtYearsInput.getText() )* 12;
    I was going to leave out the remed portion but thought it might help you with the navigation. I am sorry I did not use code tags, but I am going to go find out what those are and use them in the future.

  • How to get the content of text file to write in JTextArea?

    Hello,
    I have text area and File chooser..
    i wanna the content of choosed file to be written into text area..
    I have this code:
    import java.awt.Container;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.File;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.*;
    public class Test_Stemmer extends JFrame {
    public Test_Stemmer() {
    super("Arabic Stemmer..");
    setSize(350, 470);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setResizable(false);
    Container c = getContentPane();
    c.setLayout(new FlowLayout());
    JButton openButton = new JButton("Open");
    JButton saveButton = new JButton("Save");
    JButton dirButton = new JButton("Pick Dir");
    JTextArea ta=new JTextArea("File will be written here", 10, 25);
    JTextArea ta2=new JTextArea("Stemmed File will be written here", 10, 25);
    final JLabel statusbar =
                  new JLabel("Output of your selection will go here");
    // Create a file chooser that opens up as an Open dialog
    openButton.addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent ae) {
         JFileChooser chooser = new JFileChooser();
         chooser.setMultiSelectionEnabled(true);
         int option = chooser.showOpenDialog(Test_Stemmer.this);
         if (option == JFileChooser.APPROVE_OPTION) {
           File[] sf = chooser.getSelectedFiles();
           String filelist = "nothing";
           if (sf.length > 0) filelist = sf[0].getName();
           for (int i = 1; i < sf.length; i++) {
             filelist += ", " + sf.getName();
    statusbar.setText("You chose " + filelist);
    else {
    statusbar.setText("You canceled.");
    // Create a file chooser that opens up as a Save dialog
    saveButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    JFileChooser chooser = new JFileChooser();
    int option = chooser.showSaveDialog(Test_Stemmer.this);
    if (option == JFileChooser.APPROVE_OPTION) {
    statusbar.setText("You saved " + ((chooser.getSelectedFile()!=null)?
    chooser.getSelectedFile().getName():"nothing"));
    else {
    statusbar.setText("You canceled.");
    // Create a file chooser that allows you to pick a directory
    // rather than a file
    dirButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    JFileChooser chooser = new JFileChooser();
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    int option = chooser.showOpenDialog(Test_Stemmer.this);
    if (option == JFileChooser.APPROVE_OPTION) {
    statusbar.setText("You opened " + ((chooser.getSelectedFile()!=null)?
    chooser.getSelectedFile().getName():"nothing"));
    else {
    statusbar.setText("You canceled.");
    c.add(openButton);
    c.add(saveButton);
    c.add(dirButton);
    c.add(statusbar);
    c.add(ta);
    c.add(ta2);
    public static void main(String args[]) {
    Test_Stemmer sfc = new Test_Stemmer();
    sfc.setVisible(true);
    }could you please help me, and tell me what to add or to modify,,
    Thank you..                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    realahmed8 wrote:
    thanks masijade,
    i have filter the file chooser for only text files,
    but i still don't know how to use FileReader to put text file content to the text area (ta) ..
    please tell me how and where to use it..How? -- See the IO Tutorials on Sun for the FileReader (and I assume you know how to call setText and append in the JTextArea).
    Where? -- In the actionPerformed method (better would be a separate thread that is triggered through the actionPerformed method, but that is probably beyond you at the moment), of course.
    Give it a try.

  • How do I update a JTextArea dynamically?

    Hello! This is my first post, so be gentle. :-)
    I am just getting started in Java and am writing a gui app to take a list of PC's from a JTextArea on the left, and reboot them one at a time. Then on the right, in another JTextArea, output whether the reboot was successful, or couldn't ping it, etc. The trouble is, when I run the program, it steps through each PC in the list just like I want it to. Reboots them just as designed. Appends to the JTextArea just as designed. But it does not update the text area until it makes it through the entire list. If I have 100 PCs in the list, it attempts to reboot them all, then BOOM all the appends to the log text area are applied at once. Is there any way to update the text area as an attempt is made on each PC in the list?
    Here's the reboot code.
    try
         Runtime runtime = Runtime.getRuntime();
         // TODO Auto-generated method stub
         if (e.getSource() == leave)
              System.exit(0);
         else if (e.getSource() == reboot)
              StringTokenizer tokenizer = new StringTokenizer(pclist.getText() + String.valueOf(CRLF));
              //StringTokenizer tokenizer = new StringTokenizer(pclist.getText());
              //System.out.println(String.valueOf(CRLF)+ "this");
              while(tokenizer.hasMoreTokens())
                   computers.add(tokenizer.nextToken());
              log.setText("");
              //System.out.println(computers.size());
              for(int i = 0; i < computers.size(); i++)
                   try
                        Process checkpulse = runtime.exec("ping " + computers.get(i) + " -n 1");// | find '"Reply"'");
                        int checkPulseExitVal = checkpulse.waitFor();
                        //System.out.println(checkPulseExitVal);
                             if (checkPulseExitVal != 0)
                                  log.append("Unable to Ping " + computers.get(i) + "\r\n");
                                  log.revalidate();
                                  //log.setCaretPosition(i);
                             else if(checkPulseExitVal == 0)
                                  //System.out.println(computers.size());
                                  Process restart = runtime.exec("shutdown -r -t 0 -m \\\\" + computers.get(i));
                                  int restartExitVal = restart.waitFor();
                                  if (restartExitVal == 0)
                                       log.append(computers.get(i) + " Rebooted\r\n");
                                       log.revalidate();
                                       //log.validate();
                                       //log.setCaretPosition(i);
                             else
                                  log.append("Sumpin happened and I'm not sure what.\r\n");
                                  log.revalidate();
                   catch (InterruptedException e1)
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
    catch (IOException e1)
         // TODO Auto-generated catch block
         e1.printStackTrace();
    {code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Dang...I must be doing something not quite right. I'm going to post a largeish block of code. Can you nudge me in the correct direction please? This code compiles and runs. You can just type in bogus pc names on the left and the right pane won't update until it tries to ping and reboot them all.
    package pccontrol;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.BorderLayout;
    import java.awt.event.*;
    import com.sun.java.swing.plaf.motif.MotifLookAndFeel;
    import com.sun.java.swing.plaf.windows.WindowsLookAndFeel;
    import com.sun.org.apache.xml.internal.serialize.LineSeparator;
    import java.io.*;
    import java.lang.*;
    import java.util.*;
    import java.lang.Runtime;
    public class Control extends JFrame
         //private GuiFrame fr = new GuiFrame();
         private JFrame fr = new JFrame();
         private JLabel putlist = new JLabel();
         private JMenuBar topframe = new JMenuBar();
         private JButton reboot = new JButton("Reboot 'em!");
         private JButton leave = new JButton("Exit");
         private JTextArea pclist = new JTextArea(0, 20);
         private JTextArea log = new JTextArea();
         private JScrollPane scrollPane = new JScrollPane(pclist);
         private JScrollPane logScrollPane = new JScrollPane(log);
         private JPanel pan = new JPanel();
         final ArrayList computers = new ArrayList();
         //String[] computers = new String[getRandom(50)];
         char CRLF = 13;
         private Thread thread;
         Runtime runtime = Runtime.getRuntime();
         //private Process child;
         //private String comp;
         //private String command = "shutdown";
         public Control() throws HeadlessException
              // TODO Auto-generated constructor stub
              initialize();
         public Control(GraphicsConfiguration arg0)
              super(arg0);
              // TODO Auto-generated constructor stub
              initialize();
         public Control(String arg0) throws HeadlessException
              super(arg0);
              // TODO Auto-generated constructor stub
              initialize();
         public Control(String arg0, GraphicsConfiguration arg1)
              super(arg0, arg1);
              // TODO Auto-generated constructor stub
              initialize();
          * @param args
         public static void main(final String[] args)
              // TODO Auto-generated method stub
              new Control();
         public void initialize()
              fr.getContentPane();
              pan.setLayout(new BorderLayout());
              pan.add("North", topframe);
              topframe.add(reboot);
              topframe.add(leave);
              reboot.setToolTipText("Click here to REBOOT them all!");
              //pan.add("West",pclist);
              pan.add("West", scrollPane);
              pan.add("Center", logScrollPane);
              putlist.setText("            Paste PC list below                                              ");
              topframe.add(putlist, 0,0);
              fr.add(pan);
              //pclist.setLineWrap(false);
              fr.pack();
              //Create the FrameEventHandler
              FrameEventHandler feh = new FrameEventHandler();
              //Register this Frame with feh
              addWindowListener(feh);
              //Create the button event handler.
              ButtonEventHandler beh = new ButtonEventHandler();
              reboot.addActionListener(beh);
              leave.addActionListener(beh);
              try
                   //Change the look and feel of the UI manager.
                   UIManager.setLookAndFeel(new WindowsLookAndFeel());
                   //UIManager.setLookAndFeel(new MotifLookAndFeel());
              catch (Exception e)
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              fr.setTitle("PC Control");
              fr.setSize(600, 600);
              SwingUtilities.updateComponentTreeUI(fr);
              fr.setLocation(150, 150);
              fr.setVisible(true);
         class ButtonEventHandler implements ActionListener
              public void actionPerformed(ActionEvent e)
                        //Runtime runtime = Runtime.getRuntime();
                        // TODO Auto-generated method stub
                        if (e.getSource() == leave)
                             System.exit(0);
                        else if (e.getSource() == reboot)
                             StringTokenizer tokenizer = new StringTokenizer(pclist.getText() + String.valueOf(CRLF));
                             //StringTokenizer tokenizer = new StringTokenizer(pclist.getText());
                             //System.out.println(String.valueOf(CRLF)+ "this");
                             //thread = new Thread (new Runnable()
                                  //public void run()
                             while(tokenizer.hasMoreTokens())
                                  computers.add(tokenizer.nextToken());
                             log.setText("");
                             //System.out.println(computers.size());
              final Runnable runner = (new Runnable()
                   public void run()
                        for(int i = 0; i < computers.size(); i++)
                                  try
                                       Process checkpulse = runtime.exec("ping " + computers.get(i) + " -n 1");// | find '"Reply"'");
                                       int checkPulseExitVal = checkpulse.waitFor();
                                       //System.out.println(checkPulseExitVal);
                                       if (checkPulseExitVal != 0)
                                            log.append("Unable to Ping " + computers.get(i) + "\r\n");
                                       else //(checkPulseExitVal == 0)
                                            //System.out.println(computers.size());
                                            Process restart = runtime.exec("shutdown -r -t 0 -m \\\\" + computers.get(i));
                                            int restartExitVal = restart.waitFor();
                                            if (restartExitVal == 0)
                                                 log.append(computers.get(i) + " Rebooted\r\n");
                                  catch (IOException e)
                                       // TODO Auto-generated catch block
                                       e.printStackTrace();
                                  catch (InterruptedException e)
                                       // TODO Auto-generated catch block
                                       e.printStackTrace();
                   EventQueue.invokeLater(runner);
    class FrameEventHandler extends WindowAdapter
         //Everride the method / event that you are interested in.
         public void windowClosing (WindowEvent e)
              // TODO Auto-generated method stub
              //super.windowClosing(e);
              e.getWindow().setVisible(false);
              e.getWindow().dispose();
              System.exit(0);
    }{code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Doubt to be Clarified on JTextArea appending a string

    Hi All,
    Here is the actual code.
    String msg="Settings Details Will be Produced after the Connection is Successful";
                        String msg1=      "-------------------------------------------------------------------------";
                        String comdetails="1)Comport Enabled is:";
                        String baudratedetails="2)BaudRate Selected is:";
                        String databitdetails="3)DataBit is:";
                        String paritybitdetails="4)ParityBit is:";
                        String stopbitdetails="5)Stopbit is:";
    contentarea.setText("");
                           contentarea.append(msg);
                        contentarea.append("\r\n");
                        contentarea.append(msg1);
                        contentarea.append("\r\n");
                        contentarea.append(msg1);
                        contentarea.append("\r\n");
                        contentarea.append(comdetails);contentarea.append(cv);
                        contentarea.append("\r\n");
                        contentarea.append(baudratedetails);contentarea.append(bv);
                        contentarea.append("\r\n");
                        contentarea.append(databitdetails);contentarea.append(dv);
                        contentarea.append("\r\n");
                        contentarea.append(paritybitdetails);contentarea.append(pv);
                        contentarea.append("\r\n");
                        contentarea.append(stopbitdetails);contentarea.append(sv);
                        contentarea.append("\r\n");
                        contentarea.append(msg1);
                        contentarea.append("\r\n");
                        contentarea.append(msg1);I have a JTextArea which is basically linked up with a JBUtton.So when i click on JButton in the JTextArea thte following will be displayed.
    "Settings Details Will be Produced after the Connection is Successful"
    1)Comport Enabled is:COM3
    2)BaudRate Selected is:38400
    3)DataBit is:8bit
    4)ParityBit is:NONE
    5)Stopbit is:1bitSo my question when i again click on the same JButton the same data which is highlighted in the code tags need to be displayed again from the next end line of the previous data instead of overriding operation.Can any one help me out in doing this???
    Thanks in advance.
    regards,
    Viswanadh

    Hi toodburch,
    Thanks for the reply.My requirement is for every click on the JButton it should be in the following way.Assume i have pressed 3 times.then it should be displayed as shown.
    "Settings Details Will be Produced after the Connection is Successful"
    1)Comport Enabled is:COM3
    2)BaudRate Selected is:38400
    3)DataBit is:8bit
    4)ParityBit is:NONE
    5)Stopbit is:1bit
    "Settings Details Will be Produced after the Connection is Successful"
    1)Comport Enabled is:COM3
    2)BaudRate Selected is:38400
    3)DataBit is:8bit
    4)ParityBit is:NONE
    5)Stopbit is:1bit
    "Settings Details Will be Produced after the Connection is Successful"
    1)Comport Enabled is:COM3
    2)BaudRate Selected is:38400
    3)DataBit is:8bit
    4)ParityBit is:NONE
    5)Stopbit is:1bitThanks
    regards,
    Viswanadh

  • How to display most updated data on the TOP of the JTextArea???

    hi ,
    i have a JTextArea inside a JTextPane
    and the usual way that JTextArea is display
    The 1st message on top and follow until the ends
    is there any way to display the most updated/newest data on TOP instead Of the normal way?

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TextTop extends JFrame {
        public TextTop() {
            initComponents();
        private void initComponents() {
            jTextArea1 = new JTextArea();
            jToolBar1 = new JToolBar();
            jButton1 = new JButton();
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            jTextArea1.setBackground(new Color(255, 255, 204));
            jTextArea1.setEditable(false);
            getContentPane().add(jTextArea1, BorderLayout.CENTER);
            jToolBar1.setFloatable(false);
            jButton1.setText("TEXT");
            jButton1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            jToolBar1.add(jButton1);
            getContentPane().add(jToolBar1, BorderLayout.NORTH);
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-409)/2, (screenSize.height-334)/2, 409, 334);
        int count;
        private void jButton1ActionPerformed(ActionEvent evt) {
            count++;
            jTextArea1.insert("Text  " +count+ "\n", 0);
        public static void main(String args[]) {
                    new TextTop().setVisible(true);
        private JButton jButton1;
        private JTextArea jTextArea1;
        private JToolBar jToolBar1;
    }

  • How to handle other encodings in JTextArea?

    Hi,
    I created a simple editor using JTextArea. When I typed some
    Chinese characters in it, it can be displayed. But after I used
    getText() to get the content, and wrote it to file byte by byte, then
    loaded it back to the same application, the Chinese characters
    are gone. Is there any special handling I should do when dealing
    with other character encodings?

    Hi,
    I tried to use Reader and Writer, but the file I reloaded is still different
    from what I saved. Here is a complete list of my code. Is there anythingI did wrong? Thanks a lot.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class Editor extends JPanel
       JFrame frame;
       final JButton loadBtn = new JButton("Load");
       final JButton saveBtn = new JButton("Save");
       final JButton exitBtn = new JButton("Exit");
       final JTextArea editArea = new JTextArea(100, 10);
       final JFileChooser fd = new JFileChooser();
       public Editor()
          setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
          frame = new JFrame("test");
          final JPanel ctrlPanel = new JPanel();
          ctrlPanel.add(loadBtn);
          ctrlPanel.add(saveBtn);
          ctrlPanel.add(exitBtn);
          add(ctrlPanel);
          final JScrollPane editPane = new JScrollPane(editArea);
          add(editArea);
          editArea.setVisible(true);
          loadBtn.addActionListener( new ActionListener () {
           public void actionPerformed (ActionEvent e) {
              JFrame fm= new JFrame();
              fd.showOpenDialog(fm);
              File f = fd.getSelectedFile();
              if (f!=null) load(f);
          saveBtn.addActionListener( new ActionListener () {
           public void actionPerformed (ActionEvent e) {
              JFrame fm= new JFrame();
              fd.showSaveDialog(fm);
              File f = fd.getSelectedFile();
              if (f!=null) save(f);
          exitBtn.addActionListener( new ActionListener () {
           public void actionPerformed (ActionEvent e) {
              System.exit(0);
         frame.getContentPane().add(this);
         frame.setLocation(400, 400);
         frame.setSize(600, 300);
         frame.show();
       public boolean save(OutputStream os)
          try
            OutputStreamWriter osw = new OutputStreamWriter(os);
            osw.write(editArea.getText());
            osw.close();
          catch (Exception e)
            e.printStackTrace();
            return false;
          return true;
       public boolean save(File f)
          boolean code = true;
          try
             FileOutputStream os = new FileOutputStream(f);
             code = save(os);
             os.close();
          catch (Exception e)
             e.printStackTrace();
             return false;
          return code;
       public boolean load(InputStream is)
         try
            BufferedReader in = new BufferedReader(new InputStreamReader(is));
            String inputLine;
            while ((inputLine = in.readLine()) != null)
               if (inputLine.length()>0)
                 editArea.append(inputLine+"\n");
            in.close();
         catch (Exception e)
            e.printStackTrace();
            return false;
         return true;
       public boolean load(File f)
         boolean code = true;
         try
            FileInputStream fis = new FileInputStream (f);
            code = load(fis);
            fis.close();
         catch (Exception e)
            e.printStackTrace();
            return false;
         return code;
       public static void main(String args[])
         Editor editor = new Editor();
         editor.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         editor.show();
    }

  • Adding JButton to JScrollPane

    Hi there,
    Just a quick request to look at this piece of code and see what I might be doing wrong... I'm trying to add a JButton to the bottom left of a JScrollPane using this code...
    private JScrollPane resultsPane;
    private JTextArea resultsArea;
    private JButton saveResultsButton;
    Container container = getContentPane();
    resultsPane = new JScrollPane(resultsArea);
    resultsPane.add(saveResultsButton);
    container.add(topPanel) // this is a JPanel containing 2 other panels...
    container.add(resultsPane, Borderlyout.SOUTH);The problem is that my 'saveResultsButton' is simply not being displayed. Anyone have any idea from this code what my error could be?
    Any help appreciated.

    Hi there,
    Just a quick request to look at this piece of code
    and see what I might be doing wrong... I'm trying to
    add a JButton to the bottom left of a JScrollPane
    using this code...
    private JScrollPane resultsPane;
    private JTextArea resultsArea;
    private JButton saveResultsButton;
    Container container = getContentPane();
    resultsPane = new JScrollPane(resultsArea);
    resultsPane.add(saveResultsButton);The JScrollPane merely adds the up and down scroll bars. You can't really add anything to a scrollbar. You probably don't want to add a JButton to the JTextArea either! Create another JPanel and add(resultsPane) to it then add(saveResultsButton) to it. Then add the JPanel to the container.

  • Search LinkedList and display to JtextArea

    The user will type in a first name and hit the "go" button. If the name is in the list it should say the person's name is in the list in the JTextArea, if not it should say the person's name is not in the list in the JTextArea. I have the basic layout, but am lost on how to get what the user typed in the JTextField and the button click and display to textarea to all play together.
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    public class FirstName extends JFrame {
         private static final String names[] = { "Joe", "Mark", "David", "Bryan","Amber","Abigail","Skyler","Melanie" };
         private javax.swing.JButton jButton1;
         private javax.swing.JTextArea jTextArea1;
         private javax.swing.JPanel jPanel1;
         private javax.swing.JTextField jTextField1;
         private java.awt.Label label1;
         public FirstName() {
              initComponents();
              List link = new LinkedList(Arrays.asList(names));     
              setSize( 400, 200 );
              show();
         private void initComponents() {
              jPanel1 = new JPanel();
             label1 = new Label();
              jTextField1 = new javax.swing.JTextField();
              jButton1 = new javax.swing.JButton();
              jTextArea1 = new javax.swing.JTextArea();
              label1.setText("Enter a Name to Search:");
              jPanel1.add(label1);
              jTextField1.setColumns(20);
              jPanel1.add(jTextField1);
              jButton1.setText("Go");
              jButton1.addMouseListener(new MouseAdapter() {
                   public void mouseClicked(MouseEvent evt) {
                        MouseClicked(evt);
              jPanel1.add(jButton1);
              jTextArea1.setColumns(30);
              jTextArea1.setRows(5);
              jPanel1.add(jTextArea1);
              getContentPane().add(jPanel1, BorderLayout.CENTER);
         private void MouseClicked(MouseEvent evt) {
         public static void main(String args[]) {
              FirstName application = new FirstName();
              application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    I'm getting a Syntax error on token "(",";"expected
    for actionPerformed, what is wrong?
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    public class FirstName extends JFrame {
         private String names[] =
                   "Joe",
                   "Mark",
                   "David",
                   "Bryan",
                   "Amber",
                   "Abigail",
                   "Skyler",
                   "Melanie" };
         private JButton jButton1;
         private JTextArea jTextArea1;
         private JPanel jPanel1;
         private JTextField jTextField1;
         private Label label1;
         public FirstName() {
              initComponents();
              List link = new LinkedList(Arrays.asList(names));
              setSize(400, 200);
              show();
         private void initComponents() {
              jPanel1 = new JPanel();
              label1 = new Label();
              jTextField1 = new javax.swing.JTextField();
              jButton1 = new javax.swing.JButton();
              jTextArea1 = new javax.swing.JTextArea();
              label1.setText("Enter a Name to Search:");
              jPanel1.add(label1);
              jTextField1.setColumns(20);
              jPanel1.add(jTextField1);
              JButton1 = new JButton1("  OK  ");
              jbutton1.addActionListener(new ActionListener(this));
              public void actionPerformed(ActionEvent e) {
                   String entered = jTextField1.getText();
                   // search for "entered" within the list    
                   if (found) {
                        jTextArea1.setText("found");
                   } else {
                        jTextArea1.setText("not found");
                   jPanel1.add(jButton1);
                   jTextArea1.setColumns(30);
                   jTextArea1.setRows(5);
                   jPanel1.add(jTextArea1);
                   getContentPane().add(jPanel1, BorderLayout.CENTER);
         public static void main(String args[]) {
              FirstName application = new FirstName();
              application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

  • JButton / Action performed

    Hi,
    I have an Interface class which builds an interface.
    On the interface is a Jbutton, and a Jtextarea.
    When this button is pressed the Interface class sends a message to an implementation class which carries out a service.
    The problem is that the program stalls until the implementation class performs all the code.
    The implementation class should send messages back to the text area updating the textArea with info, but instead it only updates at the end when all code in implementation class is performed.
    does anybody have any idea why it is doing this?

    The buttons action listener executes in swing thead whose primary job is to paint the screens.
    It looks like you are executing your "implementation code" in swing thread. If it takes a while to execute, the screen will stall/freeze.
    If my analysis is correct, try executing it in a worker thread..

  • Showing preview of downloaded pis fails

    Hi there (second try),
    this is a often discussed matter AFAIK. There are synchronizing Problems when downloading pics into a component that displays the pics. This could be solved by using imageObservers or MediaTracker Objects (I tried them, but they didn't work).
    So far. In my application I have a different way of retrieving pictures. First I read in a jpg-File via a DataInputStream and write it directly to the harddisk. then I open the file and put it in a JLabel for previewing. The Streamreading and the displaying are obviously unsynchronous.
    What I want is: Reading one File. Displaying it. Reading the next File. Display it etc. etc.
    What I get is: Reading, Reading, Reading, Displaying the last file.
    How can I handle this ? Is there a way to wait until the File is completley downloaded, display then the picture and start then to download the next pic?
    Below you find a listing of a reduced version of my app (it has unfortunatly still around 200 lines, but if you ignore that swing stuff in the constructor, the real code is short enough.). Its fully working if you want to try it (before starting: copy any jpg named "title.jpg" into the same dir. make sure the workDir (Line 20) exists).
    In the listing you will find methods that are responsible for downloading and displaying the Pics. These Methods are not too long.
    they are called:
    public void getAllPics() as a controlling method
    public void getThePic() for really downloading a pic
    public void showThePic() for Displaying the Pic in the JLabel
    Thanks
    - rebelman
    Here is the Listing:
    *  ProblemApp
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.io.*;
    import java.net.*;
    import java.util.Vector;
    public class ProblemApp extends JFrame {
         JCheckBox           previewBox;
         JLabel               previewLabel;
         JButton               browseButton, exitButton;
         JTextArea           myLogArea;
         JScrollPane      myLogScrollPane;
         JScrollPane          previewPane;
         String workDir = "c:\\";
         public ProblemApp() {                                             // **** Constructor
              super("Housten, we have a problem!");
              getContentPane().setLayout(new BorderLayout());
              // Preparing Button Area
              browseButton                     = new JButton("Start   Download");
              exitButton                          = new JButton("Exit Application");
              // Preparing logging area
              myLogArea                          = new JTextArea("Log:", 6, 40);
              myLogArea.setLineWrap(true);                    // Wordwrap on
              myLogArea.setWrapStyleWord(true);               // Wrap on word borders
              myLogArea.setEditable(false);                    // not editable
              myLogScrollPane                = new JScrollPane(myLogArea);
              // Preparing Preview Area
              previewBox                          = new JCheckBox("Preview on");
              previewBox.setMnemonic(KeyEvent.VK_P);
              previewBox.setSelected(true);
              previewLabel                    = new JLabel(new ImageIcon("title.jpg", "titlepic"));
              previewPane                         = new JScrollPane(previewLabel);
              // Defining panels
              JPanel topPanel                    = new JPanel();
              JPanel middlePanel               = new JPanel();
              JPanel bottomPanel                = new JPanel();
              JPanel browseButtonPanel     = new JPanel();
              JPanel exitButtonPanel          = new JPanel();
              JPanel previewPanel               = new JPanel();
              JPanel picPanel                    = new JPanel();
              // Defining Layoutmanagers for Panels
              topPanel.setLayout(new GridLayout(1,2));                               // top Panel for Upper Panels
              middlePanel.setLayout(new BorderLayout());                               // middle Panel for middle Panels
              bottomPanel.setLayout(new BorderLayout());                               // bottom panel for logging
              browseButtonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));     // Panel for browseButt (for width)
              exitButtonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));     // Panel for exit Butt (for width)
              picPanel.setLayout(new GridLayout(1,1));                               // pic panel for the pic
              previewPanel.setLayout(new FlowLayout(FlowLayout.LEFT));          // Panel for the Preview Box
              // Adding components to panels
              browseButtonPanel.add(browseButton);
              exitButtonPanel.add(exitButton);
              picPanel.add(previewPane);
              previewPanel.add(previewBox);
              topPanel.add(browseButtonPanel);
              topPanel.add(exitButtonPanel);
              middlePanel.add(previewPanel, BorderLayout.NORTH);
              middlePanel.add(picPanel, BorderLayout.CENTER);
              bottomPanel.add(myLogScrollPane);
              // adding panels to frame
              getContentPane().add(topPanel, BorderLayout.NORTH);
              getContentPane().add(middlePanel, BorderLayout.CENTER);
              getContentPane().add(bottomPanel, BorderLayout.SOUTH);
              this.enableEvents(AWTEvent.WINDOW_EVENT_MASK);                    // enabling events (window closing)
              // ActionListener for Start Download Button
              browseButton.addActionListener(new ActionListener() {          // anonymous Class for start Download
                   public void actionPerformed(ActionEvent e) {
                        getAllPics();                                                  // calling method below
              // Action Listner, for exiting the Application
              ActionListener exitListener = new ActionListener() {           // anonymous Class exitListener
                   public void actionPerformed(ActionEvent e) {
                        dispose();
                        System.exit(0);
              exitButton.addActionListener(exitListener);                         // Register exitListener to Exitbutton
         }                                                                                // **** end of Constructor
         //Method for downloading all the pics
         // The caller for getAllPics must make sure, that the workDir allready exists
         public void getAllPics() {
              String theFilename;
              String myURL;
              Vector theList = new Vector(4,4);
              theList = getList();                                        // Trying to get a list of picture URL's
              for(int i = 0; i < theList.size() ; i++) {
                   myURL = theList.elementAt(i).toString();
                   if(myURL.toLowerCase().endsWith(".jpg")) {          // its a JPG: No problem, get it!
                        theFilename = workDir+"pic"+i+".jpg";          // workDir defined above. make sure it exists
                        getThePic(myURL, theFilename);                    // really getting a pic now
                        showThePic(theFilename);                         // Displaying the preview
                   else {
                        addLine("This is not a JPG. Trying this later. ");
                        addLine(myURL);
         // Method for downloading a pic when I know its URL and a valid Path icl. pic-filename
         public void getThePic(String theURL, String thePath) {               //complete URL of the PIC, and complete path
              byte thisByte;
              DataOutputStream picFile =null;
              try {
                   URL myURL = new URL(theURL);
                   try {
                        DataInputStream myPic = new DataInputStream(myURL.openStream());
                        picFile = makeOutputFile(thePath);               // getting output-stream
                        try {
                             addLine("Read: "+theURL);
                             while (true) {
                                  thisByte = (byte)myPic.readByte();
                                  picFile.writeByte(thisByte);
                        catch(EOFException e){ // File complete
                   catch(Exception e) {
                        addLine("Error while reading the pic!");
              catch(MalformedURLException mue) {
                   addLine("Error in the URL!");
              finally {
                   try {
                        picFile.flush();
                        picFile.close();
                        addLine("Saved as: "+thePath);
                   catch(IOException e){
         } // end of method getThePic()
         // Method for showing the given Pic
         public void showThePic(String thePath) {
              if(previewBox.isSelected())
                   previewLabel.setIcon(new ImageIcon(thePath));
         // Method for the Pic Saver, that creates the outputstream
         public DataOutputStream makeOutputFile(String thePath) {
              FileOutputStream fileOut =null;
              try {
                   fileOut = new FileOutputStream(thePath);     // give it the path, INCLUDING the filename
              catch(IOException e){
                   addLine("Error while creating the output file!");
              return new DataOutputStream(fileOut);
         //Method for creating a URL List in a Vector
         public Vector getList() {
              Vector theList = new Vector(4,4);
              theList.addElement("http://user.cs.tu-berlin.de/~karlb/tux/sysadminsparadise.jpg");
              theList.addElement("http://user.cs.tu-berlin.de/~karlb/tux/tuxblackbig.jpg");
              theList.addElement("http://user.cs.tu-berlin.de/~karlb/tux/Toasted.jpg");
              theList.addElement("http://www.apple.com/hotnews/features/mwsf99pics/lara.jpg");
              theList.addElement("http://www.empireonline.co.uk/img/features/events/tombraider/premiere/lara.jpg");
              return theList;
         // Method for appending Logmessages to the log area
         public void addLine(String newLine) {
              myLogArea.append("\n" + newLine);
              JViewport vp = myLogScrollPane.getViewport();
              int height = Math.max(0, this.getSize().height - vp.getHeight());
              vp.scrollRectToVisible(new Rectangle(0, height, vp.getWidth(), vp.getHeight()));
         public static void main(String[] arg) {                                                       //Mainmethod
               ProblemApp myWindow = new ProblemApp();
               myWindow.pack();
               myWindow.show();
    }

    Apple - Mac OS X - Feedback

  • DLoading Pic, Displaying, Sync Prob

    Hi there,
    this is a often discussed matter AFAIK. There are synchronizing Problems when downloading pics into a component that displays the pics. This could be solved by using imageObservers or MediaTracker Objects.
    So far. In my application I have a different way of retrieving pictures. First I read in a jpg-File via a DataInputStream and write it directly to the harddisk. then I open the file and put it in a JLabel for previewing. The Streamreading and the displaying are obviously unsynchronous.
    What I want is: Reading one File. Displaying it. Reading the next File. Display it etc. etc.
    What I get is: Reading, Reading, Reading, Displaying the last file.
    How can I handle this ? Is there a way to wait until the File is completley downloaded, display then the picture and start then to download the next pic?
    Below you find a listing of a reduced version of my app (it has unfortunatly still around 200 lines). Its fully working if you want to try it (before starting: copy any jpg named "title.jpg" into the same dir. make sure the workDir (Line 20) exists).
    In the listing you will find methods that are responsible for downloading and displaying the Pics. These Methods are not too long.
    its:
    public void getAllPics() as a controlling method
    public void getThePic() for really downloading a pic
    public void showThePic() for Displaying the Pic in the JLabel
    Thanks
    - rebelman
    Here is the Listing:
    *  ProblemApp
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.io.*;
    import java.net.*;
    import java.util.Vector;
    public class ProblemApp extends JFrame {
         JCheckBox           previewBox;
         JLabel               previewLabel;
         JButton               browseButton, exitButton;
         JTextArea           myLogArea;
         JScrollPane      myLogScrollPane;
         JScrollPane          previewPane;
         String workDir = "c:\\";
         public ProblemApp() {                                             // **** Constructor
              super("Housten, we have a problem!");
              getContentPane().setLayout(new BorderLayout());
              // Preparing Button Area
              browseButton                     = new JButton("Start   Download");
              exitButton                          = new JButton("Exit Application");
              // Preparing logging area
              myLogArea                          = new JTextArea("Log:", 6, 40);
              myLogArea.setLineWrap(true);                    // Wordwrap on
              myLogArea.setWrapStyleWord(true);               // Wrap on word borders
              myLogArea.setEditable(false);                    // not editable
              myLogScrollPane                = new JScrollPane(myLogArea);
              // Preparing Preview Area
              previewBox                          = new JCheckBox("Preview on");
              previewBox.setMnemonic(KeyEvent.VK_P);
              previewBox.setSelected(true);
              previewLabel                    = new JLabel(new ImageIcon("title.jpg", "titlepic"));
              previewPane                         = new JScrollPane(previewLabel);
              // Defining panels
              JPanel topPanel                    = new JPanel();
              JPanel middlePanel               = new JPanel();
              JPanel bottomPanel                = new JPanel();
              JPanel browseButtonPanel     = new JPanel();
              JPanel exitButtonPanel          = new JPanel();
              JPanel previewPanel               = new JPanel();
              JPanel picPanel                    = new JPanel();
              // Defining Layoutmanagers for Panels
              topPanel.setLayout(new GridLayout(1,2));                               // top Panel for Upper Panels
              middlePanel.setLayout(new BorderLayout());                               // middle Panel for middle Panels
              bottomPanel.setLayout(new BorderLayout());                               // bottom panel for logging
              browseButtonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));     // Panel for browseButt (for width)
              exitButtonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));     // Panel for exit Butt (for width)
              picPanel.setLayout(new GridLayout(1,1));                               // pic panel for the pic
              previewPanel.setLayout(new FlowLayout(FlowLayout.LEFT));          // Panel for the Preview Box
              // Adding components to panels
              browseButtonPanel.add(browseButton);
              exitButtonPanel.add(exitButton);
              picPanel.add(previewPane);
              previewPanel.add(previewBox);
              topPanel.add(browseButtonPanel);
              topPanel.add(exitButtonPanel);
              middlePanel.add(previewPanel, BorderLayout.NORTH);
              middlePanel.add(picPanel, BorderLayout.CENTER);
              bottomPanel.add(myLogScrollPane);
              // adding panels to frame
              getContentPane().add(topPanel, BorderLayout.NORTH);
              getContentPane().add(middlePanel, BorderLayout.CENTER);
              getContentPane().add(bottomPanel, BorderLayout.SOUTH);
              this.enableEvents(AWTEvent.WINDOW_EVENT_MASK);                    // enabling events (window closing)
              // ActionListener for Start Download Button
              browseButton.addActionListener(new ActionListener() {          // anonymous Class for start Download
                   public void actionPerformed(ActionEvent e) {
                        getAllPics();                                                  // calling method below
              // Action Listner, for exiting the Application
              ActionListener exitListener = new ActionListener() {           // anonymous Class exitListener
                   public void actionPerformed(ActionEvent e) {
                        dispose();
                        System.exit(0);
              exitButton.addActionListener(exitListener);                         // Register exitListener to Exitbutton
         }                                                                                // **** end of Constructor
         //Method for downloading all the pics
         // The caller for getAllPics must make sure, that the workDir allready exists
         public void getAllPics() {
              String theFilename;
              String myURL;
              Vector theList = new Vector(4,4);
              theList = getList();                                        // Trying to get a list of picture URL's
              for(int i = 0; i < theList.size() ; i++) {
                   myURL = theList.elementAt(i).toString();
                   if(myURL.toLowerCase().endsWith(".jpg")) {          // its a JPG: No problem, get it!
                        theFilename = workDir+"pic"+i+".jpg";          // workDir defined above. make sure it exists
                        getThePic(myURL, theFilename);                    // really getting a pic now
                        showThePic(theFilename);                         // Displaying the preview
                   else {
                        addLine("This is not a JPG. Trying this later. ");
                        addLine(myURL);
         // Method for downloading a pic when I know its URL and a valid Path icl. pic-filename
         public void getThePic(String theURL, String thePath) {               //complete URL of the PIC, and complete path
              byte thisByte;
              DataOutputStream picFile =null;
              try {
                   URL myURL = new URL(theURL);
                   try {
                        DataInputStream myPic = new DataInputStream(myURL.openStream());
                        picFile = makeOutputFile(thePath);               // getting output-stream
                        try {
                             addLine("Read: "+theURL);
                             while (true) {
                                  thisByte = (byte)myPic.readByte();
                                  picFile.writeByte(thisByte);
                        catch(EOFException e){ // File complete
                   catch(Exception e) {
                        addLine("Error while reading the pic!");
              catch(MalformedURLException mue) {
                   addLine("Error in the URL!");
              finally {
                   try {
                        picFile.flush();
                        picFile.close();
                        addLine("Saved as: "+thePath);
                   catch(IOException e){
         } // end of method getThePic()
         // Method for showing the given Pic
         public void showThePic(String thePath) {
              if(previewBox.isSelected())
                   previewLabel.setIcon(new ImageIcon(thePath));
         // Method for the Pic Saver, that creates the outputstream
         public DataOutputStream makeOutputFile(String thePath) {
              FileOutputStream fileOut =null;
              try {
                   fileOut = new FileOutputStream(thePath);     // give it the path, INCLUDING the filename
              catch(IOException e){
                   addLine("Error while creating the output file!");
              return new DataOutputStream(fileOut);
         //Method for creating a URL List in a Vector
         public Vector getList() {
              Vector theList = new Vector(4,4);
              theList.addElement("http://user.cs.tu-berlin.de/~karlb/tux/sysadminsparadise.jpg");
              theList.addElement("http://user.cs.tu-berlin.de/~karlb/tux/tuxblackbig.jpg");
              theList.addElement("http://user.cs.tu-berlin.de/~karlb/tux/Toasted.jpg");
              theList.addElement("http://www.apple.com/hotnews/features/mwsf99pics/lara.jpg");
              theList.addElement("http://www.empireonline.co.uk/img/features/events/tombraider/premiere/lara.jpg");
              return theList;
         // Method for appending Logmessages to the log area
         public void addLine(String newLine) {
              myLogArea.append("\n" + newLine);
              JViewport vp = myLogScrollPane.getViewport();
              int height = Math.max(0, this.getSize().height - vp.getHeight());
              vp.scrollRectToVisible(new Rectangle(0, height, vp.getWidth(), vp.getHeight()));
         public static void main(String[] arg) {                                                       //Mainmethod
               ProblemApp myWindow = new ProblemApp();
               myWindow.pack();
               myWindow.show();
    }

    Hi there,
    this is a often discussed matter AFAIK. There are synchronizing Problems when downloading pics into a component that displays the pics. This could be solved by using imageObservers or MediaTracker Objects.
    So far. In my application I have a different way of retrieving pictures. First I read in a jpg-File via a DataInputStream and write it directly to the harddisk. then I open the file and put it in a JLabel for previewing. The Streamreading and the displaying are obviously unsynchronous.
    What I want is: Reading one File. Displaying it. Reading the next File. Display it etc. etc.
    What I get is: Reading, Reading, Reading, Displaying the last file.
    How can I handle this ? Is there a way to wait until the File is completley downloaded, display then the picture and start then to download the next pic?
    Below you find a listing of a reduced version of my app (it has unfortunatly still around 200 lines). Its fully working if you want to try it (before starting: copy any jpg named "title.jpg" into the same dir. make sure the workDir (Line 20) exists).
    In the listing you will find methods that are responsible for downloading and displaying the Pics. These Methods are not too long.
    its:
    public void getAllPics() as a controlling method
    public void getThePic() for really downloading a pic
    public void showThePic() for Displaying the Pic in the JLabel
    Thanks
    - rebelman
    Here is the Listing:
    *  ProblemApp
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.io.*;
    import java.net.*;
    import java.util.Vector;
    public class ProblemApp extends JFrame {
         JCheckBox           previewBox;
         JLabel               previewLabel;
         JButton               browseButton, exitButton;
         JTextArea           myLogArea;
         JScrollPane      myLogScrollPane;
         JScrollPane          previewPane;
         String workDir = "c:\\";
         public ProblemApp() {                                             // **** Constructor
              super("Housten, we have a problem!");
              getContentPane().setLayout(new BorderLayout());
              // Preparing Button Area
              browseButton                     = new JButton("Start   Download");
              exitButton                          = new JButton("Exit Application");
              // Preparing logging area
              myLogArea                          = new JTextArea("Log:", 6, 40);
              myLogArea.setLineWrap(true);                    // Wordwrap on
              myLogArea.setWrapStyleWord(true);               // Wrap on word borders
              myLogArea.setEditable(false);                    // not editable
              myLogScrollPane                = new JScrollPane(myLogArea);
              // Preparing Preview Area
              previewBox                          = new JCheckBox("Preview on");
              previewBox.setMnemonic(KeyEvent.VK_P);
              previewBox.setSelected(true);
              previewLabel                    = new JLabel(new ImageIcon("title.jpg", "titlepic"));
              previewPane                         = new JScrollPane(previewLabel);
              // Defining panels
              JPanel topPanel                    = new JPanel();
              JPanel middlePanel               = new JPanel();
              JPanel bottomPanel                = new JPanel();
              JPanel browseButtonPanel     = new JPanel();
              JPanel exitButtonPanel          = new JPanel();
              JPanel previewPanel               = new JPanel();
              JPanel picPanel                    = new JPanel();
              // Defining Layoutmanagers for Panels
              topPanel.setLayout(new GridLayout(1,2));                               // top Panel for Upper Panels
              middlePanel.setLayout(new BorderLayout());                               // middle Panel for middle Panels
              bottomPanel.setLayout(new BorderLayout());                               // bottom panel for logging
              browseButtonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));     // Panel for browseButt (for width)
              exitButtonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));     // Panel for exit Butt (for width)
              picPanel.setLayout(new GridLayout(1,1));                               // pic panel for the pic
              previewPanel.setLayout(new FlowLayout(FlowLayout.LEFT));          // Panel for the Preview Box
              // Adding components to panels
              browseButtonPanel.add(browseButton);
              exitButtonPanel.add(exitButton);
              picPanel.add(previewPane);
              previewPanel.add(previewBox);
              topPanel.add(browseButtonPanel);
              topPanel.add(exitButtonPanel);
              middlePanel.add(previewPanel, BorderLayout.NORTH);
              middlePanel.add(picPanel, BorderLayout.CENTER);
              bottomPanel.add(myLogScrollPane);
              // adding panels to frame
              getContentPane().add(topPanel, BorderLayout.NORTH);
              getContentPane().add(middlePanel, BorderLayout.CENTER);
              getContentPane().add(bottomPanel, BorderLayout.SOUTH);
              this.enableEvents(AWTEvent.WINDOW_EVENT_MASK);                    // enabling events (window closing)
              // ActionListener for Start Download Button
              browseButton.addActionListener(new ActionListener() {          // anonymous Class for start Download
                   public void actionPerformed(ActionEvent e) {
                        getAllPics();                                                  // calling method below
              // Action Listner, for exiting the Application
              ActionListener exitListener = new ActionListener() {           // anonymous Class exitListener
                   public void actionPerformed(ActionEvent e) {
                        dispose();
                        System.exit(0);
              exitButton.addActionListener(exitListener);                         // Register exitListener to Exitbutton
         }                                                                                // **** end of Constructor
         //Method for downloading all the pics
         // The caller for getAllPics must make sure, that the workDir allready exists
         public void getAllPics() {
              String theFilename;
              String myURL;
              Vector theList = new Vector(4,4);
              theList = getList();                                        // Trying to get a list of picture URL's
              for(int i = 0; i < theList.size() ; i++) {
                   myURL = theList.elementAt(i).toString();
                   if(myURL.toLowerCase().endsWith(".jpg")) {          // its a JPG: No problem, get it!
                        theFilename = workDir+"pic"+i+".jpg";          // workDir defined above. make sure it exists
                        getThePic(myURL, theFilename);                    // really getting a pic now
                        showThePic(theFilename);                         // Displaying the preview
                   else {
                        addLine("This is not a JPG. Trying this later. ");
                        addLine(myURL);
         // Method for downloading a pic when I know its URL and a valid Path icl. pic-filename
         public void getThePic(String theURL, String thePath) {               //complete URL of the PIC, and complete path
              byte thisByte;
              DataOutputStream picFile =null;
              try {
                   URL myURL = new URL(theURL);
                   try {
                        DataInputStream myPic = new DataInputStream(myURL.openStream());
                        picFile = makeOutputFile(thePath);               // getting output-stream
                        try {
                             addLine("Read: "+theURL);
                             while (true) {
                                  thisByte = (byte)myPic.readByte();
                                  picFile.writeByte(thisByte);
                        catch(EOFException e){ // File complete
                   catch(Exception e) {
                        addLine("Error while reading the pic!");
              catch(MalformedURLException mue) {
                   addLine("Error in the URL!");
              finally {
                   try {
                        picFile.flush();
                        picFile.close();
                        addLine("Saved as: "+thePath);
                   catch(IOException e){
         } // end of method getThePic()
         // Method for showing the given Pic
         public void showThePic(String thePath) {
              if(previewBox.isSelected())
                   previewLabel.setIcon(new ImageIcon(thePath));
         // Method for the Pic Saver, that creates the outputstream
         public DataOutputStream makeOutputFile(String thePath) {
              FileOutputStream fileOut =null;
              try {
                   fileOut = new FileOutputStream(thePath);     // give it the path, INCLUDING the filename
              catch(IOException e){
                   addLine("Error while creating the output file!");
              return new DataOutputStream(fileOut);
         //Method for creating a URL List in a Vector
         public Vector getList() {
              Vector theList = new Vector(4,4);
              theList.addElement("http://user.cs.tu-berlin.de/~karlb/tux/sysadminsparadise.jpg");
              theList.addElement("http://user.cs.tu-berlin.de/~karlb/tux/tuxblackbig.jpg");
              theList.addElement("http://user.cs.tu-berlin.de/~karlb/tux/Toasted.jpg");
              theList.addElement("http://www.apple.com/hotnews/features/mwsf99pics/lara.jpg");
              theList.addElement("http://www.empireonline.co.uk/img/features/events/tombraider/premiere/lara.jpg");
              return theList;
         // Method for appending Logmessages to the log area
         public void addLine(String newLine) {
              myLogArea.append("\n" + newLine);
              JViewport vp = myLogScrollPane.getViewport();
              int height = Math.max(0, this.getSize().height - vp.getHeight());
              vp.scrollRectToVisible(new Rectangle(0, height, vp.getWidth(), vp.getHeight()));
         public static void main(String[] arg) {                                                       //Mainmethod
               ProblemApp myWindow = new ProblemApp();
               myWindow.pack();
               myWindow.show();
    }

  • Not Printing Full Image

    Hello,
    I'm new to prinitng in Java, and I'm trying to simply send the contents of a JTextArea to the printer, but I have two issues with the results that come out of my printer.
    1) After hitting the writeButton a few times to create text in the text area, it appears fine on the screen, however when I print the page, it cuts out the beginning of every sentence, so my printout is full of lines that read: "e this prints someday!!!!!!! rather than "Lets hope this prints someday!!!!! . I'm on a network, so I sent the job to multiple printers, and it still does the same thing....so it's definitely my code.
    2) The print job always comes out as portrait, even if I take out the comments in my code to try and force landscape, or even if I just choose in the print dialogue box to print landscape.....it always comes out portrait.
    I know I'm catching the JTextArea text somewhat, but I don't think I'm rendering it to the printer correctly. Eventually, the "write" button will actually be renamed and read a file off of a server and display the text file on the screen. I would then like the user to be able to use the print button to print a report of the text on screen.
    One last thing....Is there a way I can make this an Applet, and not have to write a securityPolicyManager for the print functions to work????
    Thanks!
    Here is my code:
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.geom.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.print.PrinterJob;
    import java.awt.print.*;
    public class Print2 extends JPanel
                                 implements Printable, ActionListener {
        //NEW VARIABLES FOR SWING APPLICATION
        static private final String newline = "\n";
        JFrame frame;
        JButton writeButton, printButton;
        JTextArea log;
        public Print2() {
            super(new BorderLayout());
            log = new JTextArea(30,60);
            log.setMargin(new Insets(5,5,5,5));
            log.setEditable(false);
            JScrollPane logScrollPane = new JScrollPane(log);
            //Create the open button
            writeButton = new JButton("Write Sample Text");
            writeButton.addActionListener(this);
            //Create the save button
         printButton = new JButton("Print");
            printButton.addActionListener(this);
            //For layout purposes, put the buttons in a separate panel
            JPanel buttonPanel = new JPanel(); //use FlowLayout
            buttonPanel.add(writeButton);
            buttonPanel.add(printButton);
            //Add the buttons and the log to this panel.
            add(buttonPanel, BorderLayout.PAGE_START);
            add(logScrollPane, BorderLayout.CENTER);
        public void actionPerformed(ActionEvent e) {
            //Handle open button action.
            if (e.getSource() == writeButton) {
              log.append("Let's hope this prints someday!!!!!!!\n");
         //Handle open button action.
            if (e.getSource() == printButton) {
              log.append("test print button\n");
              PrinterJob printJob = PrinterJob.getPrinterJob();
                     printJob.setPrintable(this);
                 if (printJob.printDialog()) {
                          try {
                                                    //Tried adding these lines here to print Landscape, but it still prints PORTRAIT
                       //PageFormat landscape = printJob.defaultPage();          
                       //landscape.setOrientation(PageFormat.LANDSCAPE);          
                                      printJob.print(); 
                          } catch (Exception ex) {
                                   ex.printStackTrace();
         public int print(Graphics g, PageFormat pf, int pi) throws PrinterException {
                 if (pi >= 1) {
                          return Printable.NO_SUCH_PAGE;
                   drawShapes((Graphics2D) g);
                      return Printable.PAGE_EXISTS;
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
              Graphics2D g2 = (Graphics2D) g;
              drawShapes(g2);
         public void drawShapes(Graphics2D g2){
              log.paint(g2);
        private static void createAndShowGUI() {
         try{
              UIManager.setLookAndFeel(
                          //UIManager.getSystemLookAndFeelClassName());
                   "com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
             } catch (Exception e) { }
            //Create and set up the window.
            JFrame frame = new JFrame("Print Tester");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Create and set up the content pane.
            JComponent newContentPane = new Print2();
            newContentPane.setOpaque(true);
            frame.setContentPane(newContentPane);
            //Display the window.
            frame.pack();
            frame.setVisible(true);
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();

    The graphics object passed to the print method has (0,0) as the coordinates of a corner of the paper.
    (Which corner depends on your orientation.) But pages are printed with margins (usually 25mm=1inch)
    on all sides -- that is why text is being clipped. To fix this, use the imageableX/Y properties
    of PageFormat:
    public int print(Graphics g, PageFormat pf, int pi) throws PrinterException {
        if (pi >= 1)
            return Printable.NO_SUCH_PAGE;
        Graphics2D g2 = (Graphics2D) g;
        double x = pf.getImageableX();
        double y = pf.getImageableY();
        g2.translate(x, y);
        drawShapes(g2);
        return Printable.PAGE_EXISTS;
    }As far as portait/landscape mode: letting the user choose in the page setup dialog works for me:
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == writeButton)
            log.append("Let's hope this prints someday!!!!!!!\n");
        if (e.getSource() == printButton) {
            log.append("test print button\n");
            PrinterJob printJob = PrinterJob.getPrinterJob();
            PageFormat pf = printJob.defaultPage();
            pf = printJob.pageDialog(pf);
            printJob.setPrintable(this, pf);
            if (printJob.printDialog()) {
                try {
                    printJob.print();
                } catch (PrinterException ex) {
                    ex.printStackTrace();
    }Or you can explicitly set the orientation:
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == writeButton)
            log.append("Let's hope this prints someday!!!!!!!\n");
        if (e.getSource() == printButton) {
            log.append("test print button\n");
            PrinterJob printJob = PrinterJob.getPrinterJob();
            PageFormat pf = printJob.defaultPage();
            pf.setOrientation(PageFormat.LANDSCAPE);
            printJob.setPrintable(this, pf);
            if (printJob.printDialog()) {
                try {
                    printJob.print();
                } catch (PrinterException ex) {
                    ex.printStackTrace();
    }Finally, having a displayed page range of 1-9999 may be disconcerting to users!
    The way around that is to print a Pageable, not a Printable object. The standard
    Pageable object, a Book, is easy to work with. Here I let the user choose orientation,
    but you could choose it as I did above:
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == writeButton)
            log.append("Let's hope this prints someday!!!!!!!\n");
        if (e.getSource() == printButton) {
            log.append("test print button\n");
            PrinterJob printJob = PrinterJob.getPrinterJob();
            PageFormat pf = printJob.defaultPage();
            pf = printJob.pageDialog(pf);
            Book book = new Book();
            book.append(this, pf);
            printJob.setPageable(book);
            if (printJob.printDialog()) {
                try {
                    printJob.print();
                } catch (PrinterException ex) {
                    ex.printStackTrace();
    }

  • How to create a custom focus manager in jdk1.4

    Dear All,
    I'm now trying to create a form for user to submit data. The key tab are easily to tab between textfields in html, you can set whatever order you want. But when I tried to create a form using java, I found very hard to do so. Any reference link and examples are appreciate.
    Thanks in advance
    Kitty

    cat8888,
    In general, tab-order is usaually the order you've added to the Panel / JPanel. When Panel is added to Panel and that to Panel and so on, sometimes the order can become less clear. When "trapped" inside a TextArea / JTextArea, the tab key takes on it's own meaning and now it wants to tab inside the TextArea. For this, you'll need special coding. For example, you might try adding code like this:
    myTextAreaObject.addKeyListener( new KeyAdapter() {
    public void keyPressed(KeyEvent ke) {
    if ( ke.getKeyCode() == ke.VK_TAB ) {
    myNextButtonObject.requestFocus();
    ... which effectively forces focus on - in this case - the JButton following the JTextArea.
    Not sure if this is what you mean, but HTH. And by the way, if someone has a neater way t odo this, I'd also like to know.
    ~Bill

Maybe you are looking for

  • Problem with international characters showing up as junk

    Hi All, Little question. I've made a xml data template which executes a query to fetch person names from the e-business suite tables. However there are international characters in the names which are showing up incorrectly. When executing the query i

  • Cracked screen

    I have an HP 15 notebook and the screen is cracked. I am trying to see how I can connect it to an HP v75 external monitor. Please advise

  • Drag and Drop Survey Link into Mail Forms

    Hi Experts, I have below client requirement regarding mail forms. Query:  Is it possible to drag and drop survey link into mail form ? To be best my knowledge we need to insert survey link manually into  mail form. Your help is highly appreciated. Th

  • Transistions turn to black

    When I apply transitions between clips they play back as black. Preview shows the desired transition effect, but playback of the transition is black. This is only happening between clips. The same transition will work properly when applied between tw

  • Why doesn't my phone always send me a text alert?

    WHy doesn't my iphone4S always send me a text alert?