2015-05-10 5 views
2

Я пробовал каждый метод вставки области прокрутки внутри текстового поля, но каждый раз, когда он не показывал панель прокрутки. Вот полный код:JScrollPane не отображается в JTextArea

import java.awt.*; 
import javax.swing.*; 
import javax.swing.border.*; 
import javax.swing.SwingConstants.*; 
import java.awt.event.*; 
import java.util.*; 
import java.io.*; 
import java.text.DecimalFormat; 

public class Cart extends JFrame { 
    private JPanel contentPane; 
    BufferedReader in1 = null; 
    PrintWriter itemList = null; 
    String itemName, size, category; 
    int quantity; 
    double totalPrice, total = 0.00; 
    DecimalFormat formatter = new DecimalFormat("#, ##0.00"); 

    public Cart() { 
     setBounds(100, 100, 629, 439); 
     contentPane = new JPanel(); 
     contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); 
     setContentPane(contentPane); 
     contentPane.setLayout(null); 

     JLabel lblCart = new JLabel("CART"); 
     lblCart.setHorizontalAlignment(SwingConstants.CENTER); 
     lblCart.setFont(new Font("Sinhala Sangam MN", Font.BOLD, 23)); 
     lblCart.setBounds(6, 6, 617, 35); 
     contentPane.add(lblCart); 

     JButton btnConfirm = new JButton("Confirm"); 
     btnConfirm.setBounds(494, 382, 117, 29); 
     contentPane.add(btnConfirm); 

     JButton btnBack = new JButton("Continue Shopping"); 
     btnBack.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       new MenuPage(); 
       dispose(); 
      } 
     }); 
     btnBack.setBounds(345, 382, 148, 29); 
     contentPane.add(btnBack); 

     JButton btnDelete = new JButton("Delete"); 
     btnDelete.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       JOptionPane.showMessageDialog(null, "Need to remove item? Please resubmit your item from the menu page", "Delete Item?", JOptionPane.INFORMATION_MESSAGE); 
      } 
     }); 
     btnDelete.setBounds(16, 382, 117, 29); 
     contentPane.add(btnDelete); 

     JTextArea itemArea = new JTextArea(); 
     itemArea.setBackground(new Color(230, 230, 250)); 
     itemArea.setBounds(16, 53, 595, 308); 
     itemArea.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null)); 
     JScrollPane scroll = new JScrollPane(itemArea); 
     scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); 
     contentPane.add(itemArea); 
     contentPane.add(scroll); 

     try { 
      in1 = new BufferedReader(new FileReader("G2L.txt")); 
      itemList = new PrintWriter(new FileWriter("CartList.txt")); 

      String indata = null; 

      while ((indata = in1.readLine()) != null) { 
       StringTokenizer st = new StringTokenizer(indata, ";"); 

       itemName = st.nextToken(); 
       quantity = Integer.parseInt(st.nextToken()); 
       size = st.nextToken(); 
       totalPrice = Double.parseDouble(st.nextToken()); 
       category = st.nextToken(); 

       itemList.println("Item : " + itemName + "\nQuantity : " + quantity + "\nSize : " 
         + size + "\nCategory : " + category + "\nTotal : MYR " + formatter.format(totalPrice) + "\n"); 

       total = total + totalPrice; 
      } 
      in1.close(); 
      itemList.close(); 

      itemArea.read(new BufferedReader(new FileReader("CartList.txt")), null); 
     } catch (FileNotFoundException fnfe) { 
      System.out.println("File not found"); 
     } catch (IOException ioe) { 
      System.out.println(ioe.getMessage()); 
     } 

     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     setLocationRelativeTo(null); 
     setResizable(false); 
     setVisible(true); 
    } 

    public static void main(String args[]) { 
     Cart c = new Cart(); 
    } 
} 

Данные в текстовом файле G2L.txt является:

Ocean Blue;3;XXL;270.00 ;Formal Shirt 
Peach Pink;2;XL;211.00 ;Formal Shirt 
Grayed Out;1;M;88.50 ;Formal Shirt 
Black Slack;2;XL;211.00 ;Formal Shirt 

Я пропускаю что-то здесь? Любая помощь будет оценена по достоинству. Спасибо.

+0

См редактирует, чтобы ответить. –

ответ

2

Вы стреляете в ногу, используя нулевые макеты и setBounds.

В то время как пустые макеты и setBounds() могут показаться Swing новичками, как самый простой и лучший способ создания сложных графических интерфейсов, чем больше Swing GUI вы создадите более серьезные трудности, с которыми вы столкнетесь при их использовании. Они не будут изменять размеры ваших компонентов при изменении размера графического интерфейса, они являются королевской ведьмой для улучшения или поддержки, они полностью не выполняются при размещении в scrollpanes, они выглядят ужасно ужасно при просмотре на всех платформах или разрешениях экрана, отличных от исходного ,

Если вы установите границы JTextArea, вы полностью не можете расширять его, не позволяя работать с вашими прокрутками. Вместо этого задайте свойства столбца и строки JTextArea, избавьтесь от макетов null и используйте менеджеров компоновки, чтобы создавать красивые и легко отлаживаемые графические интерфейсы.

