【问题标题】:I'm trying to place multiple paintComponents in a JFrame. [duplicate]我正在尝试将多个paintComponents 放在一个JFrame 中。 [复制]
【发布时间】:2016-02-16 09:03:08
【问题描述】:

按下按钮 1 会在窗格 2 中放置一个框,按下按钮 2 会打开另一个框,但第一个会消失。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class GuiDemo extends JPanel implements ActionListener {
    JFrame pane1 = new JFrame("pane1");
    JFrame pane2 = new JFrame("pane2");
    public  GuiDemo(){

        pane1.setSize(400,400);
        pane1.setLocation(100, 100);
        pane2.setSize(400,400);
        pane2.setLocation(800, 100);
        pane1.setVisible(true);
        pane2.setVisible(true);
        pane1.setLayout(new FlowLayout());
        JButton b1 = new JButton("Button 1");
        JButton b2 = new JButton("Button 2");
        pane1.add(b1);
        pane1.add(b2);
        b1.setVisible(true);
        b1.addActionListener(this);
        b2.setVisible(true);
        b2.addActionListener(this);
    }

    public void actionPerformed(ActionEvent e){
        switch (e.getActionCommand()){
            case "Button 1":{
                placeCircle pc = new placeCircle(0);
                pane2.add(pc);
                pane2.setVisible(true);
                break;}
            case "Button 2":{
                placeCircle pc = new placeCircle(1);
                pane2.add(pc);
                pane2.setVisible(true);
                break;}
        }
    }

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

}

a 作为框 1 和框 2 之间的偏移量传递。

class placeCircle extends JPanel{
    int a;
    public placeCircle(int a){
        this.a = a;

    }
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setColor(Color.BLACK);
        g.drawRect(20+a*100, 20, 20, 20);       
    }

}

但我的主要问题是,我应该使用 painComponent 吗?

【问题讨论】:

  • 请考虑在你的类名中使用首字母大写的驼峰式大小写,因为这是java中的官方naming convention
  • 基本答案是,不要这样做,你是在与布局管理器作斗争。相反,你应该有一个单独的组件/面板,它维护一个需要绘制的对象列表,然后在它的 paintComponent 方法中,它迭代这个列表把它们绘制

标签: java swing


【解决方案1】:

按下按钮 1 会在窗格 2 中放置一个框,按下按钮 2 会打开另一个框,但第一个会消失。

JFrame 的默认布局管理器是 BorderLayout。您正在向 BorderLayout 的 CENTER 添加组件,但一次只能显示一个组件,因此您只能看到最后一个。

我应该使用 painComponent 吗?

是的,但是您的所有绘画都需要在该组件的 paintComponent() 方法中的单个组件中完成。

所以基本上你需要保留一个要绘制的对象列表。然后paintComponent() 方法遍历列表并绘制每个对象。

查看Custom Painting Approaches 中的Draw On Component 示例。有关此方法的示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    相关资源
    最近更新 更多