简体   繁体   English

JButton需要更改JTextfield文本

[英]JButton needs to change JTextfield text

This is homework. 这是功课。 Beginning Java class. 入门Java类。 Still wrapping my head around this stuff. 仍然把我的头缠在这东西上。

The project is to make an Inventory Management System. 该项目是要建立一个库存管理系统。

I have everything figured out except how to make this button change the text in a JTextField. 除了如何使此按钮更改JTextField中的文本外,我已经弄清楚了一切。 It needs to add info from an array of a product (DVD's in this case). 它需要从产品阵列(在本例中为DVD)中添加信息。 The book talks about different ways to manage things like font, position and state of a JTextField but it does not cover formatting or calling a method for the text. 这本书讨论了管理诸如JTextField的字体,位置和状态之类的不同方法,但是没有涉及格式化或调用文本的方法。

Here is an example of what I want to do using a JTextArea. 这是我要使用JTextArea进行操作的示例。 This is essentially what I want to do with my JTextFields. 从本质上讲,这就是我想对JTextField进行的操作。

   ...
    // 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()));
 }

And here is my actual code so far 这是到目前为止我的实际代码

// 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

Any hints tips or nudges appreciated. 任何提示提示或微调表示赞赏。 Don't do it all for me though please. 不过请不要为我全部。

You add an action listener to the button (so that it will listen to the button action (click)). 您向按钮添加了一个动作侦听器(以便它可以侦听按钮动作(单击))。 Then program that action to change the TextField value. 然后对该动作进行编程以更改TextField值。

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

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

Observe that variables accessed with in 'actionPerformed' must be final (except the fields). 请注意,使用'actionPerformed'访问的变量必须是最终变量(字段除外)。

Hope this helps. 希望这可以帮助。

For a cross-reference like "my button changes my testbox", the idea is to give to the button (the controller, the code that will get activated when clicked) a reference to the textbox. 对于像“我的按钮更改我的测试框”这样的交叉引用,其想法是为按钮(控制器,单击时将被激活的代码)提供对文本框的引用。 So when the button is pressed, it can change the textbox. 因此,当按下按钮时,它可以更改文本框。

They are many improvements possible, but that's the basic idea. 他们有许多可能的改进,但这是基本思想。

I guess I don't understand the question. 我想我不明白这个问题。

You know how to add multiple pieces of text to a single component. 您知道如何将多个文本片段添加到单个组件中。

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

So why it is so hard to add a single piece of text to multiple components? 那么,为什么很难将单个文本添加到多个组件中呢?

itemTextField.setText( inv.get(currentDisplay).getItem() );
nameTextField.setText( inv.get(currentDisplay).getName() );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM