Related
got a problem here, trying to create a login to database system at the moment. I have to classes : UserLogManagerMainWindow and DatabaseConnectionFrame. My program is about log management. I want to make a database connection :
UserLogManagerMainWindow class has a button "Connect to database", on it's click DatabaseConnectionFrame initialize and gets up a frame with jlabels and jtextfields, after I enter everything i need, i press "Login" button, after this I want that my UserLogManagerMainWindow class continues on pressenting the logs from connected database.
I have written some code about how it supposed to look : "the logic about what am i trying to say"
connectToDatabaseBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
DatabaseConnectionFrame dcf = new DatabaseConnectionFrame();
dcf.setVisible(true);
if(dcf.answer == true) {
importButtons(menuBar);
setJMenuBar(menuBar);
try {
DatabaseComm.getColumnNamesToPanel(model, titles);
projects = DatabaseComm.AddLogsToArrayReturnProjectNames(events);
DatabaseComm.fillDataToPanel(model, events, titles, row);
DatabaseComm.resizeColumnWidth(table);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else {
System.out.println("not working");
}
}
});
But if statement does not working, i know why. That's why i'm asking how to make it work? More likely, threading is the key, but not good at it at the moment. Any tips without threading? And if threading is the only way, may i get some help of it?
Giving DatabaseConnectionFrame class below either:
package manager;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.SwingConstants;
import javax.swing.JButton;
public class DatabaseConnectionFrame extends JFrame{
private JPanel contentPane;
private JTextField address;
private JPasswordField password;
private JTextField username;
private JButton btnLogin;
private JButton btnCancel;
private JLabel lblPort;
private JTextField port;
public boolean answer = false;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DatabaseConnectionFrame frame = new DatabaseConnectionFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public DatabaseConnectionFrame() {
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setSize(450,250);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
contentPane.setLayout(gbl_contentPane);
JLabel lblDatabaseIpAddress = new JLabel("Database ip address:");
GridBagConstraints gbc_lblDatabaseIpAddress = new GridBagConstraints();
gbc_lblDatabaseIpAddress.anchor = GridBagConstraints.EAST;
gbc_lblDatabaseIpAddress.insets = new Insets(0, 0, 5, 5);
gbc_lblDatabaseIpAddress.gridx = 0;
gbc_lblDatabaseIpAddress.gridy = 0;
contentPane.add(lblDatabaseIpAddress, gbc_lblDatabaseIpAddress);
address = new JTextField();
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.insets = new Insets(0, 0, 5, 0);
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 1;
gbc_textField.gridy = 0;
contentPane.add(address, gbc_textField);
address.setColumns(10);
lblPort = new JLabel("Port");
GridBagConstraints gbc_lblPort = new GridBagConstraints();
gbc_lblPort.anchor = GridBagConstraints.EAST;
gbc_lblPort.insets = new Insets(0, 0, 5, 5);
gbc_lblPort.gridx = 0;
gbc_lblPort.gridy = 1;
contentPane.add(lblPort, gbc_lblPort);
port = new JTextField();
GridBagConstraints gbc_textField1 = new GridBagConstraints();
gbc_textField1.insets = new Insets(0, 0, 5, 0);
gbc_textField1.fill = GridBagConstraints.HORIZONTAL;
gbc_textField1.gridx = 1;
gbc_textField1.gridy = 1;
contentPane.add(port, gbc_textField1);
port.setColumns(10);
JLabel lblUsername = new JLabel("Username:");
lblUsername.setHorizontalAlignment(SwingConstants.CENTER);
GridBagConstraints gbc_lblUsername = new GridBagConstraints();
gbc_lblUsername.anchor = GridBagConstraints.EAST;
gbc_lblUsername.insets = new Insets(0, 0, 5, 5);
gbc_lblUsername.gridx = 0;
gbc_lblUsername.gridy = 2;
contentPane.add(lblUsername, gbc_lblUsername);
username = new JTextField();
GridBagConstraints gbc_textField_1 = new GridBagConstraints();
gbc_textField_1.insets = new Insets(0, 0, 5, 0);
gbc_textField_1.fill = GridBagConstraints.HORIZONTAL;
gbc_textField_1.gridx = 1;
gbc_textField_1.gridy = 2;
contentPane.add(username, gbc_textField_1);
username.setColumns(10);
JLabel lblPassword = new JLabel("Password");
GridBagConstraints gbc_lblPassword = new GridBagConstraints();
gbc_lblPassword.anchor = GridBagConstraints.EAST;
gbc_lblPassword.insets = new Insets(0, 0, 5, 5);
gbc_lblPassword.gridx = 0;
gbc_lblPassword.gridy = 3;
contentPane.add(lblPassword, gbc_lblPassword);
password = new JPasswordField();
GridBagConstraints gbc_passwordField = new GridBagConstraints();
gbc_passwordField.insets = new Insets(0, 0, 5, 0);
gbc_passwordField.fill = GridBagConstraints.HORIZONTAL;
gbc_passwordField.gridx = 1;
gbc_passwordField.gridy = 3;
contentPane.add(password, gbc_passwordField);
btnLogin = new JButton("Login");
GridBagConstraints gbc_btnLogin = new GridBagConstraints();
gbc_btnLogin.insets = new Insets(0, 0, 0, 5);
gbc_btnLogin.gridx = 0;
gbc_btnLogin.gridy = 4;
contentPane.add(btnLogin, gbc_btnLogin);
btnCancel = new JButton("Cancel");
GridBagConstraints gbc_btnCancel = new GridBagConstraints();
gbc_btnCancel.gridx = 1;
gbc_btnCancel.gridy = 4;
contentPane.add(btnCancel, gbc_btnCancel);
btnCancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dispose();
}
});
btnLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String dbAddress = address.getText();
String dbPort = port.getText();
String dbUsername = username.getText();
char[] dbPassword = password.getPassword();
if( dbAddress.isEmpty() || dbPort.isEmpty() || dbUsername.isEmpty() || dbPassword.length == 0) {
JOptionPane.showMessageDialog(getParent(),
"All fields have to be filled!");
}
else {
if(databaseValidation(dbAddress, dbPort, dbUsername, dbPassword)) {
JOptionPane.showMessageDialog(getParent(),
"Connected!");
answer = true;
setVisible(false);
}
else {
JOptionPane.showMessageDialog(getParent(),
"There was error connecting to the database!");
answer = false;
}
}
System.out.println(answer);
}
});
}
public boolean databaseValidation(String address, String port, String username, char[] password) {
String pw = String.valueOf(password);
System.out.println(pw);
try {
Connection con = DriverManager.getConnection("jdbc:mysql://" + address + ":" + port + "/logctrl?user=" + username + "&password=" + pw );
} catch (SQLException e) {
System.out.println("Error connecting to database!");
return false;
}
System.out.println("Connected");
return true;
}
}
If you want to wait for the user input, you have two choices, you either make your own observer pattern which can be called at some point in the future when the state changes in some way or you use a dialog, which will block the codes execution at the point the dialog is made visible and will wait till it's closed
See How to use dialogs for details
import java.awt.Frame;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
JButton btn = new JButton("Show the dialog");
add(btn);
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JDialog dialog = new JDialog((Frame)SwingUtilities.getWindowAncestor(TestPane.this), "I'm in charge now", true);
JButton btn = new JButton("Waiting");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
});
dialog.add(btn);
dialog.pack();
dialog.setLocationRelativeTo(TestPane.this);
dialog.setVisible(true);
JOptionPane.showMessageDialog(TestPane.this, "You won't see this till the dialog is closed");
}
});
}
}
}
I have 2 windows at the moment. After a user clicks on the Submit button, the Main window appears but it appears as such:
The codes are:
LoginForm.java
package interfaceGUI;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginForm extends JFrame{
private JLabel loginEmail;
private JLabel loginPass;
private JTextField loginTextField;
private JPasswordField loginPassField;
private JButton submit;
private JPanel loginArea;
private JPanel buttonArea;
public LoginForm()
{
super("Party Supplies Rental");
setLayout(new FlowLayout());
loginEmail = new JLabel("Enter Your Email Address: ");
loginTextField = new JTextField(20);
loginPass = new JLabel("Enter Your Password: ");
loginPassField = new JPasswordField(20);
loginArea = new JPanel();
loginArea.setLayout(new GridLayout(2,2));
loginArea.add(loginEmail); //add to the JPanel
loginArea.add(loginTextField);
loginArea.add(loginPass);
loginArea.add(loginPassField);
add(loginArea); //add JPanel to the frame
submit = new JButton("Submit");
buttonArea = new JPanel();
buttonArea.setLayout(new GridLayout(1,2));
buttonArea.add(submit);
add(buttonArea);
ButtonHandler handler= new ButtonHandler();
submit.addActionListener(handler);
}
public class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
if(event.getSource() == submit)
{
dispose();
new Main().setVisible(true);
}
}
}
}
And Main.java:
package interfaceGUI;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main extends JFrame{
private JLabel label;
private JPanel forLabel;
private JButton birthdayCategory;
private JButton summerCategory;
private JButton halloweenCategory;
private JPanel forCategory;
public Main()
{
super("Home");
setLayout(new FlowLayout());
label = new JLabel("Choose the Party Category");
forLabel = new JPanel();
forLabel.setLayout(new GridLayout(1,3));
forLabel.add(label);
add(forLabel);
birthdayCategory = new JButton("Birthday Party");
summerCategory = new JButton("Summer/Festive Party");
halloweenCategory = new JButton("Halloween Party");
forCategory = new JPanel();
forCategory.setLayout(new GridLayout(1,3));
forCategory.add(birthdayCategory);
forCategory.add(summerCategory);
forCategory.add(halloweenCategory);
add(forCategory);
}
}
The testMain.java:
package interfaceGUI;
import javax.swing.JFrame;
public class testMain {
public static void main(String[] args) {
Main myFrame = new Main();
myFrame.setSize(300,200); //not working
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}
}
Can anybody suggest me what's wrong? Thanks.
I wouldn't call setSize() but rather would let my components and the layout managers set their own sizes by calling pack(). Occasionally you might want to override a component's getPreferredSize() but if you do so, do it with extreme care.
Calling pack() does seem to work for me with your code:
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TestMain {
private static void createAndShowGui() {
LoginForm loginForm = new LoginForm();
loginForm.pack();
loginForm.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
class LoginForm extends JFrame {
private JLabel loginEmail;
private JLabel loginPass;
private JTextField loginTextField;
private JPasswordField loginPassField;
private JButton submit;
private JPanel loginArea;
private JPanel buttonArea;
public LoginForm() {
super("Party Supplies Rental");
setLayout(new FlowLayout());
loginEmail = new JLabel("Enter Your Email Address: ");
loginTextField = new JTextField(20);
loginPass = new JLabel("Enter Your Password: ");
loginPassField = new JPasswordField(20);
loginArea = new JPanel();
loginArea.setLayout(new GridLayout(2, 2));
loginArea.add(loginEmail); // add to the JPanel
loginArea.add(loginTextField);
loginArea.add(loginPass);
loginArea.add(loginPassField);
add(loginArea); // add JPanel to the frame
submit = new JButton("Submit");
buttonArea = new JPanel();
buttonArea.setLayout(new GridLayout(1, 2));
buttonArea.add(submit);
add(buttonArea);
ButtonHandler handler = new ButtonHandler();
submit.addActionListener(handler);
}
public class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == submit) {
dispose();
Main main = new Main();
main.pack();
main.setVisible(true);
}
}
}
}
class Main extends JFrame {
private JLabel label;
private JPanel forLabel;
private JButton birthdayCategory;
private JButton summerCategory;
private JButton halloweenCategory;
private JPanel forCategory;
public Main() {
super("Home");
setLayout(new FlowLayout());
label = new JLabel("Choose the Party Category");
forLabel = new JPanel();
forLabel.setLayout(new GridLayout(1, 3));
forLabel.add(label);
add(forLabel);
birthdayCategory = new JButton("Birthday Party");
summerCategory = new JButton("Summer/Festive Party");
halloweenCategory = new JButton("Halloween Party");
forCategory = new JPanel();
forCategory.setLayout(new GridLayout(1, 3));
forCategory.add(birthdayCategory);
forCategory.add(summerCategory);
forCategory.add(halloweenCategory);
add(forCategory);
}
}
Note that if this were my project, I'd change it to use a CardLayout to swap views, something like:
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class TestMain2 extends JPanel {
private static final String GUI_NAME = "My GUI";
private CardLayout cardLayout = new CardLayout();
private LoginPanel loginPanel = new LoginPanel();
private HomePanel homePanel = new HomePanel();
public TestMain2() {
setLayout(cardLayout);
add(loginPanel, LoginPanel.NAME);
add(homePanel, HomePanel.NAME);
for (PartyCategory partyCategory : PartyCategory.values()) {
PartyPanel partyPanel = new PartyPanel(partyCategory.getName());
partyPanel.addPropertyChangeListener(PartyPanel.RETURN, new PartyPanelListener());
add(partyPanel, partyCategory.getName());
}
loginPanel.addPropertyChangeListener(LoginPanel.NAME, new LoginPanelListener());
homePanel.addPropertyChangeListener(HomePanel.PARTY_CATEGORY, new HomeListener());
}
private class LoginPanelListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getNewValue() == Boolean.TRUE) {
System.out.println("Submit Pressed");
System.out.println("Login: " + loginPanel.getLogin());
// TODO: Dangerous code!!! Delete this!!!
System.out.println("Password: " + new String(loginPanel.getPassword()));
cardLayout.show(TestMain2.this, HomePanel.NAME);
} else {
System.out.println("Cancel Pressed");
}
}
}
private class HomeListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
PartyCategory partyCategory = (PartyCategory) evt.getNewValue();
cardLayout.show(TestMain2.this, partyCategory.getName());
}
}
private class PartyPanelListener implements PropertyChangeListener {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getNewValue() == Boolean.TRUE) {
cardLayout.show(TestMain2.this, HomePanel.NAME);
}
}
}
private static void createAndShowGui() {
TestMain2 mainPanel = new TestMain2();
JFrame frame = new JFrame(GUI_NAME);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings({"serial", "hiding"})
class LoginPanel extends JPanel {
public static final String NAME = "Login";
private static final int COLS = 10;
private static final String EMAIL_PROMPT = "Enter Your Email Address:";
private static final String PASSWORD_PROMPT = "Enter Your Password:";
private boolean submitPressed = false;
private JTextField textField = new JTextField(COLS);
private JPasswordField passField = new JPasswordField(COLS);
public LoginPanel() {
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 5));
buttonPanel.add(new JButton(new ButtonAction("Submit", KeyEvent.VK_S, true)));
buttonPanel.add(new JButton(new ButtonAction("Cancel", KeyEvent.VK_C, false)));
buttonPanel.add(new JButton(new ExitAction()));
JPanel innerPanel = new JPanel(new GridBagLayout());
innerPanel.setBorder(BorderFactory.createTitledBorder(NAME));
innerPanel.add(new JLabel(EMAIL_PROMPT, JLabel.LEADING), getGbc(0, 0));
innerPanel.add(textField, getGbc(1, 0));
innerPanel.add(new JLabel(PASSWORD_PROMPT, JLabel.LEADING), getGbc(0, 1));
innerPanel.add(passField, getGbc(1, 1));
innerPanel.add(buttonPanel, getGbc(0, 2, 2, 1));
add(innerPanel);
}
public boolean isLoginValid() {
return submitPressed;
}
public void setSubmitPressed(boolean submitPressed) {
this.submitPressed = submitPressed;
firePropertyChange(NAME, null, submitPressed);
}
public String getLogin() {
return textField.getText();
}
public char[] getPassword() {
return passField.getPassword();
}
private class ButtonAction extends AbstractAction {
private boolean submitPressed;
public ButtonAction(String name, int mnemonic, boolean submitPressed) {
super(name);
putValue(MNEMONIC_KEY, mnemonic);
this.submitPressed = submitPressed;
}
#Override
public void actionPerformed(ActionEvent e) {
setSubmitPressed(submitPressed);
}
}
private static GridBagConstraints getGbc(int x, int y, int width, int height) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = width;
gbc.gridheight = height;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
if (x == 1) {
gbc.insets = new Insets(5, 15, 5, 5);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.EAST;
} else {
gbc.insets = new Insets(5, 5, 5, 5);
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.WEST;
}
return gbc;
}
private static GridBagConstraints getGbc(int x, int y) {
return getGbc(x, y, 1, 1);
}
}
#SuppressWarnings({"serial", "hiding"})
class HomePanel extends JPanel {
public static final String NAME = "Home";
public static final String PARTY_CATEGORY = "Party Category";
private static final String PROMPT = "Choose Party Category:";
private PartyCategory partyCategory = null;
public HomePanel() {
JPanel buttonPanel = new JPanel(new GridLayout(1, 0, 5, 5));
for (PartyCategory partyCategory : PartyCategory.values()) {
buttonPanel.add(new JButton(new ButtonListener(partyCategory)));
}
add(new JLabel(PROMPT));
add(buttonPanel);
}
public PartyCategory getPartyCategory() {
return partyCategory;
}
public void setPartyCategory(PartyCategory partyCategory) {
this.partyCategory = partyCategory;
firePropertyChange(PARTY_CATEGORY, null, partyCategory);
}
private class ButtonListener extends AbstractAction {
private PartyCategory partyCategory;
public ButtonListener(PartyCategory partyCategory) {
super(partyCategory.getName());
this.partyCategory = partyCategory;
int mnemonic = partyCategory.getName().charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
#Override
public void actionPerformed(ActionEvent e) {
setPartyCategory(partyCategory);
}
}
}
enum PartyCategory {
BIRTHDAY_PARTY("Birthday Party"),
SUMMER_FESTIVE_PARTY("Summer/Festive Party"),
HALLOWEEN_PARTY("Halloween Party");
private String name;
private PartyCategory(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
#SuppressWarnings("serial")
class PartyPanel extends JPanel {
public static final String RETURN = "return";
private static final int PREF_W = 400;
private static final int PREF_H = PREF_W;
public PartyPanel(String name) {
JLabel label = new JLabel(name, SwingConstants.CENTER);
label.setFont(label.getFont().deriveFont(Font.BOLD, 48f));
JPanel returnButtonPanel = new JPanel();
returnButtonPanel.add(new JButton(new ReturnAction()));
returnButtonPanel.add(new JButton(new ExitAction()));
setLayout(new BorderLayout());
add(label);
add(returnButtonPanel, BorderLayout.PAGE_END);
}
#Override
public Dimension getPreferredSize() {
Dimension superSize = super.getPreferredSize();
if (isPreferredSizeSet()) {
return superSize;
}
int prefW = Math.max(superSize.width, PREF_W);
int prefH = Math.max(superSize.height, PREF_H);
return new Dimension(prefW, prefH);
}
private class ReturnAction extends AbstractAction {
public ReturnAction() {
super("Return Home");
putValue(MNEMONIC_KEY, KeyEvent.VK_R);
}
#Override
public void actionPerformed(ActionEvent e) {
PartyPanel.this.firePropertyChange(RETURN, null, true);
}
}
}
#SuppressWarnings("serial")
class ExitAction extends AbstractAction {
public ExitAction() {
super("Exit");
putValue(MNEMONIC_KEY, KeyEvent.VK_X);
}
#Override
public void actionPerformed(ActionEvent e) {
// this will not work for JMenuItem which would require a test to see if coming
// from a pop up first.
Component source = (Component) e.getSource();
Window win = SwingUtilities.getWindowAncestor(source);
win.dispose();
}
}
So, my problem here is that I want a JPanel on my JFrame to function as a slideshow where 4 different pictures fade in and fade out.
I'm using the Scalr library to resize, everything works except with I use run();
As soon as I use that my window won't open and it get stuck with just the text running through. Is there anyway to make this panel have it's own way? Just sitting in the corner and doing his own thing?
A basic explanation would be lovely because I'm very new with Threads and everything around that.
Thank you!
import javax.imageio.ImageIO;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JSplitPane;
import java.awt.BorderLayout;
import java.awt.GridBagLayout;
import javax.swing.JPanel;
import java.awt.GridBagConstraints;
import javax.swing.JButton;
import javax.swing.JTextField;
import java.awt.Insets;
import javax.swing.JTextArea;
import javax.swing.JList;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.awt.Dimension;
import java.awt.Font;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.ButtonGroup;
import javax.swing.AbstractAction;
import se.lundell.team.Team;
import javax.swing.ListSelectionModel;
import javax.swing.Action;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import org.imgscalr.Scalr;
public class MainWindow {
private JFrame frame;
private JTextField textField;
private final ButtonGroup buttonGroup = new ButtonGroup();
protected DefaultListModel<Team> teamList;
private JList list;
private JTextArea textArea;
private final Action addTeamAction = new AddTeamAction();
private final Action removeTeamAction = new RemoveTeamAction();
private final Action clearListAction = new ClearListAction();
private final Action generateAction = new GenerateAction();
public ArrayList<Team> teamA;
public ArrayList<Team> teamB;
/**
* Create the application.
*/
public MainWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 957, 642);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout(0, 0));
JSplitPane splitPane = new JSplitPane();
frame.getContentPane().add(splitPane, BorderLayout.CENTER);
JPanel leftPanel = new JPanel();
splitPane.setLeftComponent(leftPanel);
GridBagLayout gbl_leftPanel = new GridBagLayout();
gbl_leftPanel.columnWidths = new int[]{0, 0};
gbl_leftPanel.rowHeights = new int[]{0, 0, 41, 66, 0, 0};
gbl_leftPanel.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_leftPanel.rowWeights = new double[]{1.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
leftPanel.setLayout(gbl_leftPanel);
teamList = new DefaultListModel<Team>();
teamList.addElement(new Team("team1"));
teamList.addElement(new Team("team2"));
teamList.addElement(new Team("team3"));
teamList.addElement(new Team("team4"));
list = new JList();
list.setModel(teamList);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
GridBagConstraints gbc_list = new GridBagConstraints();
gbc_list.insets = new Insets(0, 0, 5, 0);
gbc_list.fill = GridBagConstraints.BOTH;
gbc_list.gridx = 0;
gbc_list.gridy = 0;
leftPanel.add(list, gbc_list);
textField = new JTextField();
GridBagConstraints gbc_textField = new GridBagConstraints();
gbc_textField.insets = new Insets(0, 0, 5, 0);
gbc_textField.fill = GridBagConstraints.HORIZONTAL;
gbc_textField.gridx = 0;
gbc_textField.gridy = 1;
leftPanel.add(textField, gbc_textField);
textField.setColumns(10);
JPanel btnPanel = new JPanel();
GridBagConstraints gbc_btnPanel = new GridBagConstraints();
gbc_btnPanel.insets = new Insets(0, 0, 5, 0);
gbc_btnPanel.fill = GridBagConstraints.VERTICAL;
gbc_btnPanel.gridx = 0;
gbc_btnPanel.gridy = 2;
leftPanel.add(btnPanel, gbc_btnPanel);
btnPanel.setLayout(new GridLayout(0, 3, 0, 0));
JButton btnAdd = new JButton("Add");
btnAdd.setAction(addTeamAction);
buttonGroup.add(btnAdd);
btnPanel.add(btnAdd);
JButton btnRemove = new JButton("Remove");
btnRemove.setAction(removeTeamAction);
buttonGroup.add(btnRemove);
btnPanel.add(btnRemove);
JButton btnClear = new JButton("Clear");
btnClear.setAction(clearListAction);
buttonGroup.add(btnClear);
btnPanel.add(btnClear);
JPanel generatePanel = new JPanel();
generatePanel.setPreferredSize(new Dimension(10, 20));
GridBagConstraints gbc_generatePanel = new GridBagConstraints();
gbc_generatePanel.fill = GridBagConstraints.BOTH;
gbc_generatePanel.insets = new Insets(0, 0, 5, 0);
gbc_generatePanel.gridx = 0;
gbc_generatePanel.gridy = 3;
leftPanel.add(generatePanel, gbc_generatePanel);
generatePanel.setLayout(new GridLayout(1, 0, 0, 0));
JButton btnGenerate = new JButton("Generate");
btnGenerate.setAction(generateAction);
btnGenerate.setFont(new Font("Tahoma", Font.PLAIN, 26));
generatePanel.add(btnGenerate);
PictureFrame canvasPanel = new PictureFrame();
GridBagConstraints gbc_canvasPanel = new GridBagConstraints();
gbc_canvasPanel.fill = GridBagConstraints.BOTH;
gbc_canvasPanel.gridx = 0;
gbc_canvasPanel.gridy = 4;
leftPanel.add(canvasPanel, gbc_canvasPanel);
JPanel rightPanel = new JPanel();
splitPane.setRightComponent(rightPanel);
rightPanel.setLayout(new BorderLayout(0, 0));
textArea = new JTextArea();
textArea.setEditable(false);
textArea.setAlignmentY(Component.BOTTOM_ALIGNMENT);
textArea.setAlignmentX(Component.LEFT_ALIGNMENT);
rightPanel.add(textArea, BorderLayout.CENTER);
JMenuBar menuBar = new JMenuBar();
frame.getContentPane().add(menuBar, BorderLayout.NORTH);
JMenu mnMenu = new JMenu("Menu");
menuBar.add(mnMenu);
JMenuItem mntmLoad = new JMenuItem("Load");
mnMenu.add(mntmLoad);
JMenuItem mntmSave = new JMenuItem("Save");
mnMenu.add(mntmSave);
JMenuItem mntmExit = new JMenuItem("Exit");
mnMenu.add(mntmExit);
frame.setVisible(true);
}
protected JList getList() {
return list;
}
private class AddTeamAction extends AbstractAction {
public AddTeamAction() {
putValue(NAME, "Add");
putValue(SHORT_DESCRIPTION, "Add team to list.");
}
public void actionPerformed(ActionEvent e) {
if(!textField.getText().isEmpty()) {
teamList.addElement(new Team(textField.getText()));
textField.setText("");
} else {
JOptionPane.showMessageDialog(null, "You need to enter a name.", "Error!", JOptionPane.ERROR_MESSAGE);
}
}
}
private class RemoveTeamAction extends AbstractAction {
public RemoveTeamAction() {
putValue(NAME, "Remove");
putValue(SHORT_DESCRIPTION, "Remove the selected team.");
}
public void actionPerformed(ActionEvent e) {
int choice = getList().getSelectedIndex();
teamList.removeElementAt(choice);
}
}
private class ClearListAction extends AbstractAction {
public ClearListAction() {
putValue(NAME, "Clear");
putValue(SHORT_DESCRIPTION, "Clear the list and the tournament window");
}
public void actionPerformed(ActionEvent e) {
teamList.clear();
textArea.setText("");
teamA.clear();
teamB.clear();
}
}
private class GenerateAction extends AbstractAction {
public GenerateAction() {
putValue(NAME, "Generate");
putValue(SHORT_DESCRIPTION, "Generate a new Round Robin tournament.");
teamA = new ArrayList<Team>();
teamB = new ArrayList<Team>();
}
public void actionPerformed(ActionEvent e) {
rotateSchedual();
}
private void rotateSchedual(){
if(teamList.getSize() % 2 == 0) {
start();
} else {
teamList.addElement(new Team("Dummy"));
start();
}
}
protected void start() {
for(int i = 0; i < teamList.getSize(); i++) {
teamA.add(teamList.getElementAt(i));
}
// Split the arrayList to two and invert.
splitSchedual();
int length = teamA.size();
System.out.println(teamB.size());
System.out.println(length);
printSchedual(length);
//remove index 0 from teamA and add index 0 from teamB first in the list. then add the first team back in again.
for(int i = 0;i <= (length - 1); i++){
//copy index 0 and add it to the other array.
//remove index 0 in both arrays.
teamA.add(1, teamB.get(0));
teamB.remove(0);
teamB.add(teamA.get(length));
teamA.remove(length);
printSchedual(length);
}
}
//Splits the array in to two arrays.
protected void splitSchedual(){
int length = teamA.size();
for(int i = (length/2);i < (length);i++){
teamB.add(teamA.get(i));
}
for(int i = (length - 1);i >= (length/2); i--) {
teamA.remove(i);
}
}
protected void printSchedual(int length){
int rounds = length;
for(int i = 0; i < (rounds - 1); i++){
textArea.append((i+1) + ". " + teamA.get(i).getTeamname() + " - " + teamB.get(i).getTeamname() + "\n");
}
textArea.append("-----------------------------\n");
}
}
public class PictureFrame extends JPanel implements Runnable {
Runnable run;
Image[] imageArray = new Image[4];
Image resized;
public PictureFrame() {
setVisible(true);
try {
imageArray[0] = ImageIO.read(new File(getClass().getResource("/se/lundell/assets/TrophyTheChampion.gif").getFile()));
imageArray[1] = ImageIO.read(new File(getClass().getResource("/se/lundell/assets/trophy.gif").getFile()));
imageArray[2] = ImageIO.read(new File(getClass().getResource("/se/lundell/assets/trophy1.gif").getFile()));
imageArray[3] = ImageIO.read(new File(getClass().getResource("/se/lundell/assets/nicolas_cage.jpg").getFile()));
} catch (IOException e) {
e.printStackTrace();
}
resized = Scalr.resize((BufferedImage)imageArray[0], 190, 190);
}
#Override
public void run() {
System.out.println("körs bara en gång.");
while(true) {
System.out.println("This will print, over and over again.");
for(int i = 0; i < imageArray.length; i++) {
resized = Scalr.resize((BufferedImage)imageArray[i], 190, 190);
repaint();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
#Override
public void paint(Graphics g) {
g.drawImage(resized, 30, 0, null);
}
}
}
Guys I have a problem with my JTable, my JTable(tblLivro) which contents should be the result(ArrayList) of my query (working) , but when I try to put the rsult in my jtable it just doesn't work, it doesn't show any errors, yet not show it. Why?
Here is my code
package view;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import model.Livro;
import control.LivroControl;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.table.DefaultTableModel;
public class LivroView extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JLabel lblIdLivro, lblLombada, lblTitulo, lblTituloInternacional, lblEdicao, lblEditora, lblAutor ;
private JTextField txtIdLivro, txtTombo, txtTitulo, txtTituloInternacional, txtEdicao, txtEditora, txtAutor;
private JButton btnAdicionar, btnPesquisar, btnExcluir;
private JPanel painelPrincipal, painelGeral, painelBotoes, painelJPanel;
private JTable tblLivros;
private List<Livro> encontrados;
DefaultTableModel modelo;
public LivroView() {
super("Manutenção de Livros");
encontrados = new ArrayList<Livro>();
lblIdLivro = new JLabel("Código do livro:");
lblLombada = new JLabel("Tombo:");
lblTitulo = new JLabel("Título:");
lblTituloInternacional = new JLabel("Título Internacional:");
lblEdicao = new JLabel("Edição:");
lblEditora = new JLabel("Editora:");
lblAutor = new JLabel("Autor:");
txtIdLivro = new JTextField(20);
txtTombo= new JTextField("Tombo");
txtTitulo = new JTextField(20);
txtTituloInternacional= new JTextField(20);
txtEdicao = new JTextField(20);
txtEditora= new JTextField(20);
txtAutor= new JTextField("Autor");
txtIdLivro.setText("");
txtTombo.setText("");
txtTitulo.setText("");
txtTituloInternacional.setText("");
txtEdicao.setText("");
txtEditora.setText("");
txtAutor.setText("");
btnAdicionar = new JButton("Adicionar");
btnExcluir = new JButton("Excluir");
btnPesquisar = new JButton("Pesquisar");
btnAdicionar.addActionListener(this);
btnPesquisar.addActionListener(this);
btnExcluir.addActionListener(this);
painelPrincipal = new JPanel();
painelGeral = new JPanel();
painelBotoes = new JPanel();
painelJPanel = new JPanel();
painelPrincipal.setLayout(new BorderLayout());
painelGeral.setLayout(new GridLayout(7,2));
painelBotoes.setLayout(new GridLayout(2,1));
painelGeral.add(lblIdLivro);
painelGeral.add(txtIdLivro);
painelGeral.add(lblLombada);
painelGeral.add(txtTombo);
painelGeral.add(lblTitulo);
painelGeral.add(txtTitulo);
painelGeral.add(lblTituloInternacional);
painelGeral.add(txtTituloInternacional);
painelGeral.add(lblEdicao);
painelGeral.add(txtEdicao);
painelGeral.add(lblEditora);
painelGeral.add(txtEditora);
painelGeral.add(lblAutor);
painelGeral.add(txtAutor);
painelBotoes.add(btnAdicionar);
painelBotoes.add(btnPesquisar);
painelBotoes.add(btnExcluir);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(55, 80, 359, 235);
painelJPanel.add(scrollPane);
tblLivros = new JTable();
tblLivros.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"Tombo", "T\u00EDtulo", "T\u00EDtulo Internacional", "Edi\u00E7\u00E3o", "Autor", "Editora"
}
));
modelo = new DefaultTableModel();
tblLivros.getColumnModel().getColumn(0).setPreferredWidth(54);
tblLivros.getColumnModel().getColumn(1).setPreferredWidth(104);
tblLivros.getColumnModel().getColumn(2).setPreferredWidth(136);
tblLivros.getColumnModel().getColumn(4).setPreferredWidth(102);
// modelo = (DefaultTableModel) tblLivros.getModel();
scrollPane.setViewportView(tblLivros);
painelJPanel.setLayout(null);
painelPrincipal.add(painelGeral, BorderLayout.NORTH);
painelPrincipal.add(painelBotoes, BorderLayout.CENTER);
this.setSize(500,300);
this.setVisible(true);
this.setContentPane(painelPrincipal);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
LivroControl control = new LivroControl();
if ("Adicionar".equalsIgnoreCase(cmd)){
boolean adicionado = false;
adicionado = control.adicionarLivro(txtIdLivro.getText(), txtTitulo.getText(), txtTituloInternacional.getText(), txtTombo.getText(), txtAutor.getText(), txtEdicao.getText(), txtEditora.getText());
if (adicionado == true){
txtIdLivro.setText("");
txtTombo.setText("");
txtTitulo.setText("");
txtTituloInternacional.setText("");
txtEdicao.setText("");
txtEditora.setText("");
txtAutor.setText("");
txtIdLivro.requestFocus();
}
}
else if("Excluir".equalsIgnoreCase(cmd)){
control.excluirLivro(txtTombo.getText());
txtTombo.setText("");
}
else if("Pesquisar".equalsIgnoreCase(cmd)){
if (!txtTombo.getText().equals("")){
Livro l = control.pesquisarLivroPorTombo(txtTombo.getText());
if (l!=null){
txtIdLivro.setText(String.valueOf(l.getIdLivro()));
txtTombo.setText(l.getTombo());
txtTitulo.setText(l.getTitulo());
txtTituloInternacional.setText(l.getTituloInternacional());
txtEdicao.setText(l.getEdicao());
txtEditora.setText(l.getEditora());
txtAutor.setText(l.getAutor());
}
}
else if (!txtAutor.getText().equals("")){
encontrados = control.pesquisarLivroPorAutor(txtAutor.getText());
if (encontrados!= null){
for (Livro dados : encontrados){
Object[] objetoTombo = new Object[1];
Object[] objetoTitulo = new Object[2];
Object[] objetoTituloInternacional = new Object[3];
Object[] objetoEdicao = new Object[4];
Object[] objetoAutor = new Object[5];
Object[] objetoEditora = new Object[6];
objetoTombo[0] = dados.getTombo();
objetoTitulo[0] = dados.getTitulo();
objetoTituloInternacional[0] = dados.getTituloInternacional();
objetoEdicao[0] = dados.getEdicao();
objetoAutor[0]= dados.getAutor();
objetoEditora[0]= dados.getEditora();
//modelo.setNumRows(0);
modelo.addRow(objetoTombo);
modelo.addRow(objetoTitulo);
modelo.addRow(objetoTituloInternacional);
modelo.addRow(objetoEdicao);
modelo.addRow(objetoAutor);
modelo.addRow(objetoEditora);
}
this.setSize(700,500);
tblLivros.setModel(modelo);
painelJPanel.add(tblLivros);
painelJPanel.setVisible(true);
painelJPanel.repaint();
painelPrincipal.add(painelJPanel, BorderLayout.SOUTH);
painelPrincipal.repaint();
}
}
else {
encontrados = control.pesquisarLivroPorNome(txtTitulo.getText());
if (encontrados!= null){
}
}
}
}
public static void main(String[] args) {
new LivroView();
}
}
Thank you!
Because you didn't even added JScrollPane on your painelPrincipal. You can do it like this:
painelPrincipal.add(scrollPane, BorderLayout.SOUTH);
Also:
Do not call setVisible for JFrame before all components are added.
Call pack instead of setSize for JFrame
Avoid using null layout and absolute positioning.
Regards and good luck!
EDIT:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LivroView extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JLabel lblIdLivro, lblLombada, lblTitulo, lblTituloInternacional, lblEdicao, lblEditora, lblAutor ;
private JTextField txtIdLivro, txtTombo, txtTitulo, txtTituloInternacional, txtEdicao, txtEditora, txtAutor;
private JButton btnAdicionar, btnPesquisar, btnExcluir;
private JPanel painelPrincipal, painelGeral, painelBotoes, painelJPanel;
private JTable tblLivros;
DefaultTableModel modelo;
public LivroView() {
super("Manutenção de Livros");
lblIdLivro = new JLabel("Código do livro:");
lblLombada = new JLabel("Tombo:");
lblTitulo = new JLabel("Título:");
lblTituloInternacional = new JLabel("Título Internacional:");
lblEdicao = new JLabel("Edição:");
lblEditora = new JLabel("Editora:");
lblAutor = new JLabel("Autor:");
txtIdLivro = new JTextField(20);
txtTombo= new JTextField("Tombo");
txtTitulo = new JTextField(20);
txtTituloInternacional= new JTextField(20);
txtEdicao = new JTextField(20);
txtEditora= new JTextField(20);
txtAutor= new JTextField("Autor");
txtIdLivro.setText("");
txtTombo.setText("");
txtTitulo.setText("");
txtTituloInternacional.setText("");
txtEdicao.setText("");
txtEditora.setText("");
txtAutor.setText("");
btnAdicionar = new JButton("Adicionar");
btnExcluir = new JButton("Excluir");
btnPesquisar = new JButton("Pesquisar");
btnAdicionar.addActionListener(this);
btnPesquisar.addActionListener(this);
btnExcluir.addActionListener(this);
painelPrincipal = new JPanel();
painelGeral = new JPanel();
painelBotoes = new JPanel();
painelJPanel = new JPanel();
painelPrincipal.setLayout(new BorderLayout());
painelGeral.setLayout(new GridLayout(7,2));
painelBotoes.setLayout(new GridLayout(2,1));
painelGeral.add(lblIdLivro);
painelGeral.add(txtIdLivro);
painelGeral.add(lblLombada);
painelGeral.add(txtTombo);
painelGeral.add(lblTitulo);
painelGeral.add(txtTitulo);
painelGeral.add(lblTituloInternacional);
painelGeral.add(txtTituloInternacional);
painelGeral.add(lblEdicao);
painelGeral.add(txtEdicao);
painelGeral.add(lblEditora);
painelGeral.add(txtEditora);
painelGeral.add(lblAutor);
painelGeral.add(txtAutor);
painelBotoes.add(btnAdicionar);
painelBotoes.add(btnPesquisar);
painelBotoes.add(btnExcluir);
tblLivros = new JTable();
tblLivros.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"Tombo", "T\u00EDtulo", "T\u00EDtulo Internacional", "Edi\u00E7\u00E3o", "Autor", "Editora"
}
));
JScrollPane scrollPane = new JScrollPane(tblLivros);
painelPrincipal.add(painelGeral, BorderLayout.NORTH);
painelPrincipal.add(painelBotoes, BorderLayout.CENTER);
painelPrincipal.add(scrollPane, BorderLayout.SOUTH);
this.setContentPane(painelPrincipal);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if ("Adicionar".equalsIgnoreCase(cmd)){
boolean adicionado = false;
if (adicionado == true){
txtIdLivro.setText("");
txtTombo.setText("");
txtTitulo.setText("");
txtTituloInternacional.setText("");
txtEdicao.setText("");
txtEditora.setText("");
txtAutor.setText("");
txtIdLivro.requestFocus();
}
}
else if("Excluir".equalsIgnoreCase(cmd)){
txtTombo.setText("");
}
else if("Pesquisar".equalsIgnoreCase(cmd)){
if (!txtTombo.getText().equals("")){
}
else if (!txtAutor.getText().equals("")){
} }
}
public static void main(String[] args) {
new LivroView();
}
}
Ok, here is your code. Altough I had to remove some pieces of code to make it functional.
First of all, stop using null layouts. Swing was designed to be used with layout managers.
You add the table to the scroll pane which is a good thing.
scrollPane.setViewportView(tblLivros);
Later on it looks like you update the model (which is a good thing), but then you add the table to another panel (which is a bad thing). This removes the table from the scrollpane. The table will no longer have a header unless the table is displayed in a scrollpane. All you need to do is invoke the setModel() method and the table will automatically repaint itself.
tblLivros.setModel(modelo);
//painelJPanel.add(tblLivros);
//painelJPanel.setVisible(true);
//painelJPanel.repaint();
//painelPrincipal.add(painelJPanel, BorderLayout.SOUTH);
If you ever do need to add a component to a visible GUI then the code should be:
panel.add(..)
panel.revalidate();
panel.repaint();
just got help from a friend, here is the final code:
public class LivroView extends JFrame implements ActionListener {
private JTable tblLivros;
DefaultTableModel modeloTabela;
private List<Livro> encontrados;
public LivroView() {
super("Manutenção de Livros");
encontrados = new ArrayList<Livro>();
modeloTabela = new DefaultTableModel(
new String[] {
"Tombo", "Título", "Título Internacional", "Edição", "Autor", "Editora"
}, 0);
tblLivros = new JTable(modeloTabela);
tblLivros.getColumnModel().getColumn(0).setPreferredWidth(54);
tblLivros.getColumnModel().getColumn(1).setPreferredWidth(104);
tblLivros.getColumnModel().getColumn(2).setPreferredWidth(136);
tblLivros.getColumnModel().getColumn(4).setPreferredWidth(102);
painelTabela = new JScrollPane(tblLivros);
painelTabela.setVisible(false);
painelPrincipal.add(painelGeral, BorderLayout.NORTH);
painelPrincipal.add(painelBotoes, BorderLayout.CENTER);
painelPrincipal.add(painelTabela, BorderLayout.SOUTH);
//this.setSize(500,300);
this.setContentPane(painelPrincipal);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
LivroControl control = new LivroControl();
if ("Adicionar".equalsIgnoreCase(cmd)){
}
else if("Excluir".equalsIgnoreCase(cmd)){
}
else if("Pesquisar".equalsIgnoreCase(cmd)){
if (!txtTombo.getText().equals("")){
Livro l = control.pesquisarLivroPorTombo(txtTombo.getText());
if (l!=null){
txtIdLivro.setText(String.valueOf(l.getIdLivro()));
txtTombo.setText(l.getTombo());
txtTitulo.setText(l.getTitulo());
txtTituloInternacional.setText(l.getTituloInternacional());
txtEdicao.setText(l.getEdicao());
txtEditora.setText(l.getEditora());
txtAutor.setText(l.getAutor());
}
}
else if (!txtAutor.getText().equals("")){
encontrados = control.pesquisarLivroPorAutor(txtAutor.getText());
if (encontrados!= null){
for (Livro dados : encontrados){
Object[] row = new Object[6];
row[0] = dados.getTombo();
row[1] = dados.getTitulo();
row[2] = dados.getTituloInternacional();
row[3] = dados.getEdicao();
row[4]= dados.getAutor();
row[5]= dados.getEditora();
modeloTabela.addRow(row);
}
painelTabela.setVisible(true);
painelPrincipal.repaint();
this.pack();
}
}
else {
//the same
}
}
}
public static void main(String[] args) {
new LivroView();
}
}
Thank you so much for the help!
I have a problem here. I create program to add data to the table and sort it when i press the button. when i press the sort button once, it isn't wrong. but when i press again it is wrong. so why? please help me.
this is the code.
Nama Class
public class Nama {
private String nama;
private int index;
public Nama(String n,int i){
nama=n;index=i;
}
void setData(String n,int i){
nama=n;index=i;
}
String nama(){
return nama;
}
int ind(){
return index;
}
public String toString(){
return(String.format("%s %d", nama,index));
}
}
MergeSort Class
import java.util.*;
public class MergeSortS{
public void merge_sort(int low,int high,Nama [] a){
int mid;
if(low<high) {
mid=(low+high)/2;
merge_sort(low,mid,a);
merge_sort(mid+1,high, a);
merge(low,mid,high,a);
}
}
public void merge(int low,int mid,int high,Nama [] a){
int h,i,j,k;
Nama b[]=new Nama[50];
h=low;
i=low;
j=mid+1;
while((h<=mid)&&(j<=high)){
if(a[h].nama().compareToIgnoreCase(a[j].nama())<0){
b[i]=a[h];
h++;
}
else{
b[i]=a[j];
j++;
}
i++;
}
if(h>mid){
for(k=j;k<=high;k++){
b[i]=a[k];
i++;
}
}
else{
for(k=h;k<=mid;k++){
b[i]=a[k];
i++;
}
}
for(k=low;k<=high;k++) a[k]=b[k];
}
public MergeSortS() {
}
}
Panel Class
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
/**
*
* #author Kareem
*/
public class Panel extends JPanel implements ActionListener{
JTable table;
JTextField tf1,tf2,tf3,tf4;
JButton b1,b2,b3,b4,b5,b6,b7;
Vector rows,columns,temp;
DefaultTableModel tabModel;
String[]data = new String[3];
String [] column = {"Nama", "Nim", "IP"};
Nama[] n,nim,ip;
MergeSortS mS;
int c=0,index=0;
public Panel(){
this.setBounds(0,0,1280, 800);
this.setLayout(null);
inaTf();
inaTab();
inaBut();
n= new Nama[50];
nim= new Nama[50];
ip= new Nama[50];
mS= new MergeSortS();
this.setVisible(true);
}
public void inaTab(){
rows=new Vector();
columns= new Vector();
temp= new Vector();
addColumns(column);
tabModel=new DefaultTableModel();
tabModel.setDataVector(rows,columns);
table = new JTable(tabModel);
table.setPreferredScrollableViewportSize(new
Dimension(500, 70));
table.setFillsViewportHeight(true);
table.setBounds(100,100,200,200);
JScrollPane scroll = new JScrollPane(table);
scroll.setBounds(50,50,400,400);
add(scroll);
}
public void inaBut(){
b1=new JButton("add Row");
b1.setBounds(50,600,90,25);
add(b1);
b1.addActionListener(this);
b2=new JButton("Delete Row");
b2.setBounds(170,600,90,25);
add(b2);
b2.addActionListener(this);
b3=new JButton("SortName");
b3.setBounds(290,600,120,25);
add(b3);
b3.addActionListener(this);
b5=new JButton("SortNim");
b5.setBounds(290,650,120,25);
add(b5);
b5.addActionListener(this);
b6=new JButton("SortIP");
b6.setBounds(290,700,120,25);
add(b6);
b6.addActionListener(this);
b4=new JButton("RESET");
b4.setBounds(170,650,90,25);
add(b4);
b4.addActionListener(this);
}
public void inaTf(){
tf1=new JTextField();
tf1.setBounds(640,50,90,25);
add(tf1);
JLabel l1= new JLabel("Nama \t: ");
l1.setBounds(530,50,90,25);
add(l1);
tf2=new JTextField();
tf2.setBounds(640,80,90,25);
add(tf2);
JLabel l2= new JLabel("Nim : ");
l2.setBounds(530,80,90,25);
add(l2);
tf3=new JTextField();
tf3.setBounds(640,110,90,25);
add(tf3);
JLabel l3= new JLabel("IPK : ");
l3.setBounds(530,110,90,25);
add(l3);
tf4=new JTextField();
tf4.setBounds(640,140,90,25);
add(tf4);
JLabel l4= new JLabel("Hapus Baris ke ");
l4.setBounds(530,140,120,25);
add(l4);
}
public void addRow()
{
Vector r;
r = createBlankElement();
rows.addElement(r);
table.addNotify();
}
public void addRow(String [] data)
{
Vector r=new Vector();
r = isi(data);
rows.addElement(r);
table.addNotify();
}
public Vector createBlankElement()
{
Vector t = new Vector();
t.addElement((String) " ");
t.addElement((String) " ");
t.addElement((String) " ");
return t;
}
public Vector isi(String[] data) {
Vector t = new Vector();
for(int j=0;j<3;j++){
t.addElement((String) data[j]);
}
return t;
}
public void addColumns(String[] colName) {
for(int i=0;i<colName.length;i++)
columns.addElement((String) colName[i]);
}
void deleteRow(int index) {
if(index!=-1) {
rows.removeElementAt(index);
table.addNotify();
}
}
#Override
public void actionPerformed(ActionEvent e) {
try{
if(e.getSource()==b1){
data[0]=tf1.getText()+" "+index;
n[index]=new Nama(data[0],index);
data[1]=tf2.getText();
nim[index]=new Nama(data[1],index);
data[2]=tf3.getText()+rows.size();
ip[index]=new Nama (data[2],index);
c=c+1;
index=index+1;
addRow(data);
}
if(e.getSource()==b2){
int i;
i=Integer.parseInt(tf4.getText());
deleteRow(i);
// for(;i<rows.size();i++){
// n[i]=n[i+1];
// }
}
if(e.getSource()==b3){
mS.merge_sort(0, rows.size()-1, n);
temp.setSize(rows.size());
for(int i=0;i<index;i++){
temp.set(i, rows.get(n[i].ind()));
}
for(int i=0;i<index;i++){
rows.set(i, temp.get(i));
}
}
if(e.getSource()==b4){
rows.setSize(0);
temp.setSize(0);
for(int i=0;i<index;i++)n[i]=null;
index=0;
}
if(e.getSource()==b5){
mS.merge_sort(0, rows.size()-1, nim);
temp.setSize(rows.size());
for(int i=0;i<rows.size();i++){
temp.set(i, rows.get(nim[i].ind()));
}
for(int i=0;i<rows.size();i++){
rows.set(i, temp.get(i));
}
}
if(e.getSource()==b6){
mS.merge_sort(0, rows.size()-1, ip);
temp.setSize(rows.size());
for(int i=0;i<rows.size();i++){
temp.add(i, rows.get(ip[i].ind()));
}
for(int i=0;i<rows.size();i++){
rows.set(i, temp.get(i));
}
}
repaint();
}
catch (Throwable t){
JOptionPane.showMessageDialog(null, "AAAAAA");
}
}
}
Frame Class
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
/**
*
* #author Kareem
*/
public class Frame extends JFrame {
public Frame(){
super("Penghitung Gaji");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(null);
this.setSize(1280, 800);
this.getContentPane().add(new Panel());
this.setVisible(true);
}
public static void main(String[] args) {
Frame frame = new Frame();
}
}
Thanks. And Sorry for my bad english.
No where do you actually tell the TableModel that it's contents have changed...
Now, the thing that weirds me out, is you are keeping a Vector of the rows outside of the model...
mS.merge_sort(0, rows.size()-1, n);
temp.setSize(rows.size());
for(int i=0;i<index;i++){
temp.set(i, rows.get(n[i].ind()));
}
for(int i=0;i<index;i++){
rows.set(i, temp.get(i)); // This is doing nothing...
}
Once the data has been handed to the table model, you should not be interacting with it, unless you are willing to notify the table model of the changes.
Personally, I would simply use the inbuilt sorting capabilities of the JTable
ps- I would also, strongly, encourage you to learn how to use layout managers, they will save your sanity in the long run
Dashing through the snow
In a one-horse open sleigh
O'er the fields we go
Laughing all the way
Bells on bobtail ring'
Making spirits bright
What fun it is to ride and sing
A sleighing song tonight!
Jingle bells, jingle bells,
Jingle all the way.
Oh! what fun it is to ride
In a one-horse open sleigh.
Jingle bells, jingle bells, ....
song singing from code, please to apologize me if isn't this one your favorite song
can't comment or suggesting, excluding used LayoutManager in my code, I walked the path of least resistance, my endless lazyness
.
.
.
from code
.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.RowSorter.SortKey;
import javax.swing.ScrollPaneConstants;
import javax.swing.SortOrder;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;
public class MyFrame {
private JFrame frame = new JFrame();
private JTable table;
private JPanel buttonPanel = new JPanel();
private JPanel buttonPanelSouth = new JPanel();
private JPanel textFieldPanel = new JPanel();
private JPanel northPanel = new JPanel();
private JPanel centerPanel = new JPanel();
private JLabel l1, l2, l3, l4;
private JTextField tf1, tf2, tf3, tf4;
private JButton b1, b2, b3, b4, b5, b6, b7;
private String[] columnNames = {"Nama", "Nim", "IP", "Hapus Baris ke"};
private Object[][] data = {
{"igor", "B01_125-358", "1.124.01.125", true},
{"lenka", "B21_002-242", "21.124.01.002", true},
{"peter", "B99_001-358", "99.124.01.001", false},
{"zuza", "B12_100-242", "12.124.01.100", true},
{"jozo", "BUS_011-358", "99.124.01.011", false},
{"nora", "B09_154-358", "9.124.01.154", false},
{"xantipa", "B01_001-358", "1.124.01.001", false},};
private DefaultTableModel model = new DefaultTableModel(data, columnNames) {
private static final long serialVersionUID = 1L;
#Override
public boolean isCellEditable(int row, int column) {
switch (column) {
case 3:
return true;
default:
return false;
}
}
#Override
public Class getColumnClass(int column) {
return getValueAt(0, column).getClass();
}
};
public MyFrame() {
table = new JTable(model);
table.setAutoCreateRowSorter(true);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
table.setFillsViewportHeight(true);
table.getSelectionModel().setSelectionMode(
ListSelectionModel.SINGLE_SELECTION);
DefaultTableCellRenderer stringRenderer =
(DefaultTableCellRenderer) table.getDefaultRenderer(String.class);
stringRenderer.setHorizontalAlignment(SwingConstants.CENTER);
JScrollPane pane = new JScrollPane(table,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
centerPanel.setLayout(new BorderLayout(10, 10));
centerPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
centerPanel.add(pane);
centerPanel.add(pane);
//
b1 = new JButton("add Row");
b1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
model.addRow(new Object[]{(tf1.getText()).trim(),
(tf2.getText()).trim(), (tf3.getText()).trim(), true});
}
});
b2 = new JButton("Delete Row");
b2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int rowToDelete = 0;
int rowToModel = 0;
if (table.getSelectedRow() > -1) {
rowToDelete = table.getSelectedRow();
rowToModel = table.convertRowIndexToModel(rowToDelete);
model.removeRow(rowToModel);
}
}
});
b3 = new JButton("RESET");
b3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
table.getRowSorter().setSortKeys(null);
}
});
b4 = new JButton("SortName");
b4.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
table.getRowSorter().toggleSortOrder(0);
}
});
b5 = new JButton("SortNim");
b5.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
TableRowSorter rowSorter = (TableRowSorter) table.getRowSorter();
List<SortKey> sortKeys = new ArrayList<SortKey>();
SortKey sortKey = new SortKey(1, SortOrder.ASCENDING);
sortKeys.add(sortKey);
rowSorter.setSortKeys(sortKeys);
rowSorter.sort();
}
});
b6 = new JButton("SortIP");
b6.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
TableRowSorter rowSorter = (TableRowSorter) table.getRowSorter();
List<SortKey> sortKeys = new ArrayList<SortKey>();
SortKey sortKey = new SortKey(2, SortOrder.DESCENDING);
sortKeys.add(sortKey);
SortKey sortKey1 = new SortKey(1, SortOrder.ASCENDING);
sortKeys.add(sortKey1);
SortKey sortKey2 = new SortKey(0, SortOrder.UNSORTED);
sortKeys.add(sortKey2);
rowSorter.setSortKeys(sortKeys);
rowSorter.sort();
}
});
b7 = new JButton("SortIP");
buttonPanel.setLayout(new GridLayout(1, 0, 50, 0));
buttonPanel.setBorder(new EmptyBorder(2, 10, 2, 10));
buttonPanel.add(b1);
buttonPanel.add(b2);
//
buttonPanelSouth.setLayout(new GridLayout(1, 4, 5, 5));
buttonPanelSouth.add(b3);
buttonPanelSouth.add(b7);
b7.setVisible(false);
buttonPanelSouth.add(b4);
buttonPanelSouth.add(b5);
buttonPanelSouth.add(b6);
centerPanel.add(buttonPanelSouth, BorderLayout.SOUTH);
//
l1 = new JLabel("Nama : ", JLabel.RIGHT);
tf1 = new JTextField();
l2 = new JLabel("Nim : ", JLabel.RIGHT);
tf2 = new JTextField();
l3 = new JLabel("IPK : ", JLabel.RIGHT);
tf3 = new JTextField();
l4 = new JLabel("Hapus Baris ke :", JLabel.RIGHT);
tf4 = new JTextField();
textFieldPanel.setLayout(new GridLayout(4, 2, 10, 10));
textFieldPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
textFieldPanel.add(l1);
textFieldPanel.add(tf1);
textFieldPanel.add(l2);
textFieldPanel.add(tf2);
textFieldPanel.add(l3);
textFieldPanel.add(tf3);
textFieldPanel.add(l4);
textFieldPanel.add(tf4);
//
northPanel.setLayout(new BorderLayout());
northPanel.add(textFieldPanel);
northPanel.add(buttonPanel, BorderLayout.SOUTH);
//
frame.add(northPanel, BorderLayout.NORTH);
frame.add(centerPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] arg) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MyFrame myFrame = new MyFrame();
}
});
}
}