например,

import java.awt.BorderLayout; 
import java.awt.Font; 
import javax.swing.*; 

public class CartEg extends JPanel { 
    private static final long serialVersionUID = 1L; 
    private static final int GAP = 10; 
    private static final String TITLE_TEXT = "Some Great Title"; 
    private JTextArea itemArea = new JTextArea(25, 60); 

    public CartEg() { 
     // create centered title JLabel 
     JLabel titleLabel = new JLabel(TITLE_TEXT, SwingConstants.CENTER); 
     // make it big and bold 
     titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 42f)); 

     itemArea.setWrapStyleWord(true); 
     itemArea.setLineWrap(true); 
     JScrollPane scrollPane = new JScrollPane(itemArea); 

     JPanel bottomButtonPanel = new JPanel(); // panel to hold JButtons 
     bottomButtonPanel.setLayout(new BoxLayout(bottomButtonPanel, BoxLayout.LINE_AXIS)); 
     bottomButtonPanel.add(new JButton("Left Button")); 
     bottomButtonPanel.add(Box.createHorizontalGlue()); 
     bottomButtonPanel.add(new JButton("Right Button 1")); 
     bottomButtonPanel.add(new JButton("Right Button 2")); 

     // create some empty space around our components 
     setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP)); 
     // use a BorderLayout for the main JPanel 
     setLayout(new BorderLayout(GAP, GAP)); 

     // add JScrollPane to the BorderLayout.CENTER position 
     // add your JPanel that holds buttons to the BorderLayout.PAGE_END 
     // and add your title JLabel to the BorderLayout.PAGE_START position 

     add(scrollPane, BorderLayout.CENTER); 
     add(titleLabel, BorderLayout.PAGE_START); 
     add(bottomButtonPanel, BorderLayout.PAGE_END); 


    } 

    private static void createAndShowGui() { 
     CartEg mainPanel = new CartEg(); 

     JFrame frame = new JFrame("Cart Example"); 
     frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
     frame.getContentPane().add(mainPanel); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
      createAndShowGui(); 
     } 
     }); 
    } 
} 

Обратите внимание, что создать JTextArea с номером строки и столбца, переданных в конструктор. Затем я настроил JTextArea для обертывания слов. Я добавляю его в JScrollPane, а затем добавляю JScrollPane в положение BorderLayout.CENTER контейнера BorderLayout.


ред пример, который теперь использует AbstractAction, DisposeAction, и использует то же самое действие в обоих JButton и JMenuItem. Это позволяет при необходимости создавать JButton.

создать переменную DisposeAction и инициализировать его:

// create an Action that can be added to a JButton or a JMenuItem 
private Action disposeAction = new DisposeAction("Exit", KeyEvent.VK_X); 

кнопку, которая использует действие Создать и добавить к GUI одновременно:

// create jbutton that uses our dispose Action 
    bottomButtonPanel.add(new JButton(disposeAction)); 

Создание JMenuItem, который использует действие и добавить в JMenu одновременно :

// add a JMenuItem that uses the same disposeAction 
    fileMenu.add(new JMenuItem(disposeAction)); 

Вот код для частного внутреннего класса DisposeAction. Он немного запутан, так что он будет работать как для JButtons, так и для JMenuItems. Обратите внимание, что это может быть автономным, при желании, и он будет работать нормально:

private class DisposeAction extends AbstractAction { 
    private static final long serialVersionUID = 1L; 
    public DisposeAction(String name, int mnemonic) { 
    super(name); // set button's text 
    putValue(MNEMONIC_KEY, mnemonic); // set it's mnemonic key 
    } 

    @Override 
    public void actionPerformed(ActionEvent e) { 
    // get the button that caused this action 
    Object source = e.getSource(); 
    if (source instanceof AbstractButton) { 
     AbstractButton exitButton = (AbstractButton) source; 

     // get the parent top level window 
     Window topWindow = SwingUtilities.getWindowAncestor(exitButton); 
     if (topWindow == null) { // if null, then likely in a JMenuItem 
      // so we have to get its jpopupmenu parent 
      Container parent = exitButton.getParent(); 
      if (parent instanceof JPopupMenu) { 
       JPopupMenu popupMenu = (JPopupMenu) parent; 

       // get the invoker for the pop up menu 
       Component invoker = popupMenu.getInvoker(); 
       if (invoker != null) { 
       // and get *its* top level window 
       topWindow = SwingUtilities.getWindowAncestor(invoker); 
       } 
      } 
     } 
     if (topWindow != null) { 
      // dispose of the top-level window 
      topWindow.dispose(); 
     } 
    } 
    } 
} 

Полный пример:

import java.awt.BorderLayout; 
import java.awt.Component; 
import java.awt.Container; 
import java.awt.Font; 
import java.awt.Window; 
import java.awt.event.ActionEvent; 
import java.awt.event.KeyEvent; 
import javax.swing.*; 

