微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

不能使我的JButtons响应除该面板外,所有内容都会调整大小

如何解决不能使我的JButtons响应除该面板外,所有内容都会调整大小

我已经想了好几天,试图使UI响应,但是我正在学习,并且自己找不到方法

这是我想做的事,就像img一样,但是反应灵敏(总是在该JScrollPanel中显示相同数量的按钮)。我使用实际的screenSize设置开始大小,并且开始最大,因此它以12个按钮列开始。

https://i.ibb.co/9hTwsh1/image.png

但是,当我调整它的大小时,我的按钮没有,所以当我程序的其余部分调整大小时,我的按钮面板保持相同的大小:

https://i.ibb.co/NFHvfLr/image.png

(不能扩展imgs,也许有人可以为我编辑它吗?谢谢!)

我遇到的主要问题是我不知道我需要多少个按钮,所以我尝试进行动态响应式布局,但不知道如何使用我的按钮。

EDIT-1:

自昨天以来,由于您的评论(非常感谢),我进行了一些更改。

  1. 您告诉我使用GridLayout而不是GridBagLayout。我改用gridBag尝试实现响应式UI,但没有用。如您所说,我回滚到GridLayout……至少更干净。

  2. 正如您告诉我的那样,我也做了一个可复制的示例。关于这些注释,请删除它们。正如您所评论的,只是噪音(那些仅对我而言,想法)。抱歉,应该在我第一次发布之前删除它们。

  3. 关于对comboBox的更改,我试图模拟POS程序,所以我需要那些大按钮:-D

  4. 关于第四条评论。.我搜索您对updateUI的看法...问题是我使用它,因为当我执行mainPanel.removeAll()时,除非我执行“ updateUI”,否则它将不起作用那(您可以看到我在程序中使用了4次)。 removeAll之后如何更新面板? -只是寻找解决方案。也许使用revalidate是执行此操作的正确方法

您也告诉我不要使用setPreferredSize ..但我需要我的按钮始终保持相同(如果最大化,则调整大小)。不管我画10还是100。如果没有preferredSize,该怎么办? 关于静电..事实是,当我不知道如何使用静电时,我会使用静电。但是,正如您所说,我想尝试改变这一点。

代码(尝试做得更短,但是您可以看到,我还不擅长=)):

    public class StackOverflow {
    public static void main(String[] args) {
        Producto.crearProductosInicio();
        Categoria.crearCategorias();
        EventQueue.invokelater(new Runnable() {
            public void run() {

                try {
                    PantallaGeneral fondo = new PantallaGeneral();
                } catch (Exception e) {
                    e.printstacktrace();
                }
            }
        });
    }
}

class ProductPane extends JScrollPane  {
    static JPanel contenedorPanelProductos = new JPanel();
    static JPanel panelProductos;
    public ProductPane () {
        super(
                contenedorPanelProductos,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED
        );
        this.setLayout(new ScrollPaneLayout());
        panelProductos=new JPanel();
    }
    public static void dibujarProductos ( int categoria) {
        ArrayList<Categoria> categorias = Categoria.listaCategorias().stream().filter(x->x.getIDpadre()==categoria).collect(Collectors.toCollection(ArrayList::new));
        ArrayList<Producto> productos = Producto.listaProductos().stream().filter(x->x.getID_Categoria()==categoria).collect(Collectors.toCollection(ArrayList::new));

        panelProductos.removeAll();
        panelProductos.updateUI();

        JButton botones;

        panelProductos.setLayout(new GridLayout(0,12));

        panelProductos.setBackground(Color.yellow);
        int x=0,y=0;
        for (int i = 0; i<categorias.size();i++) {
            botones=categorias.get(i).getBoton();
            panelProductos.add(botones);
        }
        for (int i = 0; i<productos.size();i++) {
            botones=productos.get(i).getBoton();
            panelProductos.add(botones);
        }
        if (categoria>1) {
            botones = crearCategoriaGeneral();
            panelProductos.add(botones);
        }
        agregarPanel(panelProductos);
    }
    public static JButton crearCategoriaGeneral () {
        JButton botonGeneral = new JButton("General");
        botonGeneral.setMargin(new Insets(0,0));
        Font fuente = new Font("Arial",1,10);
        botonGeneral.setFont(fuente);
        botonGeneral.setBackground(Color.white);
        botonGeneral.setPreferredSize(new Dimension((((java.awt.Toolkit.getDefaultToolkit().getScreenSize().width/2)-40)/12),(((Toolkit.getDefaultToolkit().getScreenSize().width/2)-40)/12)));
        botonGeneral.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dibujarProductos(1);
            }
        });
        return botonGeneral;
    }
    public static void agregarPanel (JPanel panelProductos) {
        contenedorPanelProductos.setBackground(Color.BLUE);
        contenedorPanelProductos.setBorder(BorderFactory.createEmptyBorder(10,20,10,20));
        contenedorPanelProductos.setLayout(new GridBagLayout());
        GridBagConstraints v = new GridBagConstraints();
        v.weightx = 1;
        v.weighty = 1;
        v.anchor=GridBagConstraints.FirsT_LINE_START;
        contenedorPanelProductos.add(panelProductos,v);
    }
}

