你如何适应JPanel中的所有元素?

时间:2013-02-22 04:20:57

标签: java swing layout-manager

我有两个列表和三个按钮。该列表包含基本形状的元素。当我选择ex“Rect”时,它应该在画布中绘制矩形。现在我已经实现了第二个列表Rectangle。 矩形画得很完美,但我的列表又重复了为什么?以及如何很好地适应他们? 。我在哪里做错了

这是以下代码:

package src;

import javax.swing.*;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;


public class Main implements ActionListener{



    public static void main(String[] args){
        Main gui = new Main();
        gui.go();
    }

    public void go(){
         frame = new JFrame();
         panel = new JPanel();
        String figures[] = {"Rectangle","Rounded Rectangle", "Arc", "Line","Cubic curve"};
         drawing1 = new JList<String>(figures);
         drawing2 = new JList<String>(figures);
         connect_button = new JButton("connect them");

        submit1 = new JButton("Submit figure 1");
        submit2 = new JButton("Submit figure 2");

        connect_button.addActionListener(this);
        submit1.addActionListener(this);
        submit2.addActionListener(this);
        panel.add(drawing2);
        panel.add(drawing1);
        panel.add(connect_button);
        panel.add(submit1);
        panel.add(submit2);

        panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
        panel.setBackground(Color.gray);
        frame.getContentPane().add(BorderLayout.NORTH,panel);
        frame.getContentPane().add(BorderLayout.CENTER,draw);
        frame.setSize(5000,400);
        frame.setVisible(true);
    }

    public void actionPerformed(ActionEvent event){
    if(event.getSource()== submit1){

    }
    else if(event.getSource()== submit2){
        type = drawing1.getSelectedValue();
        draw.repaint();

    }
    else if(event.getSource()== connect_button){

    }



    }
    DrawingPanel draw = new DrawingPanel();
    JPanel panel;
    JFrame frame;
    JButton connect_button;
    JButton submit1;
    JButton submit2;
    JList<String> drawing1;
    JList<String> drawing2;
    String type;

    public class DrawingPanel extends JPanel{
        public void paintComponent(Graphics G){

            Graphics2D g2d = (Graphics2D) G;
            if(type=="Rectangle"){
            Rectangle2D r2d = new Rectangle2D.Float(10f, 10f, 130f, 130f);
            g2d.draw(r2d);
            }

        }

    }
}

点击提交图2之前 http://img152.imageshack.us/img152/4594/capture1ypd.png

点击提交按钮后 http://img46.imageshack.us/img46/854/capture2bk.png

1 个答案:

答案 0 :(得分:1)

您的列表正在重复,因为您自己正在创建两个类似的列表

String figures[] = {"Rectangle","Rounded Rectangle", "Arc", "Line","Cubic curve"};
drawing1 = new JList<String>(figures);
drawing2 = new JList<String>(figures);

这两个列表都传递了相同的figures,所以它们肯定会重复。尝试为每个人提供不同的String[]

希望这有帮助!