Fancy0731
2021-11-09 15:09
采纳率: 55.6%
浏览 39
已结题

java 请问如何把button放在最右边?


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.EventObject;

public class SwingTextFieldView extends JPanel implements ActionListener {
    protected JTextField textField;
    protected JTextArea textArea;
    protected JButton b;
    private final static String newline = "\n";

    public SwingTextFieldView() {
        super(new GridBagLayout());

        b = new JButton("Enter");
        b.addActionListener(this);
        b.setMnemonic(KeyEvent.VK_E);

        add(b);

        textField = new JTextField(20);
        textField.addActionListener(this);

        textArea = new JTextArea(10, 30);
        textArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(textArea);

        GridBagConstraints c = new GridBagConstraints();
        c.gridwidth = GridBagConstraints.REMAINDER;

        c.fill = GridBagConstraints.HORIZONTAL;
        add(textField, c);

        c.fill = GridBagConstraints.BOTH;
        c.weightx = 1.0;
        c.weighty = 1.0;
        add(scrollPane, c);

        JButton b = new JButton("Enter");
    }

    public void actionPerformed(ActionEvent evt) {
        String text = textField.getText();
        if(evt.getSource() == b) {
            textArea.append(text + newline);
            textField.selectAll();
  
            textArea.setCaretPosition(textArea.getDocument().getLength());
        }
    }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("SwingTextFieldView");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(new TextDemo());

        SwingTextFieldView newContenPanw = new SwingTextFieldView();
        newContenPanw.setOpaque(true);
        frame.setContentPane(newContenPanw);
        frame.pack();

        frame.setVisible(true);
    }

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

现在button在最左边,但是我想把它放在最右边 请问要如何解决?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • iilmx 2021-11-09 15:37
    最佳回答

    有个方法可以设置button的坐标点,从而实现button处于哪个位置
    xxx.setBounds(x,y,width,height);

    评论
    解决 1 无用
    打赏 举报

相关推荐 更多相似问题