Вопрос

Это домашнее задание.Начинаю урок Java.Все еще не могу прийти в себя от всего этого.

Проект заключается в создании Системы управления запасами.

Я во всем разобрался, за исключением того, как заставить эту кнопку изменять текст в JTextField.Ему необходимо добавить информацию из массива продукта (в данном случае DVD-дисков).В книге рассказывается о различных способах управления такими вещами, как шрифт, положение и состояние JTextField, но она не охватывает форматирование или вызов метода для текста.

Вот пример того, что я хочу сделать, используя JTextArea.По сути, это то, что я хочу сделать с моими JTextFields.

   ...
    // setup the interface    

 JPanel panel = new JPanel();
 txt = new JTextArea(15,40);
 txt.setEditable(false);//user shouldn't change it
 panel.add(txt);

 JButton next = new JButton("Next");

 panel.add(next);

 getContentPane().add(panel);

 displayDVD();
 }
 // view software
 public void displayDVD() {
       txt.setText("DVD Details:\n");
    txt.append("Item number: " + inv.get(currentDisplay).getItem() + "\n");
    txt.append("DVD name: " + inv.get(currentDisplay).getName() + "\n");
    txt.append("Units in stock: " + inv.get(currentDisplay).getUnits() + "\n");
    txt.append("Price: $" +                                              
       String.format("%.2f",inv.get(currentDisplay).getPrice()) + "\n");
    txt.append("Total value: $" +                             
       String.format("%.2f",inv.get(currentDisplay).value()) + "\n");
    txt.append("Fee: $" + String.format("%.2f",inv.get(currentDisplay).fee()) + "\n\n");

    txt.append("Total value: $" + String.format("%.2f",inv.value()));
 }

И вот мой фактический код на данный момент

// GUI with navigation and file manipulation buttons
import javax.swing.*; // provides basic window features
import java.awt.event.*;
import java.awt.GridLayout;
import java.awt.BorderLayout;

public class AppGUI extends JFrame 
{
   private Inventory inv;    
 private int currentDisplay = 0; 

   private JPanel topButtonJPanel;
 private JButton topButtons[]; 

 private JPanel labelJPanel;
 private JLabel labels[]; 

 private JPanel fieldJPanel;
 private JTextField fields[];

   private JPanel buttonJPanel;
 private JButton buttons[]; 

