简体   繁体   中英

How to create snapped components with java swing?

I have worked hard on writing my GUI in swing however I am trying to improve it further since I feel it still looks a little off.

I would ideally like:

  • the button to snap to the top right,
  • the textfield to be the same height as the button and stretch from the top left to the button edge
  • the scrollpane to stretch from the bottom of the textfield and the button to the edges of the window even when stretched.

I'm unsure how to "snap" the components to the top right, top left and rest of the area respectively.

    @SuppressWarnings("serial")
    class TFrame extends JFrame
    {
      TFrame()
      {
        super("Huffman Compression");//setTitle
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400, 300);
        setResizable(true);

        jPanel = new JPanel();

        jTextField = new JTextField("Enter string to compress...");

        jButton = new JButton("Compress");
        jButton.setFocusable(false);

        jTextArea = new JTextArea("LOG AREA", 30, 30);
        jTextArea.setWrapStyleWord(true);
        jTextArea.setLineWrap(true);
        jTextArea.setEditable(false);
        jTextArea.setFocusable(false);
        jTextArea.setOpaque(false);

        jScrollPane = new JScrollPane(jTextArea);
        jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

        jPanel.add(jTextField, BorderLayout.WEST);
        jPanel.add(jButton, BorderLayout.EAST);
        jPanel.add(jScrollPane, BorderLayout.SOUTH);

        add(jPanel);

        try
        {
          UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException
               | InstantiationException
               | IllegalAccessException
               | UnsupportedLookAndFeelException e)
        {
          e.printStackTrace();
        }

        setVisible(true);
      }

      private JPanel jPanel;
      private JTextField jTextField;
      private JButton jButton;
      private JTextArea jTextArea;
      private JScrollPane jScrollPane;

    }

    public static void main(String[] args)
        {

          TFrame frame = new TFrame();

        frame.pack();
        ...

This is what it currently looks like: http://i.imgur.com/90cmDl1.png

Regards.

Basically, you need to take advantage of a series of layout managers (commonly known as "compound layouts").

For example, you can accomplish the requirements for the button and field using a GridBagLayout and the by using a BorderLayout , you can accomplish the rest, for example...

日志窗口

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class BrowserWindow {

    public static void main(String[] args) {
        new BrowserWindow();
    }

    public BrowserWindow() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JPanel topPane = new JPanel(new GridBagLayout());
                GridBagConstraints gbc = new GridBagConstraints();
                gbc.gridx = 0;
                gbc.gridy = 0;
                gbc.weightx = 1;
                gbc.fill = GridBagConstraints.BOTH;
                topPane.add(new JTextField(10), gbc);
                gbc.weightx = 0;
                gbc.fill = GridBagConstraints.NONE;
                gbc.gridx++;
                topPane.add(new JButton("Compress"), gbc);

                JTextArea ta = new JTextArea("Log...", 30, 30);
                JScrollPane sp = new JScrollPane(ta);

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(topPane, BorderLayout.NORTH);
                frame.add(sp);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}

Take a look at Laying Out Components Within a Container for more details

Whether you're learning Swing or just want a quick GUI, I highly recommend using the NetBeans IDE for its WYSIWYG Swing editor. You could even re-create the same GUI you've already built (in seconds) just to compare your own code to the auto-generated version and learn from the differences.

More to the topic:

  • Controls snap into place as you drag them.
  • Selecting multiple controls allows syncing of their dimensions.
  • Snapping controls to the edges of a frame causes them to stretch by default.

There is some learning curve, because everything is configurable; but if you plan to make more than one Swing application in your life, Netbeans is the (free) way to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM