【发布时间】: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 方法中,它迭代这个列表把它们绘制