当前位置: 动力学知识库 > 问答 > 编程问答 >

java - How to exit JFrame and keep data in the same positions?

问题描述:

package dragbutton_test;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class DragButton_test extends JButton{

private int draggedAtX, draggedAtY;

public DragButton_test(String text){

super(text);

setDoubleBuffered(false);

addMouseListener(new MouseAdapter() {

@Override

public void mousePressed(MouseEvent e){

draggedAtX = e.getX();

draggedAtY = e.getY();

}

});

addMouseMotionListener(new MouseMotionAdapter(){

@Override

public void mouseDragged(MouseEvent e){

setLocation(e.getX() - draggedAtX + getLocation().x,

e.getY() - draggedAtY + getLocation().y);

}

});

}

public static void main(String[] args) {

JFrame frame = new JFrame();

JButton button = new JButton("Save");

button.setBounds(300, 480, 75, 25);

frame.add(button);

DragButton_test one = new DragButton_test("Michael");

one.setBounds(0, 10, 85, 25);

frame.getContentPane().add(one);

DragButton_test two = new DragButton_test("Bob");

two.setBounds(0, 40, 85, 25);

frame.getContentPane().add(two);

DragButton_test three = new DragButton_test("Joe");

three.setBounds(0, 70, 85, 25);

frame.getContentPane().add(three);

frame.setResizable(false);

frame.setLayout(null);

frame.getContentPane();

frame.setSize(700, 600);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setLocationRelativeTo(null);

frame.setVisible(true);

}

}

I need the save button in the JFrame to save where the user

last moved the buttons. So every time the program is run, the

buttons are in the same coordinates as before

I am not sure if this is possible however it would be amazing if you could fix it

}

网友答案:

There are many ways to do it. Using an ObjectOutputSteam and ObjectInputStream is my personal favorite. This tutorial explains how to use them.

Or you can also simply write and read from a text file. Though I doubt it's as efficient.

Good luck coding.

分享给朋友:
您可能感兴趣的文章:
随机阅读: