JSeperator in JToolBar moves the components to right end

守給你的承諾、 提交于 2019-12-11 03:12:13

问题


I am looking at Oracle's JToolBar code and trying to add JLabels within that toolbar. I have simulated the button-like feel for them by overriding the mouse events.

It worked fine until I tried to add a JSeperator as I wanted a vertical line. I have added a separator after 3 JLabels causing the rest of them to get moved to the right end as shown below.

I have tried adding the addSeparator() just before and after the JSeparator code , but still no luck.

Code

import javax.swing.JToolBar;
import javax.swing.JButton;
import javax.swing.ImageIcon;

import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;


import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FilenameFilter;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JSeparator;

public class ToolBarDemo extends JPanel
        implements ActionListener {

    protected JTextArea textArea;
    protected String newline = "\n";
    static final private String PREVIOUS = "previous";
    static final private String UP = "up";
    static final private String NEXT = "next";

    public ToolBarDemo() {
        super(new BorderLayout());

        //Create the toolbar.
        final JToolBar toolBar = new JToolBar("Still draggable");
        toolBar.setBorderPainted(true);

        //Getting only files whose name ending with '_24px.png' 
        File dir = new File("G:\\MyImagesFolder");
        File[] files = dir.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith("_24px.png");
            }
        });

        int count = 0;
        for (File pngFile : files) {
            // Trying to add 'JSeperator' after third 'JLabel'
            if (count == 3) {
                toolBar.addSeparator();
                JSeparator separator = new JSeparator();
                separator.setOrientation(JSeparator.VERTICAL);

                toolBar.add(separator);
                toolBar.addSeparator();
            }
            count++;
            System.out.println(pngFile.toString());
            toolBar.add(getToolBarIcon(pngFile.toString()));
        }

        //Create the text area used for output.  Request
        //enough space for 5 rows and 30 columns.
        textArea = new JTextArea(5, 30);
        textArea.setEditable(true);
        JScrollPane scrollPane = new JScrollPane(textArea);

        //Lay out the main panel.
        setPreferredSize(new Dimension(450, 130));
        add(toolBar, BorderLayout.PAGE_START);
        add(scrollPane, BorderLayout.CENTER);
        JButton b = new JButton("OK");
        b.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (toolBar.isVisible()) {
                    toolBar.setVisible(false);
                } else {
                    toolBar.setVisible(true);
                }
            }
        });
        add(b, BorderLayout.PAGE_END);
    }

    public JLabel getToolBarIcon(String fileName) {
        final JLabel lblToolBarIcon = new JLabel(new ImageIcon(fileName));
        lblToolBarIcon.setToolTipText(fileName);
        lblToolBarIcon.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
        lblToolBarIcon.addMouseListener(new MouseListener() {

            @Override
            public void mouseClicked(MouseEvent e) {

            }

            @Override
            public void mousePressed(MouseEvent e) {
                System.out.println("pressed");
                lblToolBarIcon.setBorder(BorderFactory.createLoweredSoftBevelBorder());
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                System.out.println("released");

                lblToolBarIcon.setBorder(BorderFactory.createRaisedSoftBevelBorder());

            }

            @Override
            public void mouseEntered(MouseEvent e) {
                System.out.println("enter");
                lblToolBarIcon.setBorder(BorderFactory.createRaisedSoftBevelBorder());
            }

            @Override
            public void mouseExited(MouseEvent e) {
                System.out.println("exit");
                lblToolBarIcon.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
            }
        });

        return lblToolBarIcon;
    }

    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();
        String description = null;

        // Handle each button.
        if (PREVIOUS.equals(cmd)) { //first button clicked
            description = "taken you to the previous <something>.";
        } else if (UP.equals(cmd)) { // second button clicked
            description = "taken you up one level to <something>.";
        } else if (NEXT.equals(cmd)) { // third button clicked
            description = "taken you to the next <something>.";
        }

    }

    /**
     * Create the GUI and show it. For thread safety, this method should be
     * invoked from the event dispatch thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("ToolBarDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Add content to the window.
        frame.add(new ToolBarDemo());

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event dispatch thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                //Turn off metal's use of bold fonts
                UIManager.put("swing.boldMetal", Boolean.FALSE);
                createAndShowGUI();
            }
        });
    }
}

How should I overcome this ? What is my mistake here ?


回答1:


Specify the Dimensions of the JSeparator explicitly so the LayoutManager is aware of any size constraints on the Component. For instance you can define the JSeparator's maximum size by overriding the getMaximumSize method:

JSeparator separator = new JSeparator(){
    @Override
    public Dimension getMaximumSize(){
        return new Dimension(5, 25);
    }
};
separator.setOrientation(JSeparator.VERTICAL);
toolBar.add(separator);



回答2:


//toolBar.add(separator);
toolBar.addSeparator();

Don't use the add(...) method to use a JSeparator.

JToolbar has a convenience method addSeparator() to add a separator to the toolbar.



来源:https://stackoverflow.com/questions/30196854/jseperator-in-jtoolbar-moves-the-components-to-right-end

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!