1

Please can someone help me, I'm trying to make a seat reservation part for my cinema ticket system assignment ... so the problem is i want the text of the button to show in the text area when selected and not show only the specific text when deselected .. but when i deselect a button the whole text area is cleared.

For e.g. when I select C1, C2, C3 - it shows in the text area correctly, but if I want to deselect C3, the text area must now show only C1 & C2. Instead, it clears the whole text area!

Can anyone spot the problem in the logic?

  import java.awt.*;
  import static java.awt.Color.blue;
  import javax.swing.*;
  import java.awt.event.*;
  import javax.swing.border.Border;


  public class Cw_Test2  extends JFrame {

JButton btn_payment,btn_reset;
JButton buttons;
JTextField t1,t2; 



public static void main(String[] args) {
    // TODO code application logic here
   new  Cw_Test2();
}

public Cw_Test2()
{
    Frame(); 

}

  public void Frame()
{
    this.setSize(1200,700);     //width, height
    this.setTitle("Seat Booking");
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLocationRelativeTo(null);

    Font myFont = new Font("Serif", Font.ITALIC | Font.BOLD, 6);
    Font newFont = myFont.deriveFont(20F);

    t1=new JTextField();  
    t1.setBounds(15, 240, 240,30); 

    JPanel thePanel = new JPanel()
     {
        @Override
         public Dimension getPreferredSize() {
         return new Dimension(350, 350);
        };
    };    
    thePanel.setLayout(null);

    JPanel ourPanel = new JPanel()        
    {
        @Override
         public Dimension getPreferredSize() {
         return new Dimension(350, 350);
        };
    };
    //ourPanel.setBackground(Color.green);
    Border ourBorder = BorderFactory.createLineBorder(blue , 2);
    ourPanel.setBorder(ourBorder);
    ourPanel.setLayout(null);
    ourPanel.setBounds(50,90, 1100,420); 

    JPanel newPanel = new JPanel()        
    {
        @Override
         public Dimension getPreferredSize() {
         return new Dimension(350, 350);
        };
    };
    //ourPanel.setBackground(Color.green);
    Border newBorder = BorderFactory.createLineBorder(blue , 1);
    newPanel.setBorder(newBorder);
    newPanel.setLayout(null);
    newPanel.setBounds(790,50, 270,340); 

    JLabel label1 = new JLabel( new ColorIcon(Color.GRAY, 400, 100) );
    label1.setText( "SCREEN" );
    label1.setHorizontalTextPosition(JLabel.CENTER);
    label1.setVerticalTextPosition(JLabel.CENTER);
    label1.setBounds(130,50, 400,30);

    JLabel label2 = new JLabel(" CINEMA TICKET MACHINE ");
    label2.setBounds(250,50,400,30);
    label2.setFont(newFont);
    JLabel label3 = new JLabel("Please Select Your Seat");
    label3.setBounds(270,10,500,30);
    label3.setFont(newFont);
    JLabel label4 = new JLabel("Selected Seats:");
    label4.setBounds(20,10,200,30);
    label4.setFont(newFont);


    btn_payment=new JButton("PROCEED TO PAY");  
    btn_payment.setBounds(35,290,200,30);

    JLabel label6 = new JLabel("Center Stall");
   label6.setBounds(285,172,200,30);

     JPanel seatPane, seatPane1, seatPane2, seatPane3, seatPane4, seatPane5;
      JToggleButton[] seat2 = new JToggleButton[8];

    JTextArea chosen = new JTextArea();
 chosen.setEditable(false);
 chosen.setLineWrap(true);
 chosen.setBounds(20, 60, 200, 100); 

  // Center Seats
 seatPane1 = new JPanel();
 seatPane1.setBounds(200,200,250,65);
 seatPane1.setLayout(new FlowLayout());

 for(int x=0; x<8; x++){


     seat2[x] = new JToggleButton("C"+(x+1));


     seatPane1.add(seat2[x]);


    seat2[x].addActionListener(new ActionListener(){

        public void actionPerformed(ActionEvent ev){

            AbstractButton abstractButton = (AbstractButton) ev.getSource();
            boolean selected = abstractButton.getModel().isSelected();

            for(int x=0; x<8; x++){


            if(seat2[x]==ev.getSource()){
                if(selected){


                    chosen.append(seat2[x].getText()+",");


                }else{
                    chosen.setText(seat2[x].getText().replace(seat2[x].getText(),""));





                }



            }

            }

        }

    }); 
 }

 newPanel.add(chosen);
 ourPanel.add(seatPane1);
 ourPanel.add(label6);
 thePanel.add(label2);
    ourPanel.add(label3);
    ourPanel.add(label1);
    newPanel.add(btn_payment);
    newPanel.add(label4);

    ourPanel.add(newPanel);
    thePanel.add(ourPanel);
    add(thePanel);
    setResizable(false);
    this.setVisible(true);

}


  public static class ColorIcon implements Icon
{
    private Color color;
    private int width;
    private int height;

    public ColorIcon(Color color, int width, int height)
    {
        this.color = color;
        this.width = width;
        this.height = height;
    }

    public int getIconWidth()
    {
        return width;
    }

    public int getIconHeight()
    {
        return height;
    }

    public void paintIcon(Component c, Graphics g, int x, int y)
    {
        g.setColor(color);
        g.fillRect(x, y, width, height);
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Rvn
  • 63
  • 10
  • Do you understand what `setText` does? Perhaps you should consider using a `JList` instead, it'd be easier to update – MadProgrammer Feb 26 '17 at 06:57
  • 1
    1) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). This problem really only requires 2-3 toggle buttons and one text area to describe! 2) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Feb 26 '17 at 08:09
  • @MadProgrammer .. Okay buddy will try that out – Rvn Feb 26 '17 at 08:49
  • @MadProgrammer *"Perhaps you should consider using a `JList` instead.."* A `JList` is not an optimal user experience for selecting cinema seats that have a particular organisation & layout. E.G. is seat 42 adjacent to an aisle? If so, is the aisle to the right or left? I'd use an array of seats and layouts to show the ..layout. – Andrew Thompson Feb 26 '17 at 08:56
  • 1
    @AndrewThompson I was thinking instead of JTextArea, that way you don't need to deal with sub string issues ;) – MadProgrammer Feb 26 '17 at 08:57
  • @MadProgrammer Well, ..that actually makes a **lot** of sense. :P – Andrew Thompson Feb 26 '17 at 08:58

1 Answers1

3

When any seat is selected or deselected, this code iterates an array of seats (in the method showSelectedSeats()) and updates the text area to show the seats that are selected.

enter image description here

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class CinemaTicketMachine {

    private JComponent ui = null;
    private JToggleButton[] seats = new JToggleButton[80];
    private JTextArea selectedSeats = new JTextArea(3, 40);

    CinemaTicketMachine() {
        initUI();
    }

    public void initUI() {
        if (ui!=null) return;

        ui = new JPanel(new BorderLayout(4,4));
        ui.setBorder(new EmptyBorder(4,4,4,4));

        selectedSeats.setLineWrap(true);
        selectedSeats.setWrapStyleWord(true);
        selectedSeats.setEditable(false);
        ui.add(new JScrollPane(selectedSeats), BorderLayout.PAGE_END);

        JPanel cinemaFloor = new JPanel(new BorderLayout(40, 0));
        cinemaFloor.setBorder(new TitledBorder("Available Seats"));
        ui.add(cinemaFloor, BorderLayout.CENTER);
        JPanel leftStall = new JPanel(new GridLayout(0, 2, 2, 2));
        JPanel centerStall = new JPanel(new GridLayout(0, 4, 2, 2));
        JPanel rightStall = new JPanel(new GridLayout(0, 2, 2, 2));

        cinemaFloor.add(leftStall, BorderLayout.WEST);
        cinemaFloor.add(centerStall, BorderLayout.CENTER);
        cinemaFloor.add(rightStall, BorderLayout.EAST);

        ActionListener seatSelectionListener = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                showSelectedSeats();
            }
        };

        for (int ii=0; ii <seats.length; ii++) {
            JToggleButton tb = new JToggleButton("S-" + (ii+1));
            tb.addActionListener(seatSelectionListener);
            seats[ii] = tb;
            int colIndex = ii%8;
            if (colIndex<2) {
                leftStall.add(tb);
            } else if (colIndex<6) {
                centerStall.add(tb);
            } else {
                rightStall.add(tb);
            }
        }
    }

    private void showSelectedSeats() {
        StringBuilder sb = new StringBuilder();
        for (int ii=0; ii<seats.length; ii++) {
            JToggleButton tb = seats[ii];
            if (tb.isSelected()) {
                sb.append(tb.getText());
                sb.append(", ");
            }
        }
        String s = sb.toString();
        if (s.length()>0) {
            s = s.substring(0, s.length()-2);
        }
        selectedSeats.setText(s);
    }

    public JComponent getUI() {
        return ui;
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                CinemaTicketMachine o = new CinemaTicketMachine();

                JFrame f = new JFrame(o.getClass().getSimpleName());
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                f.setLocationByPlatform(true);

                f.setContentPane(o.getUI());
                f.pack();
                f.setMinimumSize(f.getSize());

                f.setVisible(true);
            }
        };
        SwingUtilities.invokeLater(r);
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1
    Omg buddy, thank you sooo much i have been scratching my head thinking about how to do this ..literally spend alot of sleepless night doing this assignment (this is just one part of it ) .. and u have given me the perfect solution i needed .. its works perfectly just like how i wanted it to .. Finally i understand the concept ! – Rvn Feb 26 '17 at 09:02
  • 1
    I'd also consider having a look at [`StringJoiner`](https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html) ;) – MadProgrammer Feb 26 '17 at 10:25
  • *"buddy"* I'm not your buddy. I might be on FaceBook, but this is not a social networking site. *"..this is not i have a doubt with this.."* I presume by 'doubt' you mean 'question'. Save your doubts for the statements of politicians and used car salesmen. As to your further question, start a new question thread. – Andrew Thompson Feb 27 '17 at 09:29
  • @AndrewThompson ..Hmm Okay Sorry im new here .. Chill .. Will post a new question ... hope you can help me :) ! – Rvn Feb 27 '17 at 11:09