Marcus Robertsson
Marcus Robertsson

Reputation: 3

JButton changing position after updating JTextArea

I am currently working on a project where I am supposed to create a board that contains electronic components such as resistor, leds and capacitors.

I have a main JFrame, which holds all the small JPanels: Centerpanel - Contains the board Rightpanel - Contains the information about selected component

How I imagine it to work is the following:

  1. You choose a component from the JComboBox

    1.1. A component is created via a ComponentFactory

  2. You click somewhere on the centerpanel to add the new component to the board

After that, when you click on the component, information should be shown in the right panel in a JTextArea.

My problem is: Everything works as planned until I click the component the second time, to get the information about the component (shown in the right panel). Then the JButton is resized to a much smaller one and moved to the upper left corner.

This happened when I added the code:

String strBuilder = "Type: " + e.getComponent().getName() + "\n" + 
"ID: " + ((Components) e.getComponent()).getCompID() + "\n";
infoContainer.append(strBuilder);

Complete Code:

public class Framework extends JFrame{
// Declaring variables for the frame
private ComponentFactory cf = new ComponentFactory();
private JToolBar menuToolbar;
private String[] menuItemsString = new String[]{ "newFile", "loadFile", "saveFile" };
private JButton[] menuItems = new JButton[menuItemsString.length];

private JPanel menuPane, centerPane, innerCenter;
private JPanel rightPane;
private JTextArea infoContainer;

private JComboBox<String> componentList;
private final String NOT_SELECTABLE_OPTION = " - Select a component - ";
private String[] componentListStrings = new String[] {"Resistor","LED","Capacitor","Inductor"};
private Components newComponent, selectedComponent;
private boolean componentSelected = false;

private ArrayList<Components> compList = new ArrayList<Components>();

/**
 * Creates a new dispatcher that will listen for keyboard actions on all the selected elements.
 * @author Zovsaman
 */
private class MyDispatcher implements KeyEventDispatcher {
    @Override
    public boolean dispatchKeyEvent(KeyEvent e) {
        if(e.getID() == KeyEvent.KEY_PRESSED){
            if(componentSelected){
                if(e.getKeyCode() == 27){
                    componentSelected = false;
                }

            }
        }
        return false;
    }
}

public Framework(){
    setLayout(new BorderLayout());
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    setSize((int)screenSize.getWidth()/2, (int)screenSize.getHeight()/2);

    // Initiating all the JPanels and stuff
    menuToolbar = new JToolBar(null);
    componentList = new JComboBox<String>();
    centerPane = new JPanel();
    innerCenter = new JPanel();
    rightPane = new JPanel();
    infoContainer = new JTextArea(5, 20);

    // Setting settings and adding buttons to JToolBar at the top of the program
    menuToolbar.setFloatable(false);
    for(int i = 0; i < menuItemsString.length; i++){
        menuItems[i] = new JButton();
        menuItems[i].setName(menuItemsString[i]);
        addIcon(menuItems[i]);
        menuToolbar.add(menuItems[i]);
        if(i < menuItemsString.length){
            // Add spacing to the button menu
            menuToolbar.addSeparator(new Dimension(4, 0));
        }
    }

    // Changing settings on the JComboBox that holds all the different kinds of components
    // Changing the ComboBox to a fixed Size
    componentList.setMaximumSize(new Dimension(200, 24));

    // Adding all the items to JComboBox
    componentList.addItem(NOT_SELECTABLE_OPTION);
    for(int i = 0; i < componentListStrings.length; i++){
        componentList.addItem(componentListStrings[i]);
    }
    // Setting actionListener to listen after changing the JComboBox
    componentList.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e) {
            componentSelected = true;
            newComponent = cf.createComponent((String)componentList.getSelectedItem());
        }
    });

    menuToolbar.add(componentList);

    add(menuToolbar, BorderLayout.NORTH);

    KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
    manager.addKeyEventDispatcher(new MyDispatcher());



    // Creating the center piece
    innerCenter.setLayout(new BoxLayout(innerCenter, EXIT_ON_CLOSE));

    innerCenter.setPreferredSize(new Dimension(700, 400));
    innerCenter.setBackground(Color.LIGHT_GRAY);

    innerCenter.addMouseListener(new MouseAdapter(){
        public void mousePressed(MouseEvent e){ 
            if(newComponent != null){
                Dimension size = newComponent.getPreferredSize();

                newComponent.setBounds(e.getX() - (size.width/2), e.getY() - (size.height/2), size.width, size.height);
                newComponent.setLocation(e.getPoint());

                newComponent.addMouseListener(new MouseAdapter(){
                    public void mousePressed(MouseEvent e){
                        // TODO Update infopanel with info about marked component....
                        String strBuilder = "Type: " + e.getComponent().getName() + "\n" +
                                            "ID: " + ((Components) e.getComponent()).getCompID() + "\n";
                        infoContainer.append(strBuilder);
                    }
                });

                innerCenter.add(newComponent);
                innerCenter.repaint();

                componentSelected = false;
                newComponent = null;
            }
        }
    });
    centerPane.add(innerCenter);
    centerPane.setVisible(true);
    add(centerPane, BorderLayout.CENTER);

    JPanel tempPane = new JPanel();
    tempPane.setLayout(new BoxLayout(tempPane, BoxLayout.PAGE_AXIS));

    // Right pane, info panel
    // rightPane = new JPanel();
    // infoContainer = new JTextArea();
    infoContainer.setBackground(Color.LIGHT_GRAY);
    infoContainer.setVisible(true);

    JLabel tempLabel = new JLabel("Information about component:");
    tempPane.add(tempLabel);
    tempPane.add(infoContainer);
    rightPane.add(tempPane);

    add(rightPane, BorderLayout.EAST);

    setVisible(true);
    pack();
    setDefaultCloseOperation(EXIT_ON_CLOSE);
}

And images that describes what I mean better (First image: Component is put on the board onclick, second image: component is clicked once again to get data from it to show in the right panel)

Adding component:

Adding component

Clicking on it a second time:

Clicking on it a second time

Upvotes: 0

Views: 47

Answers (1)

Kylar
Kylar

Reputation: 9344

You're confusing the Swing layouts. You're setting the panel up with a layoutmanager:

innerCenter.setLayout(new BoxLayout(innerCenter, EXIT_ON_CLOSE));

But then later, you're trying to set the bounds of the components on it as though you're manually placing it:

newComponent.setBounds(e.getX() - (size.width/2), e.getY() - (size.height/2), size.width, size.height);
newComponent.setLocation(e.getPoint());

If you want to manually place it, you need to remove the layout manager from the panel:

innerCenter.setLayout(null);

So that you're telling Swing that you'll set the bounds and location of all it's children manually. Otherwise, the layout manager will try to re-layout everything whenever you add/remove/revalidate/pack the container.

Upvotes: 1

Related Questions