public class CartEg extends JPanel { 
    private static final long serialVersionUID = 1L; 
    private static final int GAP = 10; 
    private static final String TITLE_TEXT = "Some Great Title"; 
    private JTextArea itemArea = new JTextArea(25, 60); 

    // create an Action that can be added to a JButton or a JMenuItem 
    private Action disposeAction = new DisposeAction("Exit", KeyEvent.VK_X); 
    private JMenuBar menuBar = new JMenuBar(); // menu bar for GUI 

    public CartEg() { 
     // create centered title JLabel 
     JLabel titleLabel = new JLabel(TITLE_TEXT, SwingConstants.CENTER); 
     // make it big and bold 
     titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 42f)); 

     itemArea.setWrapStyleWord(true); 
     itemArea.setLineWrap(true); 
     JScrollPane scrollPane = new JScrollPane(itemArea); 

     JPanel bottomButtonPanel = new JPanel(); // panel to hold JButtons 
     bottomButtonPanel.setLayout(new BoxLayout(bottomButtonPanel, BoxLayout.LINE_AXIS)); 
     bottomButtonPanel.add(new JButton("Left Button")); 
     bottomButtonPanel.add(Box.createHorizontalGlue()); 
     bottomButtonPanel.add(new JButton("Right Button 1")); 
     bottomButtonPanel.add(new JButton("Right Button 2")); 

     // create jbutton that uses our dispose Action 
     bottomButtonPanel.add(new JButton(disposeAction)); 

     // create some empty space around our components 
     setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP)); 
     // use a BorderLayout for the main JPanel 
     setLayout(new BorderLayout(GAP, GAP)); 

     // add JScrollPane to the BorderLayout.CENTER position 
     // add your JPanel that holds buttons to the BorderLayout.PAGE_END 
     // and add your title JLabel to the BorderLayout.PAGE_START position 

     add(scrollPane, BorderLayout.CENTER); 
     add(titleLabel, BorderLayout.PAGE_START); 
     add(bottomButtonPanel, BorderLayout.PAGE_END); 

     // flesh out our jmenubar with a JMenu 
     JMenu fileMenu = new JMenu("File"); 
     fileMenu.setMnemonic(KeyEvent.VK_F); // alt-F to invoke it 

     // add a JMenuItem that uses the same disposeAction 
     fileMenu.add(new JMenuItem(disposeAction)); 
     menuBar.add(fileMenu); 
    } 

    // expose the JMenuBar to the world 
    public JMenuBar getMenuBar() { 
     return menuBar; 
    } 

    private class DisposeAction extends AbstractAction { 
     private static final long serialVersionUID = 1L; 
     public DisposeAction(String name, int mnemonic) { 
     super(name); // set button's text 
     putValue(MNEMONIC_KEY, mnemonic); // set it's mnemonic key 
     } 

     @Override 
     public void actionPerformed(ActionEvent e) { 
     // get the button that caused this action 
     Object source = e.getSource(); 
     if (source instanceof AbstractButton) { 
      AbstractButton exitButton = (AbstractButton) source; 

      // get the parent top level window 
      Window topWindow = SwingUtilities.getWindowAncestor(exitButton); 
      if (topWindow == null) { // if null, then likely in a JMenuItem 
       // so we have to get its jpopupmenu parent 
       Container parent = exitButton.getParent(); 
       if (parent instanceof JPopupMenu) { 
        JPopupMenu popupMenu = (JPopupMenu) parent; 

        // get the invoker for the pop up menu 
        Component invoker = popupMenu.getInvoker(); 
        if (invoker != null) { 
        // and get *its* top level window 
        topWindow = SwingUtilities.getWindowAncestor(invoker); 
        } 
       } 
      } 
      if (topWindow != null) { 
       // dispose of the top-level window 
       topWindow.dispose(); 
      } 
     } 
     } 
    } 

    private static void createAndShowGui() { 
     CartEg mainPanel = new CartEg(); 

     JFrame frame = new JFrame("Cart Example"); 
     frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
     frame.getContentPane().add(mainPanel); 
     frame.setJMenuBar(mainPanel.getMenuBar()); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
      createAndShowGui(); 
     } 
     }); 
    } 
} 
+0

Спасибо за то, что у вас есть время «перестроить» рамку, очень ценю ее. Кстати, как добавить к прослушивателю действие? –

+0

@NazhirinImran: вы также добавляете ActionListener на любую кнопку. Мой код был предназначен только для демонстрации, чтобы показать графический интерфейс.Если вы хотите функциональные JButtons, вам нужно будет иметь больше кода, чтобы это произошло. Обратите внимание, что я обычно пытаюсь установить действие JButton, а не добавлять ActionListener. Таким образом, я бы использовал внутренний класс, который расширяет AbstractAction и передает его в конструктор кнопки. –

+0

У меня есть еще одна проблема: у меня есть кнопка в JFrame (другой фрейм), который, когда пользователь щелкнет, откроет корзину, но кажется, что когда я нажимаю на нее, она ничего не делает. Кажется, что 'new CartEg()' не работает при использовании в кнопке внутри другого фрейма –

Смежные вопросы