2013-01-25 44 views
-1

我有一個帶有頁面導航按鈕,打印,搜索按鈕的jframe。當我單擊打印按鈕時,它完全打開窗口,我可以打印頁面但當我點擊搜索按鈕,我無法獲得窗口。我的要求是點擊搜索按鈕應打開一個窗口(與打印窗口相同)與文本字段,當我輸入搜索數據,然後它應該顯示比賽和不匹配。單擊JFrame中的搜索按鈕不打開JDialog

我試過下面的代碼,但我不成功。

import com.google.common.base.CharMatcher; 
import com.sun.pdfview.PDFFile; 
import com.sun.pdfview.PDFPage; 
import com.sun.pdfview.PDFRenderer; 
import com.sun.pdfview.PagePanel; 

import javax.print.attribute.HashPrintRequestAttributeSet; 
import javax.print.attribute.standard.PageRanges; 
import javax.swing.*; 

import java.awt.*; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.geom.AffineTransform; 
import java.awt.geom.Rectangle2D; 
import java.awt.print.PageFormat; 
import java.awt.print.Printable; 
import java.awt.print.PrinterException; 
import java.awt.print.PrinterJob; 
import java.io.File; 
import java.io.IOException; 
import java.io.RandomAccessFile; 
import java.nio.ByteBuffer; 
import java.nio.channels.FileChannel; 

import static com.google.common.base.Strings.isNullOrEmpty; 

public class PdfViewer extends JPanel { 
    private static enum Navigation { 
     GO_FIRST_PAGE, FORWARD, BACKWARD, GO_LAST_PAGE, GO_N_PAGE 
    } 

    private static final CharMatcher POSITIVE_DIGITAL = CharMatcher.anyOf(""); 
    private static final String GO_PAGE_TEMPLATE = "%s of %s"; 
    private static final int FIRST_PAGE = 1; 
    private int currentPage = FIRST_PAGE; 
    private JButton btnFirstPage; 
    private JButton btnPreviousPage; 
    private JTextField txtGoPage; 
    private JButton btnNextPage; 
    private JButton btnLastPage; 
    private JButton print; 
    private JButton search; 
    private PagePanel pagePanel; 
    private PDFFile pdfFile; 

    public PdfViewer() { 
     initial(); 
    } 

    private void initial() { 
     setLayout(new BorderLayout(0, 0)); 
     JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); 
     add(topPanel, BorderLayout.NORTH); 
     btnFirstPage = createButton("|<<"); 
     topPanel.add(btnFirstPage); 
     btnPreviousPage = createButton("<<"); 
     topPanel.add(btnPreviousPage); 
     txtGoPage = new JTextField(10); 
     txtGoPage.setHorizontalAlignment(JTextField.CENTER); 
     topPanel.add(txtGoPage); 
     btnNextPage = createButton(">>"); 
     topPanel.add(btnNextPage); 
     btnLastPage = createButton(">>|"); 
     topPanel.add(btnLastPage); 
     print = new JButton("print"); 
     topPanel.add(print); 
     search = new JButton("search"); 
     topPanel.add(search); 
     JScrollPane scrollPane = new JScrollPane(); 
     add(scrollPane, BorderLayout.CENTER); 
     JPanel viewPanel = new JPanel(new BorderLayout(0, 0)); 
     scrollPane.setViewportView(viewPanel); 

     pagePanel = new PagePanel(); 
     Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 
     pagePanel.setPreferredSize(screenSize); 
     viewPanel.add(pagePanel, BorderLayout.CENTER); 

     disableAllNavigationButton(); 

     btnFirstPage.addActionListener(new PageNavigationListener(Navigation.GO_FIRST_PAGE)); 
     btnPreviousPage.addActionListener(new PageNavigationListener(Navigation.BACKWARD)); 
     btnNextPage.addActionListener(new PageNavigationListener(Navigation.FORWARD)); 
     btnLastPage.addActionListener(new PageNavigationListener(Navigation.GO_LAST_PAGE)); 
     txtGoPage.addActionListener(new PageNavigationListener(Navigation.GO_N_PAGE)); 
     print.addActionListener(new PrintUIWindow()); 
     search.addActionListener(new Action1()); 
    } 

    static class Action1 implements ActionListener {   
      public void actionPerformed (ActionEvent e) { 
       JFrame parent = new JFrame(); 
       JDialog jDialog = new JDialog(); 
       Label label = new Label("Enter Word: "); 
       final JTextField jTextField = new JTextField(100); 
       JPanel panel = new JPanel(); 
       parent.add(panel); 
       panel.add(label); 
       panel.add(jTextField); 
       parent.setLocationRelativeTo(null); 
      } 
     } 

    private JButton createButton(String text) { 
     JButton button = new JButton(text); 
     button.setPreferredSize(new Dimension(55, 20)); 

     return button; 
    } 

    private void disableAllNavigationButton() { 
     btnFirstPage.setEnabled(false); 
     btnPreviousPage.setEnabled(false); 
     btnNextPage.setEnabled(false); 
     btnLastPage.setEnabled(false); 
    } 

    private boolean isMoreThanOnePage(PDFFile pdfFile) { 
     return pdfFile.getNumPages() > 1; 
    } 

    private class PageNavigationListener implements ActionListener { 
     private final Navigation navigation; 

     private PageNavigationListener(Navigation navigation) { 
      this.navigation = navigation; 
     } 

     public void actionPerformed(ActionEvent e) { 
      if (pdfFile == null) { 
       return; 
      } 

      int numPages = pdfFile.getNumPages(); 
      if (numPages <= 1) { 
       disableAllNavigationButton(); 
      } else { 
       if (navigation == Navigation.FORWARD && hasNextPage(numPages)) { 
        goPage(currentPage, numPages); 
       } 

       if (navigation == Navigation.GO_LAST_PAGE) { 
        goPage(numPages, numPages); 
       } 

       if (navigation == Navigation.BACKWARD && hasPreviousPage()) { 
        goPage(currentPage, numPages); 
       } 

       if (navigation == Navigation.GO_FIRST_PAGE) { 
        goPage(FIRST_PAGE, numPages); 
       } 

       if (navigation == Navigation.GO_N_PAGE) { 
        String text = txtGoPage.getText(); 
        boolean isValid = false; 
        if (!isNullOrEmpty(text)) { 
         boolean isNumber = POSITIVE_DIGITAL.matchesAllOf(text); 
         if (isNumber) { 
          int pageNumber = Integer.valueOf(text); 
          if (pageNumber >= 1 && pageNumber <= numPages) { 
           goPage(Integer.valueOf(text), numPages); 
           isValid = true; 
          } 
         } 
        } 

        if (!isValid) { 
         JOptionPane.showMessageDialog(PdfViewer.this, 
           format("Invalid page number '%s' in this document", text)); 
         txtGoPage.setText(format(GO_PAGE_TEMPLATE, currentPage, numPages)); 
        } 
       } 
      } 
     } 

     private void goPage(int pageNumber, int numPages) { 
      currentPage = pageNumber; 
      PDFPage page = pdfFile.getPage(currentPage); 
      pagePanel.showPage(page); 
      boolean notFirstPage = isNotFirstPage(); 
      btnFirstPage.setEnabled(notFirstPage); 
      btnPreviousPage.setEnabled(notFirstPage); 
      txtGoPage.setText(format(GO_PAGE_TEMPLATE, currentPage, numPages)); 
      boolean notLastPage = isNotLastPage(numPages); 
      btnNextPage.setEnabled(notLastPage); 
      btnLastPage.setEnabled(notLastPage); 
     } 

     private boolean hasNextPage(int numPages) { 
      return (++currentPage) <= numPages; 
     } 

     private boolean hasPreviousPage() { 
      return (--currentPage) >= FIRST_PAGE; 
     } 

     private boolean isNotLastPage(int numPages) { 
      return currentPage != numPages; 
     } 

     private boolean isNotFirstPage() { 
      return currentPage != FIRST_PAGE; 
     } 
    } 

    private class PrintUIWindow implements Printable, ActionListener { 

     /* 
     * (non-Javadoc) 
     * 
     * @see java.awt.print.Printable#print(java.awt.Graphics, 
     * java.awt.print.PageFormat, int) 
     */ 
     @Override 
     public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException { 
      int pagenum = pageIndex+1; 
       if (pagenum < 1 || pagenum > pdfFile.getNumPages()) 
        return NO_SUCH_PAGE; 

       Graphics2D g2d = (Graphics2D) graphics; 
       AffineTransform at = g2d.getTransform(); 

       PDFPage pdfPage = pdfFile.getPage (pagenum); 

       Dimension dim; 
       dim = pdfPage.getUnstretchedSize ((int) pageFormat.getImageableWidth(), 
               (int) pageFormat.getImageableHeight(), 
               pdfPage.getBBox()); 

       Rectangle bounds = new Rectangle ((int) pageFormat.getImageableX(), 
               (int) pageFormat.getImageableY(), 
               dim.width, 
               dim.height); 

       PDFRenderer rend = new PDFRenderer (pdfPage, (Graphics2D) graphics, bounds, 
                null, null); 
       try 
       { 
        pdfPage.waitForFinish(); 
        rend.run(); 
       } 
       catch (InterruptedException ie) 
       { 
        //JOptionPane.showMessageDialog (this, ie.getMessage()); 
       } 

       g2d.setTransform (at); 
       g2d.draw (new Rectangle2D.Double (pageFormat.getImageableX(), 
         pageFormat.getImageableY(), 
         pageFormat.getImageableWidth(), 
         pageFormat.getImageableHeight())); 

       return PAGE_EXISTS; 
     } 

     /* 
     * (non-Javadoc) 
     * 
     * @see 
     * java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent 
     *) 
     */ 
     @Override 
     public void actionPerformed(ActionEvent e) { 
      System.out.println("Inside action performed"); 
      PrinterJob printJob = PrinterJob.getPrinterJob(); 
      printJob.setPrintable(this); 
      try 
       { 
        HashPrintRequestAttributeSet attset; 
        attset = new HashPrintRequestAttributeSet(); 
        //attset.add (new PageRanges (1, pdfFile.getNumPages())); 
        if (printJob.printDialog (attset)) 
         printJob.print (attset); 
       } 
       catch (PrinterException pe) 
       { 
        //JOptionPane.showMessageDialog (this, pe.getMessage()); 
       } 

     } 

    } 

    public PagePanel getPagePanel() { 
     return pagePanel; 
    } 

    public void setPDFFile(PDFFile pdfFile) { 
     this.pdfFile = pdfFile; 
     currentPage = FIRST_PAGE; 
     disableAllNavigationButton(); 
     txtGoPage.setText(format(GO_PAGE_TEMPLATE, FIRST_PAGE, pdfFile.getNumPages())); 
     boolean moreThanOnePage = isMoreThanOnePage(pdfFile); 
     btnNextPage.setEnabled(moreThanOnePage); 
     btnLastPage.setEnabled(moreThanOnePage); 
    } 

    public static String format(String template, Object... args) { 
     template = String.valueOf(template); // null -> "null" 
     // start substituting the arguments into the '%s' placeholders 
     StringBuilder builder = new StringBuilder(template.length() + 16 * args.length); 
     int templateStart = 0; 
     int i = 0; 
     while (i < args.length) { 
      int placeholderStart = template.indexOf("%s", templateStart); 
      if (placeholderStart == -1) { 
       break; 
      } 
      builder.append(template.substring(templateStart, placeholderStart)); 
      builder.append(args[i++]); 
      templateStart = placeholderStart + 2; 
     } 
     builder.append(template.substring(templateStart)); 

     // if we run out of placeholders, append the extra args in square braces 
     if (i < args.length) { 
      builder.append(" ["); 
      builder.append(args[i++]); 
      while (i < args.length) { 
       builder.append(", "); 
       builder.append(args[i++]); 
      } 
      builder.append(']'); 
     } 

     return builder.toString(); 
    } 

    public static void main(String[] args) { 
     try { 
      long heapSize = Runtime.getRuntime().totalMemory(); 
      System.out.println("Heap Size = " + heapSize); 

      JFrame frame = new JFrame("PDF Test"); 
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

      // load a pdf from a byte buffer 
      File file = new File("/home/swarupa/Downloads/2626OS-Chapter-5-Advanced-Theme.pdf"); 
      RandomAccessFile raf = new RandomAccessFile(file, "r"); 
      FileChannel channel = raf.getChannel(); 
      ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()); 
      final PDFFile pdffile = new PDFFile(buf); 
      PdfViewer pdfViewer = new PdfViewer(); 
      pdfViewer.setPDFFile(pdffile); 
      frame.add(pdfViewer); 
      frame.pack(); 
      frame.setVisible(true); 

      PDFPage page = pdffile.getPage(0); 
      pdfViewer.getPagePanel().showPage(page); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

} 

