如何在JPanel上绘制形状,同时将形状与事件控件链接?

时间:2018-12-11 15:00:51

标签: java user-interface

我编写了代码在面板上绘制一个简单的椭圆,然后根据单击的按钮(向左或向右)或箭头按钮,它会相应地移动。我在这里的这段代码似乎并没有使形状显示在黄色背景中。有什么我可以改变的吗?

此外,我还将链接椭圆形到两个单独的键盘和按钮单击事件中。在这里,在鼠标事件上使用KeyAdaptor方法和lambda表达式是一种很好的方法吗?预先谢谢你!

private JButton btnLeftMvmt, btnRightMvmt;

class MyPanel extends JPanel {
public void paintComponent(Graphics g) {
        super.paintComponents(g);
        int width = getWidth()/2;
        int top = (getHeight() - HEIGHT) / 2; 
        /* Code above is a vain attempt to center the oval to the yellow 
        background. 
        Is this correct, as well?*/
        g.fillOval(width, top, 150, 150);
        g.setColor(Color.RED);
    }
}

public MyFrame(){
    setTitle("Red Oval Translator");
    setSize(500, 200);
    setLayout(new BorderLayout());
    JPanel panel1, panel2;

    panel1 = new JPanel();
    panel2 = new JPanel();

    panel1.add(new MyPanel());
    panel1.setBackground(Color.YELLOW);

    btnLeftMvmt = new JButton("Left Translation");
    btnRightMvmt = new JButton("Right Translation");

    panel2.add(btnLeftMvmt);
    panel2.add(btnRightMvmt);

    add(panel1);
    add(panel2, BorderLayout.SOUTH);
    setLocationRelativeTo(null);
    setVisible(true);

2 个答案:

答案 0 :(得分:0)

代码的一个问题是,您应该交换g.fillOval(width, top, 150, 150);g.setColor(Color.RED);的顺序来获得红色的椭圆形而不是默认颜色的椭圆形。

答案 1 :(得分:0)

我认为您想要这样的东西:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

class MyPanel extends JPanel {

    public MyPanel() {
        setPreferredSize(new Dimension(300, 250));
    }

@Override
public void paintComponent(Graphics g) {

        super.paintComponents(g);
        int width = getWidth()/2;
        int top = (getHeight() - HEIGHT) / 2;
        g.setColor(Color.RED); //need to apply color before painting
        g.fillOval(width, top, 150, 150);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(()->new MyFrame());
    }
}

class MyFrame extends JFrame{

    private JButton btnLeftMvmt, btnRightMvmt;

    public MyFrame() {

        setTitle("Red Oval Translator");
        setLayout(new BorderLayout()); //BorderLayout for JFrame
        JPanel panel2 = new JPanel();
        btnLeftMvmt = new JButton("Left Translation");
        btnRightMvmt = new JButton("Right Translation");
        panel2.add(btnLeftMvmt);
        panel2.add(btnRightMvmt);

        add(new MyPanel());
        add(panel2, BorderLayout.SOUTH);
        setLocationRelativeTo(null);
        pack();
        setVisible(true);
    }
}

始终发布mcve