class Producto {
    int id;
    String nombre;
    String rutaimagen;
    double precio;
    int ID_Categoria;
    int ID_Impuesto;
    JButton boton;
    //Consulta a BD para creación de productos:
    static ArrayList<Producto> productos = new ArrayList<>();


    public Producto(int id,String nombre,String rutaimagen,double precio,int ID_Categoria,int ID_Impuesto) {
        this.id = id;
        this.nombre = nombre;
        this.rutaimagen = rutaimagen;
        this.precio = precio;
        this.ID_Categoria = ID_Categoria;
        this.ID_Impuesto = ID_Impuesto;
        establecerBoton();
    }
    private void establecerBoton() {
        boton = new JButton(this.nombre);
        boton.setMargin(new Insets(0,0));
        boton.setBackground(Color.DARK_GRAY);
        Font fuente = new Font("Arial",10);
        boton.setFont(fuente);
        Dimension tamBot = new Dimension((((java.awt.Toolkit.getDefaultToolkit().getScreenSize().width / 2) - 40) / 12),(((Toolkit.getDefaultToolkit().getScreenSize().width / 2) - 40) / 12));
        boton.setPreferredSize(tamBot);
        Producto temp = this;
        boton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                TicketPane.añadirProductoTicket(temp);
            }
        });
    }

    public JButton getBoton() {
        return boton;
    }
    public static ArrayList<Producto> listaProductos () {
        return productos;
    }
    public static void crearProductosInicio() {
            for (int i=0;i<15;i++) {
                productos.add(new Producto(i,"Aquarius"," ",0.30*i,4,1));

            }
            for (int i=15;i<75;i++) {
                productos.add(new Producto(i,"7up",0.15*i,2,1));
            }
    }
    public int getID_Categoria() {
        return ID_Categoria;
    }
    public String getNombre() {
        return nombre;
    }
    public double getPrecio() {
        return precio;
    }
}

class Categoria {
    static ArrayList<Categoria> categorias = new ArrayList<>();
    int ID;
    String nombre;
    int IDpadre;
    JButton boton;

    public Categoria(int ID,int IDpadre) {
        this.ID = ID;
        this.nombre = nombre;
        this.IDpadre = IDpadre;
        establecerBoton();
    }

    public static void crearCategorias() {
        categorias.add(new Categoria(1,"General",0));
        categorias.add(new Categoria(2,"Bebidas",1));
        categorias.add(new Categoria(3,"Comida",1));
        categorias.add(new Categoria(4,"Refrescos",2));
    }

    public static ArrayList<Categoria> listaCategorias() {
        return categorias;
    }


    private void establecerBoton() {
        boton = new JButton(this.nombre);
        boton.setMargin(new Insets(0,0));
        boton.setBackground(Color.white);
        Font fuente = new Font("Arial",10);
        boton.setFont(fuente);
        //Con el primero,siempre miden lo mismo ya que referencio la resolución del ordenador. Con el segundo,referencio el tamaño del frame,con lo que si cambio el tamaño,se cambian (no responsive=) )
        Dimension tamBot = new Dimension((((java.awt.Toolkit.getDefaultToolkit().getScreenSize().width / 2) - 40) / 12),(((Toolkit.getDefaultToolkit().getScreenSize().width / 2) - 40) / 12));
        boton.setPreferredSize(tamBot);
        boton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                ProductPane.dibujarProductos(ID);
            }
        });

    }
    public int getIDpadre() {
        return IDpadre;
    }
    public JButton getBoton() {
        return boton;
    }

}


