java - 设置按钮的位置

标签 java

此代码的输出有两个并排放置的按钮。我想更改按钮位置,例如位置在顶部和底部。如何设置按钮的位置。我需要修改这段代码的哪一部分?

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/**
 * Custom Graphics Example: Using key/button to move a line left or right.
*/
@SuppressWarnings("serial")
public class CGMoveALine extends JFrame {
    // Name-constants for the various dimensions
    public static final int CANVAS_WIDTH = 400;
    public static final int CANVAS_HEIGHT = 140;
    public static final Color LINE_COLOR = Color.BLACK;
    public static final Color CANVAS_BACKGROUND = Color.CYAN;

    // The line from (x1, y1) to (x2, y2), initially position at the center
    private int x1 = CANVAS_WIDTH / 2;
    private int y1 = CANVAS_HEIGHT / 8;
    private int x2 = x1;
    private int y2 = CANVAS_HEIGHT / 8 * 7;

    private DrawCanvas canvas; // the custom drawing canvas (extends JPanel)

    **strong text**/** Constructor to set up the GUI */
    public CGMoveALine() {
  // Set up a panel for the buttons
  JPanel btnPanel = new JPanel(new FlowLayout());
  JButton btnLeft = new JButton("Move Left ");
  btnPanel.add(btnLeft);
  btnLeft.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
        x1 -= 10;
        x2 -= 10;
        canvas.repaint();
        requestFocus(); // change the focus to JFrame to receive KeyEvent
     }
  });
  JButton btnRight = new JButton("Move Right");
  btnPanel.add(btnRight);
  btnRight.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
        x1 += 10;
        x2 += 10;
        canvas.repaint();
        requestFocus(); // change the focus to JFrame to receive KeyEvent
     }
  });

  // Set up a custom drawing JPanel
  canvas = new DrawCanvas();
  canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));

  // Add both panels to this JFrame
  Container cp = getContentPane();
  cp.setLayout(new BorderLayout());
  cp.add(canvas, BorderLayout.CENTER);
  cp.add(btnPanel, BorderLayout.SOUTH);

  // "this" JFrame fires KeyEvent
  addKeyListener(new KeyAdapter() {
     @Override
     public void keyPressed(KeyEvent evt) {
        switch(evt.getKeyCode()) {
           case KeyEvent.VK_LEFT:
              x1 -= 10;
              x2 -= 10;
              repaint();
              break;
           case KeyEvent.VK_RIGHT:
              x1 += 10;
              x2 += 10;
              repaint();
              break;
        }
     }
  });

  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Handle the CLOSE button
  setTitle("Move a Line");
  pack();           // pack all the components in the JFrame
  setVisible(true); // show it
  requestFocus();   // set the focus to JFrame to receive KeyEvent
   }

   /**
* DrawCanvas (inner class) is a JPanel used for custom drawing
*/
   class DrawCanvas extends JPanel {
       @Override
        public void paintComponent(Graphics g) {
        super.paintComponent(g);
        setBackground(CANVAS_BACKGROUND);
        g.setColor(LINE_COLOR);
        g.drawLine(x1, y1, x2, y2); // draw the line
        }
   }

   /** The entry main() method */
   public static void main(String[] args) {
      // Run GUI codes on the Event-Dispatcher Thread for thread safety
      SwingUtilities.invokeLater(new Runnable() {
         @Override
         public void run() {
             new CGMoveALine(); // Let the constructor do the job
         }
      });
    }
 }

我想让按钮像这样 position

最佳答案

在本节中:

    **strong text**/** Constructor to set up the GUI */
    public CGMoveALine() {
  // Set up a panel for the buttons
  JPanel btnPanel = new JPanel(new FlowLayout());

按以下方式更改:

  public CGMoveALine() {
  // Set up a panel for the buttons
  JPanel btnPanel = new JPanel(new GridLayout(2,1));

输出:

enter image description here

<小时/>

或者,如果您想要一个按钮在顶部,一个按钮在底部,您可以这样做:

    public CGMoveALine() {
  // Remove button panels
  JButton btnLeft = new JButton("Move Left ");
  btnLeft.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
        x1 -= 10;
        x2 -= 10;
        canvas.repaint();
        requestFocus(); // change the focus to JFrame to receive KeyEvent
     }
  });
  JButton btnRight = new JButton("Move Right");
  btnRight.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
        x1 += 10;
        x2 += 10;
        canvas.repaint();
        requestFocus(); // change the focus to JFrame to receive KeyEvent
     }
  });

  // Set up a custom drawing JPanel
  canvas = new DrawCanvas();
  canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));

  // Add both panels to this JFrame
  Container cp = getContentPane();
  cp.setLayout(new BorderLayout());
  // Manually add a button to top and one to bottom (ie, NORTH and SOUTH)
  cp.add(btnRight, BorderLayout.NORTH);
  cp.add(canvas, BorderLayout.CENTER);
  cp.add(btnLeft, BorderLayout.SOUTH);

输出:

enter image description here

顺便说一句,为什么你有这个:**强文本**/**设置GUI的构造函数*/?此行不正确,会导致编译问题。

使用通常的注释技术://Constructor to setup the GUI而不是这个?

关于java - 设置按钮的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33973914/

相关文章:

java - Neo4j-ogm 中有关闭 Session 的 API 吗?

java - JFreeChart 具有一类和自定义条形位置的条形图

java - 尽管使用paintComponent和动画线程,但使用Java/Swing的动画还是跳跃的

java - 尝试从命令行运行应用程序时出错 : cannot find class

没有 Try 和 Catch 的 Java 代码

java - 我想计算代码将进行的迭代总数

java - 使用 SOAP 的 XSD 和 XSDL 做什么 - Java

java - Springboot的@Value注解找不到Kafka Producer认证的JKS文件位置

Java Plugin升级到3.4版本后SonarQube分析中的java.lang.ClassCastException

java - 将 java 命令转换为 Maven 配置文件时出现问题