Search code examples
javaswingjcomponent

how to put some java swing control in top right corner properly?


first sorry for asking this question, i am totally new to java, really need some guide. so let say i want to make java GUI like this

enter image description here

want to make the header background responsive, so i separate the background image into 2 part, the brown one & orange one, what i want to achieve is make the brown part resizeable.

    @SuppressWarnings("serial")
    class ImagePanel extends JPanel 
    {
        private Image image;
        private boolean tile;

        ImagePanel(Image image) throws IOException 
        {
            this.image = image;
            this.tile = false;
        };

        @Override
        public void paintComponent(Graphics g) 
        {
            super.paintComponent(g);
            if (tile) 
            {
                int iw = image.getWidth(this);
                int ih = image.getHeight(this);
                if (iw > 0 && ih > 0) 
                {
                    for (int x = 0; x < getWidth(); x += iw) 
                    {
                        for (int y = 0; y < getHeight(); y += ih) 
                        {
                            g.drawImage(image, x, y, iw, ih, this);
                        }
                    }
                }
            } 
            else 
            {
                g.drawImage(image, 0, 0, getWidth(), 65, this);

            }
        }
    }

    public class FileListing 
    {
           public Component getGui(File[] all, boolean vertical) 
           {
                // put File objects in the list..
                fileList1 = new JList(all);
                fileList1.setFixedCellWidth(150);

                fileList1.addListSelectionListener(new HtmlListing());

                // ..then use a renderer
                fileList1.setCellRenderer(new FileRenderer(!vertical));

                if (!vertical) 
                {
                    fileList1.setLayoutOrientation(javax.swing.JList.HORIZONTAL_WRAP);
                    fileList1.setVisibleRowCount(-1);
                } 
                else 
                {
                    fileList1.setVisibleRowCount(9);
                }
                return new JScrollPane(fileList1);
            }

           static ArrayList<File> globarr = null;
           static JList fileList1 = null;
           static SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
           static JTable table = null;
           static JPanel gui = null;
           static JPanel CentCont = null;
           static JPanel EastCont = null;

           static class HtmlListing implements ListSelectionListener
            {
                public void valueChanged(ListSelectionEvent event) 
                {
                  if (!event.getValueIsAdjusting())
                  {
                      globarr = new ArrayList<File>();

                      FileListing fl = new FileListing();
                      fl.walk(fileList1.getSelectedValue() + "work\\airasia\\html", 500, 0);    

                      if(globarr.size() > 0)
                      {
                           Object[][] data = new Object[globarr.size()][globarr.size()];

                           for(int i = 0; i < globarr.size(); i++)
                           {
                               if(globarr.get(i).isFile())
                               {
                                   //tes[i] = (File)globarr.get(i);
                                   String filename =  globarr.get(i).getName().toString();
                                   String date = sdf.format(globarr.get(i).lastModified());

                                   Object[] obj = new Object[] {filename,  filename.substring(filename.lastIndexOf(".") + 1), date, globarr.get(i).getAbsolutePath()};
                                   data[i] = obj;
                               }
                           }

                          Object[] column = new Object[]{"name ", "type", "date modified", "path"}; 




                          DefaultTableModel model = new DefaultTableModel(data, column);

                           table =   new JTable(model) 
                           {
                                private static final long serialVersionUID = 1L;

                                public boolean isCellEditable(int row, int column) 
                                {                
                                        return false;               
                                };  
                            };


                           table.addMouseListener(new MouseAdapter()
                           {
                                 public void mouseClicked(MouseEvent e)
                                 {
                                      if (e.getClickCount() == 2)
                                      {
                                          int rowIdx = table.getSelectedRow(); // path to your new file
                                          TableModel tm = table.getModel();
                                          String path =  tm.getValueAt(rowIdx, 3).toString(); 
                                          File htmlFile = new File(path);

                                          try // open the default web browser for the HTML page
                                          {
                                              Desktop.getDesktop().browse(htmlFile.toURI());
                                              //Desktop.getDesktop().open(htmlFile);
                                          } 
                                          catch (IOException e1) 
                                          {
                                                // TODO Auto-generated catch block
                                                e1.printStackTrace();
                                          }
                                      }
                                 }
                            });

                           table.removeColumn(table.getColumnModel().getColumn(3));

                           table.setFillsViewportHeight(true);
                           table.setIntercellSpacing(new Dimension(0, 0));
                           table.setShowGrid(false);


                           JScrollPane scrollPane = new JScrollPane(table);

                           EastCont = new JPanel();
                           EastCont.setLayout(new BorderLayout());
                           EastCont.add(scrollPane);
                           EastCont.setPreferredSize(new Dimension(1100, 0));

                           gui.add(EastCont, BorderLayout.EAST);
                           gui.revalidate();
                           gui.repaint();  
                     }
                     else                  
                     {
                           //CentCont.remove(comp);
                           EastCont.remove(table);
                           gui.remove(EastCont);
                           gui.revalidate();
                           gui.repaint();
                     } 
                }       
             }  
          }

          int idx = 0;

          public void walk( String path, int length, int loopidx ) 
          {
              File root = new File( path );
              File[] list = root.listFiles();

              if (list == null) return ;

              for ( File f : list )
              {
                if ( f.isDirectory() ) 
                {
                    walk( f.getAbsolutePath(), 0, idx);    
                }
                else 
                {
                    if(f.getName().endsWith(".html"))
                    {
                        globarr.add(f);
                        idx += 1;
                    }
                 }
               }
            }

 public static void main(String[] args) throws IOException 
        {

            JFrame frame = new JFrame("File List");
            gui = new JPanel(new BorderLayout());

             JButton btnScan = new JButton("SCAN");
             //btnScan.setPreferredSize(new Dimension(70, 40));
             btnScan.setBounds(0, 0, 200, 100);

             btnScan.addActionListener(new ActionListener()
             {
                  public void actionPerformed(ActionEvent e)
                  {
                     File[] f = File.listRoots();
                     FileListing fl = new FileListing();    

                     Component c =  fl.getGui(f,true);
                     CentCont.add(c);
                     CentCont.setBorder(new EmptyBorder(3,3,3,3));
                     CentCont.setPreferredSize(new Dimension(50, 100));

                  }
             });  


             Image image = ImageIO.read(new File("C:\\Users\\User\\Desktop\\header-coklat_01_01.jpg"));
             JPanel imagePanel = new ImagePanel(image);

             JLabel lbl = new JLabel();
             ImageIcon imgThisImg = new ImageIcon(ImageIO.read(new File("C:\\Users\\User\\Desktop\\dashboard_02.jpg")));
             lbl.setIcon(imgThisImg);


             JPanel anotherPanel = new JPanel();  /// multiple panel, 
             anotherPanel.setSize(1000, 0);
             anotherPanel.setOpaque(false); // THIS IS VERY MUCH IMPORTANT
             anotherPanel.add(lbl);

             ImagePanel tes = new ImagePanel(image);
             tes.add(imagePanel, BorderLayout.WEST);
             tes.add(anotherPanel, BorderLayout.EAST);

             CentCont =  new JPanel();
             CentCont.setLayout(new BorderLayout());

             JButton btnPreview = new JButton("Preview");
             btnPreview.setBounds(25, 25, 200, 100);
             //btnPreview.setPreferredSize(new Dimension(70, 40));
             btnPreview.addActionListener(new ActionListener()
             {
                  public void actionPerformed(ActionEvent e)
                  {
                      int rowIdx = table.getSelectedRow(); // path to your new file
                      TableModel tm = table.getModel();
                      String path =  tm.getValueAt(rowIdx, 3).toString(); 
                      File htmlFile = new File(path);

                      // open the default web browser for the HTML page
                      try 
                      {
                          Desktop.getDesktop().browse(htmlFile.toURI());
                          //Desktop.getDesktop().open(htmlFile);

                      } 
                      catch (IOException e1) 
                      {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                      }
                  }
             });  

             JPanel WestCont = new JPanel();
             WestCont.setLayout(new BorderLayout());
             WestCont.add(btnScan, BorderLayout.NORTH);
             WestCont.add(btnPreview, BorderLayout.CENTER);

             //gui.setPreferredSize(new Dimension(100, 600));
             gui.add(WestCont, BorderLayout.WEST);

             //CentCont.add(btnPreview, BorderLayout.SOUTH);
             gui.add(CentCont, BorderLayout.CENTER);
             gui.add(tes, BorderLayout.NORTH);

             frame.setContentPane(gui);
             frame.setExtendedState(Frame.MAXIMIZED_BOTH);  
             frame.pack();
             frame.setLocationByPlatform(true);
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setVisible(true);         

        }
    }


    }