class PantallaGeneral {
    JFrame pantalla;

    //Container general:
    private static JPanel contenedorContenido = new JPanel();
    //Salon
    private JButton boton1 = new JButton("Mesa 1");
    private JButton boton2 = new JButton("Mesa 2");
    private JButton boton3 = new JButton("Mesa 3");
    private JButton botonB = new JButton("Barra");
    //Contenedores ventas
    JPanel ventasArriba = new JPanel();
    JPanel ventasAbajo = new JPanel();
    ProductPane panelProductos = new ProductPane();
    TicketPane panelTicket = new TicketPane();


    public PantallaGeneral ()  {
        Producto.crearProductosInicio();
        initPantalla();
        dibujarPantallaVenta(0);
    }

    private void initPantalla () {
        pantalla = new JFrame();
        pantalla.setLayout(new BorderLayout());
        //pantalla.setBounds(0,ancho,alto);
        pantalla.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
        pantalla.setResizable(true);
        pantalla.setExtendedState(JFrame.MAXIMIZED_BOTH);
        pantalla.setVisible(true);
        pantalla.getContentPane().add(contenedorContenido,BorderLayout.CENTER);
    }
    private void dibujarPantallaVenta (int numeroMesa) {

        limpiarPantalla();

        panelTicket.setPreferredSize(new Dimension(java.awt.Toolkit.getDefaultToolkit().getScreenSize().width / 2,Toolkit.getDefaultToolkit().getScreenSize().height / 2));
        panelProductos.setPreferredSize(new Dimension(java.awt.Toolkit.getDefaultToolkit().getScreenSize().width / 2,Toolkit.getDefaultToolkit().getScreenSize().height / 2));
        ventasArriba.setPreferredSize(new Dimension(java.awt.Toolkit.getDefaultToolkit().getScreenSize().width,Toolkit.getDefaultToolkit().getScreenSize().height / 2));
        ventasAbajo.setPreferredSize(new Dimension(java.awt.Toolkit.getDefaultToolkit().getScreenSize().width,Toolkit.getDefaultToolkit().getScreenSize().height / 2));

        contenedorContenido.setLayout(new BoxLayout(contenedorContenido,BoxLayout.Y_AXIS));
        contenedorContenido.add(ventasArriba);
        contenedorContenido.add(ventasAbajo);
        ventasArriba.setLayout(new BoxLayout(ventasArriba,BoxLayout.X_AXIS));

        ventasArriba.add(panelTicket);
        ventasArriba.add(panelProductos);
        panelTicket.dibujarTicket(numeroMesa);
        panelProductos.dibujarProductos(1);
    }
    public void limpiarPantalla () {

        contenedorContenido.removeAll();
        contenedorContenido.updateUI();
        System.gc();
    }
}
class TicketPane extends JPanel {

    static TreeMap<Integer,DefaultTableModel> tickets=new TreeMap<>();
    static int mesaActual=0;
    JTable tablaticket = new JTable();