   // LabelFrame constructor adds JLabels to JFrame
   public AppGUI()
   {
      super( "Inventory Program v.5" );
      setLayout( new BorderLayout() ); // set frame layout
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// quit if the window is closed

  // initialize values
  RatedDVD d1 = new RatedDVD(1, "The Invisible Man", 0, 4999.99, "PG");
  RatedDVD d2 = new RatedDVD(2, "The Matrix", 1, 13.01, "PG13");
  RatedDVD d3 = new RatedDVD(3, "Se7en", 7, 11.11, "R");
  RatedDVD d4 = new RatedDVD(4, "Oceans Eleven", 11, 9.02, "PG13");
  RatedDVD d5 = new RatedDVD(5, "Hitch Hikers Guide to the Galaxy", 42, 10.00, "G"); 

  // create inv and enter values
  inv = new Inventory();
  inv.add(d1);
  inv.add(d2);
  inv.add(d3);
  inv.add(d4);
  inv.add(d5);

  inv.sort();

  topButtons = new JButton[ 6 ]; // create topButtons array
  topButtonJPanel = new JPanel(); // set up panel
  topButtonJPanel.setLayout( new GridLayout( 1, topButtons.length, 2, 2 ) );
  topButtons[0] = new JButton( "Load file" );
  topButtons[1] = new JButton( "Add" );
  topButtons[2] = new JButton( "Modify" );
  topButtons[3] = new JButton( "Delete" );
  topButtons[4] = new JButton( "Search" );
  topButtons[5] = new JButton( "Save" );

  for(int count=0;count<topButtons.length;count++){topButtonJPanel.add(topButtons[count]);}
  //add( topButtonJPanel, BorderLayout.NORTH ); // this is for next weeks assignment

  labels = new JLabel[8];
  labelJPanel = new JPanel();
  labelJPanel.setLayout( new GridLayout( labels.length, 1 ));
  labels[0] = new JLabel( "Item ID" );
  labels[1] = new JLabel( "Name" );
  labels[2] = new JLabel( "Rating" );
  labels[3] = new JLabel( "# in Stock" );
  labels[4] = new JLabel( "Price" );
  labels[5] = new JLabel( "Restocking Fee" );//[DEBUG] ref actual Variable
  labels[6] = new JLabel( "Inventory Value with Fee (5%)" );
  labels[7] = new JLabel( "Total Value with Fee(for all items)" );

  for(int count=0;count<labels.length;count++){labelJPanel.add(labels[count]);}
  add( labelJPanel, BorderLayout.WEST );

  fields = new JTextField[8];
  fieldJPanel = new JPanel();
  int spaces = 28;
  fieldJPanel.setLayout( new GridLayout( labels.length, 1 ));
  fields[0] = new JTextField( "", spaces );
  fields[1] = new JTextField( "", spaces );
  fields[2] = new JTextField( "", spaces );
  fields[3] = new JTextField( "", spaces );
  fields[4] = new JTextField( "", spaces );
  fields[5] = new JTextField( "", spaces );
  fields[6] = new JTextField( "", spaces );
  fields[7] = new JTextField( "", spaces );

  for(int count=0;count<fields.length;count++)
  {
   fields[count].setEditable( false );
   fieldJPanel.add(fields[count]);
  }
  add( fieldJPanel, BorderLayout.EAST );

  buttons = new JButton[ 5 ]; // create buttons array
  buttonJPanel = new JPanel(); // set up panel
  buttonJPanel.setLayout( new GridLayout( 1, buttons.length, 2, 2 ) );
  buttons[0] = new JButton( "First" ); 
  buttons[0].addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    if (currentDisplay != 0)currentDisplay = 0; //advance to the end
    }
   });
  buttons[1] = new JButton( "Prev" );
  buttons[1].addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    if (currentDisplay != 0)currentDisplay--; //advance to the end
     else currentDisplay = (inv.size()-1); 
    }
   });
  Icon bug1 = new ImageIcon( getClass().getResource( "bug1.gif" ) );
  buttons[2] = new JButton( bug1 );
  buttons[3] = new JButton( "Next" );
  buttons[3].addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    if (currentDisplay < inv.size()-1)currentDisplay++; //advance to the end
     else currentDisplay = 0;    stkover
   }}); 
  buttons[4] = new JButton( "Last" );
  buttons[4].addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
    if (currentDisplay != inv.size()-1)currentDisplay = inv.size()-1; //advance to the end
     else currentDisplay = (inv.size()-1); 
    }
   });

  for(int count=0;count<buttons.length;count++){buttonJPanel.add(buttons[count]);}
  add( buttonJPanel, BorderLayout.SOUTH );
 }// end method

}// end class AppGUI

Любые подсказки или подталкивания приветствуются.Но, пожалуйста, не делай все это за меня.

Это было полезно?

Решение

Вы добавляете прослушиватель действий к кнопке (чтобы он прослушивал действие кнопки (щелчок)).Затем запрограммируйте это действие на изменение значения текстового поля.

final JButton    aButton    = ...;
final JTextField aTextField = ...;
final String     aNewText   = "New TextField Value";

aButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        aTextField.setText(aNewText);
    }
});

Обратите внимание, что переменные, к которым обращаются с помощью 'actionPerformed', должны быть окончательными (за исключением полей).

Надеюсь, это поможет.

Другие советы

Для перекрестной ссылки типа "моя кнопка изменяет мое тестовое поле" идея состоит в том, чтобы дать кнопке (контроллеру, коду, который активируется при нажатии) ссылку на текстовое поле.Таким образом, когда кнопка нажата, она может изменить текстовое поле.

Возможно множество улучшений, но это основная идея.

Наверное, я не понимаю вопроса.

Вы знаете, как добавить несколько фрагментов текста в один компонент.

txt.append("Item number: " + inv.get(currentDisplay).getItem() + "\n"); 
txt.append("DVD name: " + inv.get(currentDisplay).getName() + "\n");

Так почему же так сложно добавить один фрагмент текста к нескольким компонентам?

itemTextField.setText( inv.get(currentDisplay).getItem() );
nameTextField.setText( inv.get(currentDisplay).getName() );
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top