so far i have tried this, but the GUI look like a mess, i can't put those 2 parts correctly, this is how it look..

enter image description here

i have searching on the internet for a few days and still have not found the answer yet.


Solution

  • i have searching on the internet for a few days and still have not found the answer yet.

    • put JLabel with Icon/ImageIcon

    • to JPanel, change Layout Manager to FlowLayout.RIGHT (default Layout Manager is FlowLayout)

    • a.m. JPanel put to JFrame.NORTH area (default Layout Manager is BorderLayout)

    • Dimension (my three above points) is calculated from used LayoutManagers by Icon/ImageIcon's pixels size

    EDIT

    i already did point 1 to 3 but not showing any difference.

    • not true

    enter image description here

    from code, is required to align (horizontal & vertical) Icon, IconGap, more see in JLabel API

    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import javax.swing.Icon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    
    public class FlowLayoutRight {
    
        private JFrame frame = new JFrame();
        private JPanel panelNorth = new JPanel() {
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(200, 50);
            }
        };
        private Icon icon = UIManager.getIcon("OptionPane.errorIcon");
        private JLabel label = new JLabel(icon);
        private JPanel panelCenter = new JPanel() {
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(300, 200);
            }
        };
    
        public FlowLayoutRight() {
            panelNorth.setLayout(new FlowLayout(FlowLayout.RIGHT));
            panelNorth.add(label);
            panelNorth.setBackground(Color.BLUE);
            panelCenter.setBackground(Color.ORANGE);
            frame.add(panelNorth, BorderLayout.NORTH);
            frame.add(panelCenter);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocation(100, 100);
            frame.setVisible(true);
        }
    
        public static void main(String[] args) throws Exception {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new FlowLayoutRight();
                }
            });
        }
    }