英文:
(Fixed)JTable does not add a new row
问题
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class LoginGUI {
// ... (Main class code, excluding imports)
//ActionListener for register
public static class RegisterButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
user = userText.getText();
pass = passwordText.getText();
listUser = new DataUser(user, pass);
array.add(listUser);
System.out.println(array);
success.setText("Registration added!");
}
}
//ActionListener for show list
public static class ShowButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
show.setUser(user);
show.setPass(pass);
show.saveData();
show.setVisible(true);
}
}
}
public class DataUser {
// ... (DataUser class code)
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(breakLine).append(System.getProperty("line.separator"));
return "User: " + user + " | Pass: " + pass + sb.toString();
}
}
import javax.swing.table.DefaultTableModel;
public final class Show extends javax.swing.JFrame {
// ... (Show class code)
public void saveData() {
String data[] = {getUser(), getPass()};
table.addRow(data);
}
// ... (Other methods and variables)
public static void main(String args[]) {
// ... (main method for Show class)
}
}
请注意,我只是将您提供的代码进行了翻译。如果您有任何问题,需要进一步的帮助,或者对翻译后的代码有修改,请随时告诉我。
英文:
My project is to create a small temporary database with users and their passwords, so everything is saved in a second window, which would have a JTable and a button return to the main window. The problem would be precisely in JTable, when registering a new user, it ends up replacing the first user and so on, and a new row is not added with its respective registration.
Main:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.LinkedList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class LoginGUI {
private static JPanel panel;
private static JFrame frame;
private static JLabel userLabel, passwordLabel;
private static JPasswordField passwordText;
private static JTextField userText;
private static JButton buttonRegister, buttonShow;
private static JLabel success;
//This is just for print in the console
private static final LinkedList<DataUser> array = new LinkedList();
private static String user, pass;
private static DataUser listUser;
private static Show show = new Show(); //Problem solved by instantiating this first
public static void main(String[] args) {
//Panel
panel = new JPanel();
frame = new JFrame();
frame.setSize(350, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
panel.setLayout(null);
//User
userLabel = new JLabel("User");
userLabel.setBounds(10, 20, 80, 25);
panel.add(userLabel);
//Password
passwordLabel = new JLabel("Password");
passwordLabel.setBounds(10, 50, 80, 25);
panel.add(passwordLabel);
//Password TextField
passwordText = new JPasswordField();
passwordText.setBounds(100, 50, 165, 25);
panel.add(passwordText);
//User TextField
userText = new JTextField(20);
userText.setBounds(100, 20, 165, 25);
panel.add(userText);
//Register Button
buttonRegister = new JButton("Login");
buttonRegister.setBounds(10, 90, 80, 25);
panel.add(buttonRegister);
RegisterButtonListener registerButtonListener = new RegisterButtonListener();
buttonRegister.addActionListener(registerButtonListener);
//Show list Button
buttonShow = new JButton("Show list");
buttonShow.setBounds(100, 90, 100, 25);
panel.add(buttonShow);
ShowButtonListener showButtonListener = new ShowButtonListener();
buttonShow.addActionListener(showButtonListener);
//Login successful
success = new JLabel("");
success.setBounds(100, 110, 300, 25);
panel.add(success);
//Panel visible
frame.setVisible(true);
}
//ActionListener for register
public static class RegisterButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
user = userText.getText();
pass = passwordText.getText();
listUser = new DataUser(user, pass);
array.add(listUser);
System.out.println(array);
success.setText("Registration added!");
}
}
//ActionListener for show list
public static class ShowButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
//show = new Show();(This was the problem)
show.setUser(user);
show.setPass(pass);
show.saveData();
show.setVisible(true);
}
}
}
DataUser:
public class DataUser {
private final String user;
private final String pass;
private final String breakLine = "";
public DataUser(String user, String pass) {
this.user = user;
this.pass = pass;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(breakLine).append(System.getProperty("line.separator"));
return "User: " + user + " | Pass: " + pass
+ sb.toString();
}
}
And the new JFrame where is the JTable: JTable
Code (Problem is probably in the saveData() method):
import javax.swing.table.DefaultTableModel;
public final class Show extends javax.swing.JFrame {
DefaultTableModel table;
private final String[][] matrix = {};
String head[] = {"User", "Pass"};
private String user, pass;
public Show() {
initComponents();
table = new DefaultTableModel(matrix, head);
jTable.setModel(table);
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public void saveData() { //Problem is probably here
String data[] = {getUser(), getPass()};
table.addRow(data);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jButton1 = new javax.swing.JButton();
jScrollPane2 = new javax.swing.JScrollPane();
jTable = new javax.swing.JTable();
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null}
},
new String [] {
"User", "Pass"
}
));
jScrollPane1.setViewportView(jTable1);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("<- Return");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Title1", "Title2"
}
) {
boolean[] canEdit = new boolean [] {
false, false
};
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane2.setViewportView(jTable);
if (jTable.getColumnModel().getColumnCount() > 0) {
jTable.getColumnModel().getColumn(0).setResizable(false);
jTable.getColumnModel().getColumn(1).setResizable(false);
}
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 275, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
//Return Button
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
dispose();
}
public static void main(String args[]) {
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Show.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Show.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Show.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Show.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(() -> {
new Show().setVisible(true);
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTable jTable;
private javax.swing.JTable jTable1;
// End of variables declaration
}
专注分享java语言的经验与见解,让所有开发者获益!
评论