java - 如何停止改变按钮的位置?

标签 java swing user-interface layout-manager

我有一些简单的 GUI 的 Java Swing 代码,其中包含 JButtonJTextPaneJTextField

此代码的问题是,当我尝试在 textPane (JTextPane) 内写入一些文本时,openButton (JButton) 开始在与我正在编写的文本平行的右侧移动。

我认为问题出在 BoxLayout 内部,但我不确定,因为这是我第一次使用它。

这是整个代码:

import java.awt.Dimension;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.BoxLayout;

public class Name {

public static void main(String[] args) {
    JFrame frame = new JFrame("Box layout Application");
    frame.setSize(800, 800);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel panel = new JPanel();
    panel.setBorder(new EmptyBorder(new Insets(20, 20, 20, 20)));
    frame.add(panel);
    placeComponents(panel);

    frame.setVisible(true);
}

/**
 * Placing the GUI element on panel:
 * - button for opening FileChooser
 * - text area to display text
 * - display results
 * @param Panel on which to place the elements
 */
private static void placeComponents(JPanel panel) {
    BoxLayout boxLayout = new BoxLayout(panel, BoxLayout.Y_AXIS);
    panel.setLayout(boxLayout);

    // Button to open file location
    JButton openButton = new JButton("Choose File to open");
    openButton.setBounds(10, 80, 80, 25);
    openButton.setHorizontalAlignment(SwingConstants.LEFT);
    openButton.addActionListener(new ActionListener() {          
        public void actionPerformed(ActionEvent e) {
            //Execute when button is pressed
            // JFileChooser object
            JFileChooser chooser = new JFileChooser();
            // Dialog to open the file
            int rueckgabeWert = chooser.showOpenDialog(null);

            // Is everything OK
            if(rueckgabeWert == JFileChooser.APPROVE_OPTION) {
                // Getting address of the file
                chooser.getSelectedFile().getAbsolutePath();
            }
        }
    });      
    panel.add(openButton);
    panel.add(Box.createRigidArea(new Dimension(0, 5)));

    // Open document
    JTextPane textPane = new JTextPane();
    textPane.setPreferredSize(new Dimension(600, 600));

    for (int i=0; i < 1; i++) {
        //doc.insertString(doc.getLength(), initString[i], doc.getStyle(initStyles[i]));
    }

    panel.add(textPane);
    panel.add(Box.createRigidArea(new Dimension(0, 5)));

    // to search for something
    JTextField searchField = new JTextField(1);
    panel.add(searchField);
}
}

最佳答案

将 JButton 放入使用 FlowLayout 设置为 FlowLayout.LEADING 的 JPanel

JButton openButton = new JButton("Choose File to open");
JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
topPanel.add(openButton);

panel.add(topPanel);

此外,根据评论,删除程序中的所有 setBounds(...) 代码,永远不要设置文本组件的大小或首选大小,并将 JTextPane 放在 JScrollPane 中。


例如:

import java.awt.Dimension;
import java.awt.FlowLayout;

import javax.swing.*;

public class Name2 extends JPanel {
   private static final int GAP = 5;

   public Name2() {
      JPanel topPanel = new JPanel();
      topPanel.setLayout(new FlowLayout(FlowLayout.LEADING, 0, 0));
      topPanel.add(new JButton("Choose File to Open"));

      JTextPane textPane = new JTextPane() {
         public Dimension getPreferredScrollableViewportSize() {
            return new Dimension(750, 600);
         };
      };

      setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
      setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));

      add(topPanel);
      add(Box.createVerticalStrut(GAP));
      add(new JScrollPane(textPane));
      add(Box.createVerticalStrut(GAP));
      add(new JTextField());
   }

   private static void createAndShowGui() {
      Name2 mainPanel = new Name2();

      JFrame frame = new JFrame("Name2");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

关于java - 如何停止改变按钮的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28263390/

相关文章:

java - Spring Boot中取消授权

java - 如何在 Java 中读取一个 String 后跟一个 int?

java - JLabel 可以有多小?

design-patterns - 是否有用于设计具有多个字段的搜索表单的良好 UI 模式?

Java - JToggleButton - 虽然无限循环 - 无法单击按钮两次

java - 如何使用 JSONPath 获取根级别 JSON 对象的键/名称?

java - 使用 HttpsUrlConnection 重用 TCP 连接

java - 如果放置在 setVisible(true) 之后,JDialog 中的事件处理程序将不起作用

java - 从菜单转发操作到父类

python - Python 程序中的 'StringVar' 问题