在Java中与JButton交互

时间:2014-05-09 22:04:07

标签: java

我有一个项目,它有一个我应该用三个类制作的界面:Flight,Ticket和Seat。当用户点击座位时,该按钮将以蓝色突出显示,并且" Seat"文本字段填充了座位号。一旦用户点击"选择座位"按钮,该按钮以红色突出显示,并弹出消息询问用户是否要确认该过程。

PS:有100个座位,这意味着有100个按钮。行标记的数字最多为20,行标记为A,B,C,D和E.

我的问题是:

  1. 我尝试使用循环来增加按钮和标签的数量,但它没有用。单击按钮或单击其他按钮后,如何更改按钮的颜色?

  2. 如何链接"座位"带座位按钮的文本字段是否显示座位号?

  3. 编辑:更改我的代码并尝试使用不同的代码后,我仍然很难改变座位按钮的颜色。 这是我的代码。

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.* ; 
    import java.io.* ; 
    class project extends JFrame implements ActionListener
    { 
    Flight  flight = new Flight("Emirates", 817 ,  "RUH-DXB" , 1.45 , 18.3 ) ;
    Seat  tempSeat , seat  ; 
    JButton tempButton ;  
    int ticketNO = 1  ;
    String TicketNo ;  // to keep like "TK00001" 
    boolean issu = false ; 
    String resultTicket = "" ; 
    
    private JLabel label1 ; 
    private JLabel label2 ; 
    private JLabel label3 ; 
    private JLabel label4 ; 
    private JLabel label5 ; 
    private JLabel label6 ; 
    private JLabel label7 ; 
    private JLabel label8 ; 
    private JLabel label9 ; 
    
    private JButton chooseButton;
    private JButton IssueButton;
    
    private JTextField inputLine1;
    private JTextField inputLine2;
    private JTextField inputLine3;
    private JTextField inputLine4;
    private JTextField inputLine5;
    private JTextField inputLine6;
    private JTextField inputLine7;
    private JTextField inputLine8;
    
    
    private JTextArea  textArea ; 
    
    // 2D array 
    
    JButton[][]  LButton = new JButton[20][5];
    
    // inner class to invoke the close window event
    class EventHandler extends WindowAdapter 
     {
    
        public void windowClosing(WindowEvent evt) {
    
         int answer = JOptionPane.showConfirmDialog(null , "Are you sure that you want to Exit ?"
            ,"Exit", JOptionPane.YES_NO_OPTION);
    
         if( answer == JOptionPane.YES_OPTION)
         {
    
            Date date = new Date() ; 
            try 
            {
               File outFile = new File("Log.txt") ; 
               FileOutputStream sf = new FileOutputStream(outFile) ; 
               PrintWriter pf = new PrintWriter(sf) ;
    
    
               pf.println("=================" ) ; 
               pf.println("Today's Log - + " +  date.toString()+"\n" );
               pf.println("Issued Tickets: ");
    
               for(int i = 0 ; i< resultTicket.length() ; i++)
               {
                  if( resultTicket.charAt(i) != '\n' )
                     pf.print(resultTicket.charAt(i));    // same text in textArea
                  else
                     pf.println();
               }
    
    
               pf.println("The airlines of the flight: " + flight.getairLines() );
               pf.println("Flight number: " + flight.getflightNo());
               pf.println("Route: "+ flight.getroute() );
               pf.println("Departure Time: " + flight.getDepartureTime());
               pf.println("Dutation: " + flight.getduration());
    
               for(int r = 0 ; r < 20 ; r++)
               {
                  for(int c = 0 ; c < 5 ; c++)
                  {
                     pf.print( flight.list[r][c].getSeatNo() + " : " );
                     pf.println( flight.list[r][c].isAvailable() ? "Available" : "Unavailable");
                  }
               }
               JOptionPane.showMessageDialog(null , "The information is/are saved");
               pf.close() ; 
               System.exit(0) ; 
    
            } // end try
            catch(IOException e  )
            {
               JOptionPane.showMessageDialog(null , "Error, file couldn't be opened");
               System.exit(0) ; 
    
            }
    
         } // end if answer
      }
      }// end inner class 
       //---------------------------------------
    
    
      public static void main(String[] args) 
      {
      project frame = new project();
      frame.setVisible(true);    
    
      }
    
      public project() { 
    
      addWindowListener(new EventHandler());   
    
    
      Container contentPane = getContentPane( );
      setSize      (900, 700);
      setResizable (false);
      setTitle     ("Seat Selector ");
      setLocation  (200, 10);
      contentPane.setLayout(null);
    
      label1 = new JLabel("AirLines:" ) ; 
      label1. setBounds(10 , 30 , 100 , 30 ) ; 
      contentPane.add(label1 );
    
      inputLine1 = new JTextField(flight.getairLines());
      inputLine1.setColumns(10);
      inputLine1. setBounds(80 , 30 , 150 , 30 ) ; 
      inputLine1.setEnabled(false);
      contentPane.add(inputLine1 );
    
    
      label2 = new JLabel("FlightNumber:" ) ; 
      label2. setBounds(250 , 30 , 100 , 30 ) ; 
      contentPane.add(label2 );
    
      inputLine2 = new JTextField("" + flight.getflightNo());
      inputLine2.setColumns(10);
      inputLine2. setBounds(340 , 30 , 150 , 30 ) ; 
      inputLine2.setEnabled(false);
      contentPane.add(inputLine2 );
    
       //=================================
    
      label3 = new JLabel("Rout:" ) ; 
      label3. setBounds(10 , 60 , 100 , 30 ) ; 
      contentPane.add(label3 );
    
      inputLine3 = new JTextField(flight.getroute());
      inputLine3.setColumns(10);
      inputLine3. setBounds(80 , 60 , 150 , 30 ) ;
      inputLine3.setEnabled(false);
      contentPane.add(inputLine3 );
    
    
      label4 = new JLabel("Duration:" ) ; 
      label4. setBounds(250 , 60 , 100 , 30 ) ; 
      contentPane.add(label4 );
    
      inputLine4 = new JTextField(""+flight.getduration());
      inputLine4.setColumns(10);
      inputLine4. setBounds(340 , 60 , 150 , 30 ) ; 
      inputLine4.setEnabled(false);
      contentPane.add(inputLine4 );
       //=======================================
    
      label5 = new JLabel("TicketNubmer:" ) ; 
      label5. setBounds(10 , 120 , 100 , 30 ) ; 
      contentPane.add(label5 );
    
      inputLine5 = new JTextField("TK0000" + ticketNO);
      inputLine5.setColumns(10);
      inputLine5. setBounds(10 , 150 , 150 , 30 ) ; 
      inputLine1.setEnabled(false);
      contentPane.add(inputLine5 );
    
    
      label6 = new JLabel("Departure Time:" ) ; 
      label6. setBounds(250 , 90 , 100 , 30 ) ; 
      contentPane.add(label6 );
    
      inputLine6 = new JTextField("" + flight.getDepartureTime());
      inputLine6.setColumns(10);
      inputLine6. setBounds(340 , 90 , 150 , 30 ) ; 
      inputLine6.setEnabled(false);
      contentPane.add(inputLine6 );
      //=======================================
      label7 = new JLabel("Pasenger:" ) ; 
      label7. setBounds(10 , 190 , 100 , 30 ) ; 
      contentPane.add(label7 );
    
      inputLine7 = new JTextField("Passenger Name");
      inputLine7.setColumns(10);
      inputLine7. setBounds(80 , 190 , 150 , 30 ) ; 
      contentPane.add(inputLine7 ); 
    
      chooseButton= new JButton("Choose Seat");
      chooseButton. setBounds(250 , 190 , 150 , 30 ) ; 
      contentPane.add(chooseButton) ;
      chooseButton.addActionListener(this);
      //====================================
    
      label8 = new JLabel("Seat:" ) ; 
      label8. setBounds(10 , 230 , 100 , 30 ) ; 
      contentPane.add(label8 );
      inputLine8 = new JTextField();
      inputLine8.setColumns(10);
      inputLine8. setBounds(80 , 230 , 70 , 30 ) ; 
      inputLine8.setEnabled(false);
      contentPane.add(inputLine8 ); 
    
      IssueButton= new JButton("Issue Ticket");
      IssueButton. setBounds(250 , 230 , 150 , 30 ) ; 
      contentPane.add(IssueButton) ;
      IssueButton.addActionListener(this);
    
    
      label9 = new JLabel("Today's Log:" ) ; 
      label9. setBounds(30 , 370 , 150 , 30 ) ; 
      contentPane.add(label9 );
    
      textArea = new JTextArea();
      textArea.setColumns(15);
      textArea.setRows(8);
      textArea.setBorder(BorderFactory.createLineBorder(Color.red));
      textArea.setEditable(false);
      textArea. setBounds(30 , 400 , 400 , 200 ) ; 
      contentPane.add(textArea); 
    
      //==========================
      JLabel  chr[] = new JLabel[5];
      char ch = 'A' ;
      int x = 600 ; 
      int  y = 20 ;  
      for(int i = 0 ; i < 5 ; i++)
      {
         chr[i] = new JLabel(""+ch++) ; 
         chr[i].setBounds(x , y , 20 , 20 ) ; 
         contentPane.add(chr[i] );
         x += 20 ; 
      }
      //=============================
      JLabel  No[] = new JLabel[20];
      x = 580 ; 
      y = 40 ;  
      for(int i = 0 ; i < 20 ; i++)
      {
         No[i] = new JLabel(""+(i+1)) ; 
         No[i].setBounds(x , y , 20 , 20 ) ; 
         contentPane.add(No[i] );
         y += 20 ; 
      }
    
    
       //========================
      x = 600 ; 
      y = 20 ;
      for(int i = 0 ; i < 20 ; i++)
      {
         y = y + 20 ; 
         x = 600 ; 
         for(int j = 0 ; j<5; j++)
         {
    
            LButton[i][j] = new JButton();
            LButton[i][j]. setBounds(x , y , 20 , 20 ) ; 
            contentPane.add( LButton[i][j]) ;
            LButton[i][j].setBackground(Color.GREEN) ; 
            LButton[i][j].addActionListener(this);
            x = x+20 ; 
    
         }
      }
      disAbleSeat() ;   // call method to make all seat color unEnable 
    
      setDefaultCloseOperation( EXIT_ON_CLOSE );
    
    
       //////////***************************************
       // load file
       /*
       Seat list[]= null ;  
      try
       {
      File f = new File("reservedSeat.dat") ; 
      FileInputStream r = new FileInputStream(f) ; 
      ObjectInputStream  file = new ObjectInputStream (r) ; 
    
      list = (Seat[]) file.readObject() ; 
      file.close() ; 
      }
     catch(ClassNotFoundException  e)
     {
     System.out.println("Error, class not found");
     System.exit(0) ; 
     }
     catch(IOException  e)
     {
     System.out.println("Error, file couldn't be opened ");
     System.exit(0) ; 
     }
    
    
     for(int k = 0 ; k < list.length ; k++)
     {
     for(int i = 0 ; i < 20 ; i++)
    for(int j = 0 ; j< 5 ; j++)
    {
    Seat s = flight.getSeat(i,j) ;
    if( list[i].getSeatNo().equals( s.getSeatNo()))
    {
    s.setAvailable(false);
    LButton[i][j].setBackground(Color.RED)  ;   
    }
    
       }
       }
       /////////////////////////////////////////*****
       */
    
      }// end constructor
    
      public void actionPerformed(ActionEvent event) {
    
      JButton press = (JButton) event.getSource() ; 
      String str = press.getText() ; 
    
      if(str.equals("Choose Seat") ) 
      {
         chooseButton.setText("Confirm");
         enableSeat() ; 
         TicketNo = "TK" + ( ticketNO < 9 ? "0000" : "000") + ticketNO ; 
         inputLine5.setText(TicketNo) ; 
         return ;  
      }
      else
         if(str.equals("Confirm"))
         {
            if( tempSeat == null && tempButton == null  ) 
            {
               JOptionPane.showMessageDialog(this , "first select seat.");
               return ; 
            }
            else
               if( issu == true )
               {
                  JOptionPane.showMessageDialog(this , "you are already confirm issue seat");
                  return ; 
               }
               else
               {
                  tempSeat.setAvailable(false) ; 
                  tempButton.setBackground(Color.RED);
                  issu = true ; 
                  disAbleSeat() ; 
                  return ;  
               }
    
         } // end confirm 
      if(str.equals("Issue Ticket"))
      {
         if( issu == false )
         {
            JOptionPane.showMessageDialog(this , "you can not creat a Ticket without        confirming a seat ");
            return ; 
         }
         else
         {
            int answer = JOptionPane.showConfirmDialog(null , "are you sure you want to issue the thicket?"
               ,"confirming", JOptionPane.YES_NO_OPTION);
    
            if( answer == JOptionPane.YES_OPTION)
            {
    
               Ticket tick = new Ticket(inputLine7.getText() , 
                             TicketNo , flight , tempSeat   ) ; 
    
               ticketNO++ ; 
               tick.issueTicket() ; 
               chooseButton.setText("Choose Seat");
               resultTicket += tick.getticketNo() +"-"+ tick.getpassenger()+"-"+tempSeat.getSeatNo() +"\n" ; 
               textArea.append (tick.getticketNo() +"-"+ tick.getpassenger()+"-"+tempSeat.getSeatNo() +"\n" ); 
               tempSeat = null ;
               tempButton = null ;   
            }// press yes 
            else
               if( answer == JOptionPane.NO_OPTION)     // cancel seat and return seat to grean color
               {
                  chooseButton.setText("Choose Seat");
                  tempButton.setBackground(Color.GREEN);
                  tempSeat.setAvailable(true) ; 
    
                  disAbleSeat() ; 
    
                  tempSeat = null ;
                  tempButton = null ;
               }// press no 
         } // end if issu 
         issu = false ; 
    
      }// end button issue
      //====================================================
      else    // if press seat buttons
      {
         if( tempSeat != null && tempButton != null  ) 
         {
            tempButton.setBackground(Color.GREEN);
            tempSeat = null ; 
            tempButton = null ; 
         }
    
         for(int i = 0 ; i < 20 ; i++)
         {
            for(int j = 0 ; j<5; j++)
            {
               if(press == LButton[i][j] )
               {
                  seat = flight.getSeat(i,j) ; 
    
                  if(seat.isAvailable() == false ) 
                     return ; 
    
                  tempSeat = seat ; 
                  tempButton = press ; 
                  press.setBackground(Color.BLUE);
                  inputLine8.setText(seat.getSeatNo());
                  return ;           
               }
    
            } // end for j 
         }// end for i 
      }//  end press  seat buttons 
    
    
    
       }// end Action
    
      public void enableSeat() // all avalable 
       {
         for(int i = 0 ; i < 20 ; i++)
         for(int j = 0 ; j<5; j++)
            LButton[i][j].setEnabled(true) ; 
       }
    
       public void disAbleSeat() // 
       {
      for(int i = 0 ; i < 20 ; i++)
         for(int j = 0 ; j<5; j++)
            LButton[i][j].setEnabled(false) ; 
       }
    
     }// end class 
    

3 个答案:

答案 0 :(得分:0)

您可以使用MouseListener处理JButtons上的点击事件。然后,在侦听器内部,使用this访问该按钮,并更改其值。从中,您可以访问其他对象,假设您在类中开发了这些关系。

另一种方法是使用单例模式加载所有组件,然后在需要时在监听器中调用它们。因此,必须可以从事件处理程序方法访问它们。

嗯,对于你的问题的其余部分,这是一般的应用程序设计,所以回答非常复杂,因为不同的人可能会做不同的事情(一些好的设计,一些差的设计,取决于上下文中)

答案 1 :(得分:0)

也许这会帮助你作为一个起点

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class ListButtonPanel extends JPanel implements ActionListener {

    private List<JButton> buttons = new ArrayList<>();

    public ListButtonPanel() {

        this.setPreferredSize(new Dimension(1024, 768));
        for(int i = 1; i <= 100; i++) {
            buttons.add(new JButton("Seat-" + i));
        }

        this.setLayout(new GridLayout(10, 10));
        for(JButton button : buttons) {
            button.addActionListener(this);
            this.add(button);
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton sourceBtn = (JButton) e.getSource();

        int showConfirmDialog = JOptionPane.showConfirmDialog(getParent(), "You want to reserve seat " + sourceBtn.getText() + "", "Reserve Seat", JOptionPane.YES_NO_CANCEL_OPTION);

        if(showConfirmDialog == 0) {
            sourceBtn.setBorder(BorderFactory.createLineBorder(Color.RED, 3, true));
            sourceBtn.setEnabled(false);
            sourceBtn.setForeground(Color.red);
        }
    }
}

答案 2 :(得分:0)

这里有两个java类,展示了你需要的基本概念:

第一个展示了如何在for循环中创建按钮并为click事件添加ActionListener。

import java.awt.GridLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Frame extends JFrame {

    public Frame() {
        setSize(600, 400);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        getContentPane().setLayout(new GridLayout(2,2));

        JTextField field = new JTextField();

        // batch create buttons
        JButton btn;
        for (int i = 0; i < 10; i++) {
            String name = new Integer(i+1).toString();
            btn = new JButton(name);

            // add an action command to identify the buttons
            btn.setActionCommand(name);

            // add an instance of Action to handle the click event
            btn.addActionListener(new Action(field));

            // add button to the frame
            add(btn);
        }

        // add the field to the frame
        add(field);

        pack();

        setVisible(true);
    }

}

第二个实现ActionEvent并显示如何操作文本字段并为单击的按钮着色。

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JTextField;

public class Action implements ActionListener {

    public JTextField field;

    public Action(JTextField theField) {
        field = theField;
    }

    public void actionPerformed(ActionEvent e) {
        // set the textfield's text
        field.setText(e.getActionCommand());

        // set clicked button color
        JButton theButton = (JButton)e.getSource();
        theButton.setBackground(new Color(255, 0, 0));
    }

}