我在哪裏做錯了。可以任何一點指向我。

+6

*我在哪裏做錯了* ...在這裏傾銷你的整個代碼是錯誤的。如果一個按鈕不起作用,那麼在發佈之前,減少您的代碼,直到它只包含該按鈕以及該按鈕後面的相關邏輯。請參閱[SSCCE](http://sscce.org) – Robin

+2

'1)'remove'pdf'(3rd。sides or custom APIs)'2)'爲什麼會有靜態類Action1實現ActionListener {'可以重新創建整個'GUI'' 3)'更好地幫助發佈一個[SSCCE](http://sscce.org/),簡短,可運行,可編譯,僅僅是關於'JFrame'和'JDialog',沒有其他任何東西 – mKorbel

回答

1

您創建了JDialogJFrame,爲什麼?你永遠不會調用setVisible(true),爲什麼?

你對Action1的期望是什麼?

+0

嗨StanislavL感謝給Action.From Action1我需要一個窗口,其中包含帶有textfield的標籤。 – aaaa

2

我想,這應該解決你的問題。)你忘了設置窗口可見:)

static class Action1 implements ActionListener {   
     public void actionPerformed (ActionEvent e) { 
      JFrame parent = new JFrame(); 
      JDialog jDialog = new JDialog(); 
      Label label = new Label("Enter Word: "); 
      final JTextField jTextField = new JTextField(100); 
      JPanel panel = new JPanel(); 
      parent.add(panel); 
      panel.add(label); 
      panel.add(jTextField); 
      parent.setLocationRelativeTo(null); 
      parent.setVisible(true); 
     } 
    } 

