I have a GUI which has a textarea and a "save button" on it. I want the text that is written in the textarea to be saved when the button is pressed. I have written this code so far:
//Creates textbox
JTextArea text = new JTextArea();
text.setBounds(48, 44, 160, 16); //int (x,y,width,height)
and
//Button
JButton saveButton = new JButton("Save");
saveButton.setBounds(10, 185, 120, 20); //int (x,y,width,height)
And I have also added it to the JPanel. Everything appears as it should, I just don't know how to save the text that is written in the textarea, I have tried googling it, but it seems like there is many ways to do so and I don't know how I can implement it in a simple way that I understand. Thanks.
EDIT: I want to save the data into a string, so I can save it into a database.
You need to add an ActionListener
to your button, and save text inside actionPerformed()
method:
JButton saveButton = new JButton("Save");
saveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String areaText = text.getText();
//saveText(areaText);
}
});
If your text
variable is a local, you need to set it as final
.
Read about ActionListener
.
Also use LayoutManager
instead of setBounds()
, tutorial .
This is will give you a rough idea and you can go ahead
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/yourtablename";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
Connection conn = null;
Statement stmt = null;
JButton saveButton = new JButton("Save");
saveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String areaText = text.getText();
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "insert into your_table_name values("+areaText+")";
ResultSet rs = stmt.executeUpdate(sql);
}
});
If you want to save at database. Than you need to follow these steps.
Here is the sample code of DB connection
Class.forName("com.mysql.jdbc.Driver");// For MySQL
Connection con = DriverManager.getConnection(url,UN, PW);
Here is the sample code of Button ActionListener.
JButton saveButton = new JButton("Save");
saveButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
String areaText = text.getText();
//Execute database insert command to save at Database.
PreparedStatement stmt=con.createPreaparedStatement(
"insert into table_name(col_name) values(?)");
stmt.setString(1, areaText);
stmt.executeUpdate();// To save into DB.
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.