    public TicketPane () {

    }
    public void dibujarTicket (int numeroMesa) {
        removeAll();
        updateUI();
        tablaticket.removeAll();
        tablaticket.updateUI();
        mesaActual=numeroMesa;
        setLayout(null);
        setBackground(Color.lightGray);
        //setBounds(0,PantallaGeneral.ancho/2,PantallaGeneral.alto/2);
        if (tickets.get(mesaActual)==null) {
            tickets.put(mesaActual,new ModeloTabla());
            tickets.get(mesaActual).setColumnIdentifiers(new Object[]  { "Producto","Precio"});
        }
        //tablaticket.setBounds(0+(int)(PantallaGeneral.ancho/2*0.05),0+(int)(PantallaGeneral.alto/2*0.05),PantallaGeneral.ancho/2-(int)(PantallaGeneral.ancho/2*0.10),PantallaGeneral.alto/2-(int)(PantallaGeneral.alto/2*0.10));
        tablaticket.setVisible(true);
        tablaticket.setModel(tickets.get(mesaActual));
        tablaticket.addMouseListener(new MouseAdapter()
        {
            public void mouseClicked(MouseEvent e)
            {
                int fila = tablaticket.rowAtPoint(e.getPoint());
                System.out.println("Se selecciono la fila: " + fila);

            }
        });
        tablaticket.getColumn("Producto").setPreferredWidth(this.getWidth()-(int)(this.getWidth()*0.15));
        javax.swing.JScrollPane jScrollPane1;
        jScrollPane1 = new javax.swing.JScrollPane();
        jScrollPane1.setViewportView(tablaticket);


        //add(tablaticket);
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jScrollPane1,javax.swing.GroupLayout.DEFAULT_SIZE,388,Short.MAX_VALUE)
                                .addContainerGap())
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addComponent(jScrollPane1,288,Short.MAX_VALUE)
                                .addContainerGap())
        );


        //pantalla.getContentPane().add(this);
        updateUI();

    }
    public static void añadirProductoTicket(Producto producto) {
        NumberFormat nw = NumberFormat.getInstance(new Locale("en","EN"));
        nw.setMaximumFractionDigits(2);
        nw.setMinimumFractionDigits(2);
        if (tickets.get(mesaActual).getRowCount()==0){
            tickets.get(mesaActual).addRow(new Object[] {producto.getNombre(),nw.format(producto.getPrecio())});
            tickets.get(mesaActual).addRow(new Object[] {"Total Ticket: ",nw.format(producto.getPrecio())});
        }
        else {
            double total=Double.parseDouble( tickets.get(mesaActual).getValueAt(tickets.get(mesaActual).getRowCount()-1,tickets.get(mesaActual).getColumnCount()-1).toString());
            tickets.get(mesaActual).removeRow(tickets.get(mesaActual).getRowCount()-1);
            tickets.get(mesaActual).addRow(new Object[] {producto.getNombre(),nw.format(producto.getPrecio())});
            total+=producto.getPrecio();
            tickets.get(mesaActual).addRow(new Object[] {"Total Ticket: ",nw.format(total)});
        }

    }
    public void calcularTotal () {

    }

    public static int getMesaActual() {
        return mesaActual;
    }
}
class ModeloTabla extends DefaultTableModel {
    public boolean isCellEditable(int row,int column) {
        return false;
    }
}

第一次编辑之前的代码

    //Main sales drawing
            private void dibujarPantallaVenta (int numeroMesa) {
                limpiarPantalla();
                panelTicket.setPreferredSize(new Dimension(java.awt.Toolkit.getDefaultToolkit().getScreenSize().width/2,Toolkit.getDefaultToolkit().getScreenSize().height/2));
                panelProductos.setPreferredSize(new Dimension(java.awt.Toolkit.getDefaultToolkit().getScreenSize().width/2,Toolkit.getDefaultToolkit().getScreenSize().height/2));
                ventasArriba.setPreferredSize(new Dimension(java.awt.Toolkit.getDefaultToolkit().getScreenSize().width,Toolkit.getDefaultToolkit().getScreenSize().height/2));
                ventasAbajo.setPreferredSize(new Dimension(java.awt.Toolkit.getDefaultToolkit().getScreenSize().width,Toolkit.getDefaultToolkit().getScreenSize().height/2));
        
                pantalla.getContentPane().add(contenedorContenido,BorderLayout.CENTER);
                contenedorContenido.setLayout(new BoxLayout(contenedorContenido,BoxLayout.Y_AXIS));
                contenedorContenido.add(ventasArriba);
                contenedorContenido.add(ventasAbajo);
                ventasArriba.setLayout(new BoxLayout(ventasArriba,BoxLayout.X_AXIS));
        
                ventasArriba.add(panelTicket);
                ventasArriba.add(panelProductos);
                panelTicket.dibujarTicket(numeroMesa); //Dibujo el ticket del numero de mesa indicado
                panelProductos.dibujarProductos(1,panelTicket); //Siempre que se abre una mesa,se pinta la categoria general por defecto
        
            }
        public class ProductPane extends JScrollPane  {
        static JPanel contenedorPanelProductos = new JPanel();
        JPanel panelProductos;
        public ProductPane () {
            super(
                    contenedorPanelProductos,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED
    );
            this.setLayout(new ScrollPaneLayout());
            panelProductos=new JPanel();
        }
    
        //This is where i paint my JButtons:
          public void dibujarProductos ( int categoria,TicketPane ticketMesa) {
                //Pendiente: Establecer un tamaño inicial para los botones. Permitir agrandar y achicar este tamaño,asi como el numero de columnas para un ajuste personalizado
                ArrayList<Categoria> categorias = Categoria.listaCategorias().stream().filter(x->x.getIDpadre()==categoria).collect(Collectors.toCollection(ArrayList::new));
                ArrayList<Producto> productos = Producto.listaProductos().stream().filter(x->x.getID_Categoria()==categoria).collect(Collectors.toCollection(ArrayList::new));
        
                panelProductos.removeAll();
                panelProductos.updateUI();
        
                JButton botones;
        
                panelProductos.setLayout(new GridBagLayout());
                GridBagConstraints c = new GridBagConstraints();
                c.anchor = GridBagConstraints.FirsT_LINE_START;
                c.weightx = 1.0;
                c.weighty = 1.0;
                c.ipadx = 0;
                c.ipady = 0;
        
                panelProductos.setBackground(Color.yellow);
                int x=0,y=0;
                for (int i = 0; i<categorias.size();i++) {
                    botones=categorias.get(i).getBoton();
                    int finalI = i;
                    botones.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            dibujarProductos(categorias.get(finalI).getID(),ticketMesa);
                        }
                    });
                    c.gridx = x;
                    c.gridy = y;
                    x++;
                    if (x==12){
                        x-=12;
                        y++;
                    }
                    c.anchor = GridBagConstraints.FirsT_LINE_START;
                    panelProductos.add(botones,c);
                }
                for (int i = 0; i<productos.size();i++) {
                    botones=productos.get(i).getBoton();
                    c.gridx = x;
                    c.gridy = y;
                    x++;
                    if (x==12){
                        x-=12;
                        y++;
                    }
                    panelProductos.add(botones,c);
                }
                if (categoria>1) {
                    botones = new JButton("General");
                    botones.setMargin(new Insets(0,0));
                    Font fuente = new Font("Arial",10);
                    botones.setFont(fuente);
                    botones.setBackground(Color.white);
                    botones.setPreferredSize(new Dimension((((java.awt.Toolkit.getDefaultToolkit().getScreenSize().width/2)-40)/12),(((Toolkit.getDefaultToolkit().getScreenSize().width/2)-40)/12)));
                    botones.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            dibujarProductos(1,ticketMesa);
                        }
                    });
                    c.gridx = x;
                    c.gridy = y;
                    x++;
                    if (x==12){
                        x-=12;
                        y++;
                    }
                    panelProductos.add(botones,c);
                }
                agregarPanel(panelProductos);
        
            }
            public void agregarPanel (JPanel panelProductos) {
                contenedorPanelProductos.setBackground(Color.BLUE);
                contenedorPanelProductos.setBorder(BorderFactory.createEmptyBorder(10,20));
                contenedorPanelProductos.setLayout(new GridBagLayout());
                GridBagConstraints v = new GridBagConstraints();
                v.weightx = 1;
                v.weighty = 1;
                v.anchor=GridBagConstraints.FirsT_LINE_START;
                contenedorPanelProductos.add(panelProductos,v);
            }

我使用panelProductos是因为如果我不这样做,当我添加按钮时,它们似乎具有相同的填充,我会以其他方式修复

实际IU:

Actual UI

无面板产品:

Without panelProductos 1

Without panelProductos 2

解决方法