順便說一句,你爲什麼要創建的JDialog?

+0

嗨Dworza感謝您給予答覆。與上述代碼我得到一個文本框的框架。它是罰款。但框架有關閉(X),最小化( - ),還原按鈕。但我需要我的框架有隻有關閉選項作爲print.Thank你。 – aaaa

0

對不起,您發表評論的這篇回答作爲一篇新文章,但發表評論爲時太長。您無法刪除關閉並最小化JFrame中的按鈕。如果你想要一些沒有這些按鈕的窗口,你必須創建和定製你自己的JDialog。儘管如此,仍然會有一個關閉按鈕(X)。你可以讓你的JDialog未修飾,使之,當你實現這樣的行爲更像JFrame中:

class CustomizedDialog extends JDialog { 
public CustomizedDialog(JFrame frame, String str) { 
    super(frame, str); 
    super.setUndecorated(true); 
    addWindowListener(new WindowAdapter() { 
     public void windowClosing(WindowEvent evt) { 
      System.exit(0); 
     } 
    }); 
} 

}

然後你就可以用這個稱呼它在你的代碼:

CustomizedDialog myCustomizedDialog = new CustomizedDialog(new JFrame(), "My title"); 
JPanel panel = new JPanel(); 
panel.setSize(256, 256); 
myCustomizedDialog.add(panel); 
myCustomizedDialog.setSize(256, 256); 
myCustomizedDialog.setLocationRelativeTo(null); 
myCustomizedDialog.setVisible(true); 

我希望,這有助於:)