可拖动的JPanel在编辑时总是跳回中心位置。

huangapple 未分类评论54阅读模式
英文:

dragable JPanel keeps jumping back to center when edited

问题

我有一个带有文本字段的JPaneltextPanel)。出于某些原因我将textPanel添加到另一个面板contentPanel),然后再添加到JFrame中我已经为textPanel添加了一个MouseListener以便我可以拖动它新位置是通过方法调用setLocation...来设置的
每当我开始编辑文本字段时文本面板就会从其实际位置跳回到JFrame的中心- 为什么我需要更改什么

public void run() {
    area1 = new JTextArea();
    area1.setText("Hello!");

    GridBagLayout layout = new GridBagLayout();
    GridBagConstraints cc = new GridBagConstraints();
    cc.fill = GridBagConstraints.NONE;
    textPanel = new JPanel(layout);

    cc.anchor = GridBagConstraints.PAGE_START;
    cc.gridx = 0;
    textPanel.add(area1, cc);

    JPanel contentPanel = new JPanel(new GridBagLayout());
    cc = new GridBagConstraints();
    cc.anchor = GridBagConstraints.FIRST_LINE_START;
    cc.gridx = 0;
    cc.gridy = 0;
    cc.weightx = 1;
    cc.weighty = 1;

    MyMouseAdapter mh = new MyMouseAdapter();
    textPanel.addMouseListener(mh);
    textPanel.addMouseMotionListener(mh);

    contentPanel.add(textPanel, cc);

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    frame.add(contentPanel);
    frame.setSize(800, 600);

    frame.setVisible(true);
}
英文:

I have a JPanel with a textfield (textPanel). I added the textPanel for some reasons to another panel (contentPanel) and that to the JFrame. I have added a MouseListener to the textPanel, so that I can drag it around. The new Position is set by the methodcall setLocation (...)
Everytime I start editing the textfield, the textpanel jumps back from its actual location to the center of the JFrame. – Why? What do I have to change?

public void run() {       
    area1 = new JTextArea();
    area1.setText("Hello!");
    
    GridBagLayout layout = new GridBagLayout();
    GridBagConstraints cc = new GridBagConstraints();
    cc.fill = GridBagConstraints.NONE;       
    textPanel = new JPanel(layout);
    
    cc.anchor = GridBagConstraints.PAGE_START;
    cc.gridx = 0;	
    textPanel.add(area1, cc);
       
    JPanel contentPanel = new JPanel(new GridBagLayout());
    cc = new GridBagConstraints();
    cc.anchor = GridBagConstraints.FIRST_LINE_START;
    cc.gridx = 0; 
    cc.gridy = 0;
    cc.weightx = 1;
    cc.weighty = 1;
    
    MyMouseAdapter mh = new MyMouseAdapter();    
    textPanel.addMouseListener(mh);
    textPanel.addMouseMotionListener(mh);
    
    contentPanel.add(textPanel, cc);
        
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    
    frame.add(contentPanel);
    frame.setSize(800, 600);
    
    frame.setVisible(true);
}

huangapple
  • 本文由 发表于 2020年4月6日 15:58:26
  • 转载请务必保留本文链接:https://java.coder-hub.com/61055311.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定