希望我了解您想要做什么。您根本不希望显示水平滚动条。解决方法非常简单。更改类export default { data() { return { myTimeout: null }; },onChangeName(event) { if (event.target._value.length > 0) { this.loading = true; this.myTimeout = setTimeout(() => ( this.isNameCompleted = true,this.loading = false,this.isLoaderFinished = true,this.$refs.scrolled_3.focus()),2200); } } 的构造函数。下面只是需要在代码中更改的部分。

ProductPane

在原始代码中,您使用了class ProductPane { public ProductPane() { super(contenedorPanelProductos,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); } } 。这是默认设置,因此您无需显式设置它。但是您不希望出现水平滚动条,因此请使用HORIZONTAL_SCROLLBAR_AS_NEEDED。试试看,自己看看。如果它不起作用,请告诉我,我将删除此答案。

,

我想我了解您要做什么。我不知道您的GUI的底面板是什么。

我尝试运行您的代码并遇到问题。当我尝试减小GUI的大小时,GUI将从监视器中消失。这些按钮将消失并重新出现。

我从头开始创建了POS模拟器GUI。我不得不使用一些Swing技巧,我将对其进行详细说明。

这是GUI。

POS Simulation GUI

展开GUI填充屏幕时,按钮将移动位置以填充空间。记录带面板的尺寸保持不变。

通常,当您创建Swing GUI时,请尝试使其尽可能小。与尝试缩小GUI以使其适合特定显示器相比,扩大GUI的大小要容易得多。

我决定将JTextArea用于寄存器显示,以节省更多的GUI空间。

我从简单开始。我首先创建了JFrameItemInventory类。 Item类保存项目的名称和价格,而Inventory类保存多个项目。我将项目价格节省了几美分,这样我就可以进行整数算术而不用担心舍入错误。

我删除了所有静态的Swing组件,字段和方法。跟踪实例要比处理静态字段的副作用容易得多。

我使用了Swing组件。我没有扩展任何Swing组件。唯一的扩展Swing组件或任何Java类的方法是,当您要重写其中一个类方法时。

我一次只构建了一个小块GUI,并在编码时对其进行了测试。在运行一个或多个测试之前,我很少添加20至30行代码。我无法编写500行代码并使它们全部正确。

我写了6堂课。 POSSimulator类包含JFrame。我将其余的类设为内部类,以便可以将代码发布为完整的可执行示例。

ButtonPanel类创建按钮面板。 RegisterPanel类创建注册磁带面板。 ButtonListener类实现ActionListener并赋予按钮其功能。

Inventory类保存库存。 Item类包含一个项目。

每个类都按照类的名称进行操作。您的GUI越大,每个类做一件事情一件事情就越重要。

ButtonPanel类创建一个外部JPanel,其中包含一个JScrollPane,一个内部JPanel,其中包含一个单独的按钮JPanels。听起来很复杂,但是它允许外部JPanel增大,并使单个按钮JPanels保持其大小。

我创建了40个按钮。我只为库存创建了4个物料,因此重复了10次库存。您可能希望调整createPanel方法中的代码,以便为库存中的每个项目创建一个按钮。

您将不得不使用JPanel的首选尺寸,具体取决于您制作JButtons的首选尺寸。注释中有关不设置首选大小的建议适用于普通GUI。您的GUI是一个特殊的应用程序,直到您进一步解释了您要做什么之后,我才了解它。

RegisterPanel类更简单。 appendItem方法将一个项目附加到注册磁带面板。我使用format类的String方法来格式化商品的名称和价格,以及总价。

ButtonListener类从JButton获取项目的名称,在清单中查找该项目,并调用appendItem类的RegisterPanel方法。

InventoryItem类是普通的Java类,分别用于保存库存和物料。

这是代码。

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
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.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class POSSimulator implements Runnable {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new POSSimulator());
    }
    
    private ButtonPanel buttonPanel;
    
    private Inventory inventory;
    
    private JFrame frame;
    
    private RegisterPanel registerPanel;
    
    public POSSimulator() {
        this.inventory = new Inventory();
    }

    @Override
    public void run() {
        frame = new JFrame("POS Si8mulator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        registerPanel = new RegisterPanel();
        frame.add(registerPanel.getPanel(),BorderLayout.BEFORE_LINE_BEGINS);
        
        buttonPanel = new ButtonPanel();
        frame.add(buttonPanel.getPanel(),BorderLayout.CENTER);
        
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }
    
    public class ButtonPanel {
        
        private JPanel panel;
        
        public ButtonPanel() {
            createPanel();
        }
        
        private void createPanel() {
            panel = new JPanel(new BorderLayout());
            panel.setPreferredSize(new Dimension(360,600));
            
            JPanel innerPanel = new JPanel(new FlowLayout(
                    FlowLayout.LEADING));
            innerPanel.setPreferredSize(new Dimension(340,2320));
            
            ButtonListener listener = new ButtonListener();
            
            List<Item> items = inventory.getInventory();
            int size = items.size();
            int j = 0;
            
            // We're creating more buttons than inventory
            for (int i = 0; i < 40; i++) {
                JPanel buttonPanel = createButtonPanel(
                        items.get(j),listener);
                innerPanel.add(buttonPanel);
                j++;
                j = (j >= size) ? 0 : j;
            }
            
            JScrollPane scrollPane = new JScrollPane(innerPanel);
            panel.add(scrollPane,BorderLayout.CENTER);
        }
        
        private JPanel createButtonPanel(Item item,ButtonListener listener) {
            JPanel panel = new JPanel(new BorderLayout());
            panel.setBorder(BorderFactory.createEmptyBorder(5,5,5));
            
            JButton button = new JButton(item.getName());
            button.addActionListener(listener);
            button.setPreferredSize(new Dimension(150,100));
            panel.add(button,BorderLayout.CENTER);
            
            return panel;
        }

        public JPanel getPanel() {
            return panel;
        }
        
    }
    
    public class RegisterPanel {
        
        private int total;
        
        private JPanel panel;
        
        private JTextArea textArea;
        
        private String totalString;
        
        public RegisterPanel() {
            this.totalString = "Register total";
            
            setTotal(0);
            createPanel();
        }
        
        private void setTotal(int total) {
            this.total = total;
        }
        
        private void createPanel() {
            panel = new JPanel(new BorderLayout());
            
            textArea =  new JTextArea(10,40);
            textArea.setText("");
            textArea.setFont(new Font(
                    "Courier New",Font.BOLD,12));
            
            JScrollPane scrollPane = new JScrollPane(textArea);
            panel.add(scrollPane,BorderLayout.CENTER);
        }
        
        public void appendItem(Item item) {
            int price = item.getPrice();
            total += price;
            
            String tape = textArea.getText();
            if (!tape.isEmpty()) {
                int pos = tape.indexOf(totalString);
                tape = tape.substring(0,pos);
            }
            
            String line = String.format("%-30s",item.getName());
            line += String.format("%7.2f",0.01d * price);
            tape += line + System.lineSeparator();
            
            line = String.format("%-30s",totalString);
            line += String.format("%7.2f",0.01d * total);
            tape += line + System.lineSeparator();
            
            textArea.setText(tape);
        }

        public JPanel getPanel() {
            return panel;
        }
        
    }
    
    
    public class ButtonListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent event) {
            JButton button = (JButton) event.getSource();
            String name = button.getText();
            Item item = inventory.getItem(name);
            registerPanel.appendItem(item);
        }
        
    }
    
    public class Inventory {
        
        private List<Item> inventory;
        
        public Inventory() {
            this.inventory = new ArrayList<>();
            addInventory();
        }
        
        private void addInventory() {
            inventory.add(new Item("Coke Zero","3.33"));
            inventory.add(new Item("Sprite Zero","3.33"));
            inventory.add(new Item("Dark Kidney Beans",".99"));
            inventory.add(new Item("Tomato Sauce","1.19"));
        }
        
        public void addItem(Item item) {
            inventory.add(item);
        }
        
        public Item getItem(String name) {
            for (Item item : inventory) {
                if (item.getName().equals(name)) {
                    return item;
                }
            }
            
            return null;
        }

        public List<Item> getInventory() {
            return inventory;
        }
        
    }
    
    public class Item {
        
        private int price;
        
        private String name;
        
        public Item(String name,String price) {
            this.name = name;
            setPrice(price);
        }
        
        public void setPrice(String price) {
            Double value = Double.valueOf(price);
            this.price = (int) Math.round(100d * value);
        }

        public int getPrice() {
            return price;
        }

        public String getName() {
            return name;
        }
        
    }

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。