panels are not showing in frame - java

This was working fine before, but I set the project down for a while and when I decided to take it up again, the panels do not show up in the frame. I have tried many different possible resolutions and spent days trying to fix it with nothing working. Does anyone see what might be causing the frame to display empty?
// imports
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Scanner;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class login extends JFrame {
// create variables
JFrame login = new JFrame();
private JTextField userTF;
private JPasswordField passwordField;
private JLabel userL;
private JLabel passL;
private JLabel updateOne;
private JLabel updateTwo;
private JLabel error;
private JLabel welcome;
private JButton submit;
String password = "";
String username = "";
JPanel panel1 = new JPanel(new GridBagLayout());
JPanel panel2 = new JPanel(new GridBagLayout());
JPanel panel3 = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// constructor
public login(){
// set and add all GUI components
welcome = new JLabel("PLA LOGIN");
c.gridx = 0;
c.gridy = 0;
panel1.add(welcome, c);
userL = new JLabel("Username: ");
c.gridx = 0;
c.gridy = 1;
c.anchor = GridBagConstraints.WEST;
panel2.add(userL, c);
userTF = new JTextField(15);
userTF.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.gray));
userTF.setOpaque(false);
c.gridx = 0;
c.gridy = 2;
panel2.add(userTF, c);
passL = new JLabel("Password: ");
c.gridx = 0;
c.gridy = 3;
panel2.add(passL, c);
passwordField = new JPasswordField(15);
passwordField.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.gray));
passwordField.setOpaque(false);
c.gridx = 0;
c.gridy = 4;
panel2.add(passwordField, c);
submit = new JButton("Sign In");
c.gridx = 0;
c.gridy = 5;
c.insets = new Insets(10, 0, 0, 0); // add top padding
c.ipadx = 93;
panel2.add(submit, c);
updateOne = new JLabel("MySQL JDBC Driver Registered!");
c.gridx = 0;
c.gridy = 4;
panel3.add(updateOne,c );
updateOne.setVisible(false);
updateTwo = new JLabel("You are now connected to your database.");
c.gridx = 1;
c.gridy = 4;
panel3.add(updateTwo);
updateTwo.setVisible(false);
login.add(panel1);
login.add(panel2);
login.add(panel3);
// call text handler constructor to complete correct actions depending on user action
TextHandler handler = new TextHandler();
userTF.addActionListener(handler);
passwordField.addActionListener(handler);
submit.addActionListener(handler);
}
// inner class TextHandler
private class TextHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
// check if user hit to submit with userTF, passwordField, or submit button
if(e.getSource() == userTF){
username = e.getActionCommand();
} else if(e.getSource() == passwordField){
password = e.getActionCommand();
} else if(e.getSource() == submit){
// try to access mysql driver
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException s) {
error = new JLabel("Where is your MySQL JDBC Driver?"); // if driver not found output label
s.printStackTrace();
c.gridx = 0;
c.gridy = 3;
add(error, c);
return;
} // end try
updateOne.setVisible(true); // make label visible
Connection connection = null;
// try to login to mysql database
try {
connection = DriverManager
.getConnection("jdbc:mysql://localhost/PLA", username, password); // fetch username and password
} catch (SQLException s) {
error = new JLabel("Connection Failed! Check output console"); // error if login failed
s.printStackTrace();
c.gridx = 0;
c.gridy = 3;
add(error, c);
return;
} // end try
// if login was successful output label
if (connection != null) {
updateTwo.setVisible(true);
} else {
error = new JLabel("Failed to make connection!"); // if login failed, output label
c.gridx = 0;
c.gridy = 3;
add(error, c);
} // end if
} // end submit else if
} // end action performed
} // end private class text handler } // end class login

I'm not sure if this is you intention, but it's weird to me...
First, you declare a class that extends from JFrame...
public class login extends JFrame {
Then you declare a instance variable of the same class...
JFrame login = new JFrame();
You than add all your components to this instance...
login.add(panel1);
login.add(panel2);
login.add(panel3);
Now, I can't see how you are using this, but I imagine you are doing something like...
login login = new login()
login.setVisible(true);
Which basically, doesn't show anything...
Instead. Rather than extending from JFrame, I would extend from JPanel and drop the login instance variable.
Create a instance of login and then add it to a JFrame instance that you have created...
I also recommend that you take a look at Code Conventions for the Java Programming Language

Related

How to create new and dispose jcomponents multiple times?

(Sorry if this question is not done properly, I'm new. But at least I researched a lot before asking my own question)
Hello. I'm writing a blackjack game in java and it's turning quite massive. My problem is how to handle multiple instances of swing components, I guess you can call it. I can't figure out wether to create the components (such as jpanels and jbuttons) as class level, or in specific methods.
If I create them in their corresponding method, then my action listener can't see them, but if I create them as class level, then they get deleted when I call dispose().
class BlackjackGame extends JFrame implements ActionListener{
public void mainMenu(){
JPanel menuPane = new JPanel(new GridBagLayout()); //Init of main menu
GridBagConstraints c = new GridBagConstraints();
menuPane.setBackground(new Color(125,0,0));
menuPane.setBounds(620,220,175,250);
JLabel menuTitle = new JLabel("Welcome to Blackjack!");//Main menu-content
c.gridx = 1;
c.gridy = 0;
c.insets = new Insets(0,0,20,0);
menuPane.add(menuTitle, c);
JButton playButton = new JButton("Play!");
playButton.addActionListener(this);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 3;
c.ipadx = 25;
c.ipady = 25;
c.insets = new Insets(0,0,0,0);
menuPane.add(playButton, c);
JButton exitButton = new JButton("Exit!");
exitButton.addActionListener(this);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 3;
menuPane.add(exitButton, c);
JButton rulesButton = new JButton("Set rules.");
rulesButton.addActionListener(this);
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 3;
menuPane.add(rulesButton, c);
this.add(menuPane,0);
}
//This is where I get problems
public void actionPerformed (ActionEvent event){
if(event.getSource() == playButton){
//I want the menuPane to disappear, and a transition into the game.
menuPane.dispose();
//Call method for the rest of the game.
}else if(event .getSource() etcetera etcetera){
etcetera etcetera
}
}
}
When done this way, the actionlistener cannot find my components, such as playButton or menuPane. But if I had introduced them as class level objects:
class BlackjackGame extends JFrame implements ActionListener{
JPanel menuPane = new JPanel(new GridBagLayout());
JLabel menuTitle = new JLabel("Welcome to Blackjack!");
JButton playButton = new JButton("Play!");
JButton exitButton = new JButton("Exit!");
JButton rulesButton = new JButton("Set rules.");
public void mainMenu(){
//Rest of code
}
public void actionPerformed(ActionEvent event){
menuPane.dispose();
//Rest of code
}
}
...then as I call menuPane.dispose(), how can I get it back when I want to call mainMenu() again? If I want to go back to the main menu, then I would need to create a new instance of menuPane, as well as all the buttons, but as they are class level and already disposed I can't.
Please help me, and thank you!
PS. I can post my full code as it is atm if it would help.
Edit: Dan's answer has been accepted, as it was indeed the correct answer and it worked for my specific program very well. Thank you and merry christmas!
First, unless I've misunderstood your code, menuPane.dispose() shouldn't work as JPanel does not have a function called dispose()
The best way to do what you want to do if you want to use the same menuPane for the menu. Instead of menuPane.dispose(); use remove(menuPane); and then add(yourOtherPanel);
Working Example
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
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;
#SuppressWarnings("serial")
public class BlackjackGame extends JFrame implements ActionListener {
private JPanel menuPane;
private JLabel menuTitle;
private JButton playButton;
private JButton exitButton;
private JButton rulesButton;
private JPanel otherPane;
private JLabel otherTitle;
private JButton otherButton;
public BlackjackGame() {
mainMenu();
otherPanel();
setSize(400, 400);
setVisible(true);
}
private void mainMenu() {
menuPane = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
menuPane.setBackground(new Color(125,0,0));
menuPane.setBounds(620,220,175,250);
menuTitle = new JLabel("Welcome to Blackjack!");
c.gridx = 1;
c.gridy = 0;
c.insets = new Insets(0,0,20,0);
menuPane.add(menuTitle, c);
playButton = new JButton("Play!");
playButton.addActionListener(this);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 3;
c.ipadx = 25;
c.ipady = 25;
c.insets = new Insets(0,0,0,0);
menuPane.add(playButton, c);
exitButton = new JButton("Exit!");
exitButton.addActionListener(this);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 3;
menuPane.add(exitButton, c);
rulesButton = new JButton("Set rules.");
rulesButton.addActionListener(this);
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 3;
menuPane.add(rulesButton, c);
add(menuPane);
}
private void otherPanel() {
otherPane = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
otherPane.setBackground(new Color(125,0,0));
otherPane.setBounds(620,220,175,250);
otherTitle = new JLabel("Welcome to Second Pane!");
c.gridx = 1;
c.gridy = 0;
c.insets = new Insets(0,0,20,0);
otherPane.add(otherTitle, c);
otherButton = new JButton("Go Back!");
otherButton.addActionListener(this);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 3;
c.ipadx = 25;
c.ipady = 25;
c.insets = new Insets(0,0,0,0);
otherPane.add(otherButton, c);
}
public void actionPerformed (ActionEvent event) {
if(event.getSource() == playButton) {
remove(menuPane);
add(otherPane);
validate();
repaint();
} else if(event.getSource() == otherButton) {
remove(otherPane);
add(menuPane);
validate();
repaint();
}
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new BlackjackGame());
}
}
Edit for comments
So the java method remove() only removes the object from the container, which in this case is the JFrame. This method does not effect the object it moves so the object can be reused later. Hence why in the code above I can just use the remove() and add() methods without redeclaring or remaking menuPane and otherPane.
As for why I declare the objects like this
`private JPanel menuPane;`
And then initialize like this
menuPane = new JPanel(new GridBagLayout());
This is because I want the ActionListener to be able to see the objects without initializing them straight away. The line private JPanel menuPane; makes the object a global variable and the line menuPane = new JPanel(new GridBagLayout()); makes it into what I am going to use. Doing it this way instead of JPanel menuPane = new JPanel(new GridBagLayout()); also means I can reuse the same variable in multiple methods. For example
private JPanel panel;
private void createPanelOne() {
panel = new JPanel(new FlowLayout());
...
add(panel);
}
private void createPanelTwo() {
panel = new JPanel(new GridBagLayout());
...
add(panel);
}
After doing this, you will have two JPanels in your JFrame and they will be different, but you only need to use one JPanel
This is the other way of declaring it and it makes a local variable. Local variables aren't visible to other methods outside of the method you are using unless you pass them through.
JPanel panel = new JPanel();
I wouldn't say this is a con in the slightest. I think sometimes it is good to use local variables in a method that shouldn't be visible to other methods.
Finally to pass local variables through to other methods you can use arguments in a method you have made. For example
public void setSomeValue(int val) {
someValue = val;
}

Cannot access data from another class

my name is Gab.
I'm making a program that will make vanish one page for an other by clicking a button. The thing is, I can't pass the appropriate datas from my two classes. It may sounds weird like this, but here's my code:
My first class (class1):
import javax.swing.*;
import java.awt.*;
import java.util.Scanner;
public class class1 {
public static void main(String[] args) {
JPanel panel = new JPanel();
JFrame frame = new JFrame();
GridBagLayout gridBag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
contenu.setLayout(gridBag);
boolean start = false;
JLabel label1 = new JLabel(
"<html><p><span style = 'font-size: 18px; font-color: blue'>The Number's Genius </span>(version 1.4)</p></html>");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.gridheight = 1;
c.gridwidth = 4;
c.ipadx = 500;
panel.add(label1, c);
JLabel xxx = new JLabel("");
c.gridx = 0;
c.gridy = 4;
c.gridwidth = 3;
c.fill = GridBagConstraints.HORIZONTAL;
c.ipadx = 550;
panel.add(xxx, c);
JButton start = new JButton("<html><p><b>Start</b></p></html>");
c.gridx = 3;
c.gridy = 4;
c.gridwidth = 1;
c.ipadx = 1;
c.anchor = GridBagConstraints.LINE_END;
panel.add(start, c);
JLabel msg1 = new JLabel(
"<html><p style = 'background-color: white; font-size: 10px'>Click on Start to begin.</p></html>");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;
c.gridheight = 3;
c.gridwidth = 4;
panel.add(msg1, c);
JLabel msg2 = new JLabel(
"<html><p style = 'background-color: white; font-size: 10px'>Ok, let's begin.</p><p style = 'background-color: white; font-size: 10px'>First question: Is your number even?</html>");
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;
c.gridheight = 3;
c.gridwidth = 4;
panel.add(msg1, c);
Moteur moteur = new Moteur();
start.addActionListener(moteur);
frame.setContentPane(contenu);
frame.setSize(700, 300);
frame.setVisible(true);
frame.setResizable(false);
}
}
You might notice that the second class has some text in french, but don't worry, it's not important. Here's my second class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Moteur implements ActionListener {
public void actionPerformed(ActionEvent e) {
msg1.setVisible(false);
msg2.setVisible(true);
}
}
In fact, I want the program to make 'msg1' visibility to false and 'msg2' visibility to true, but I can't make the program work because the second class don't know what is 'msg1' and 'msg2'. Please, help me!
Regards, -Gab
For a method to be able to use an object, it needs a reference to this object. You're creating a Moteur instance, but you don't pass any object to this Moteur instance, so it doesn't have a reference to any object except itself.
For the Moteur class to be able to call methods of msg1 and msg2, you need to pass a reference to these two objects to Moteur:
public class Moteur implements ActionListener {
private JLabel messageToHide;
private JLabel messageToShow;
public Moteur(JLabel messageToHide, JLabel messageToShow) {
this.messageToHide = messageToHide;
this.messageToShow = messageToShow;
}
public void actionPerformed(ActionEvent e) {
messageToHide.setVisible(false);
messageToShow.setVisible(true);
}
}
And then, when you create the Moteur, you give them the two labels to hide and show:
Moteur moteur = new Moteur(msg1, msg2);
Use getters and setters for msg's.

JFrame with tabs is not being displayed

I have a problem with my login screen. Somehow it is not being correctly.
All the objects (JLabel,JButton,JTextfield etc.) is not being displayed correctly. This is how it should look:
It only appears once I resize the screen size by pulling at the window border.
The JFrame contains 2 JPanels as tabs. This is the code:
Login.java
package de.immozukunft.windows;
import javax.swing.*;
import de.immozukunft.tabs.LoginTab;
import de.immozukunft.tabs.MySQLConnectionTab;
import java.awt.BorderLayout;
import java.util.Locale;
import java.util.ResourceBundle;
public class Login {
/**The Login class implements the LoginTab and the MySQLConnectionTab
* to verify the user access*/
//String management
static Locale locale = new Locale("de");
static ResourceBundle r = ResourceBundle.getBundle("Strings", locale);
JFrame window = new JFrame();
//Constructor
public Login() {
window.setTitle(r.getString("userlogin"));
frame();
}
//Frame method
private void frame() {
window.setSize(400,250);
window.setLocationRelativeTo(null);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
//Tab-panel
JTabbedPane tabbedPane = new JTabbedPane();
//Tabs
tabbedPane.addTab("Login", new LoginTab(window));
tabbedPane.addTab("MySQL Verbindung", new MySQLConnectionTab()); //TODO Strings einfügen
//Add tab-panel to frame
window.add(tabbedPane, BorderLayout.CENTER);
}
}
LoginTab.java
package de.immozukunft.tabs;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import de.immozukunft.overwrittenClasses.JTextFieldImmo;
import de.immozukunft.persons.UserDetails;
import de.immozukunft.programs.MySQL;
import de.immozukunft.windows.ButtonPanel;
public class LoginTab extends JPanel {
/** LoginTab does the userverfication by
* comparing the entered data with the MySQL-database
* There is no encryption implemented*/
private static final long serialVersionUID = 1L;
//Multilingual String-Management
static Locale locale = new Locale("de");
static ResourceBundle r = ResourceBundle.getBundle("Strings", locale);
// static Connection con = null;
static Statement stnt = null;
static ResultSet rs = null;
//Constructor
public LoginTab(final JFrame window) {
panelMethod(window);
}
// LOGIN ITEMS
JLabel usernameLbl = new JLabel(r.getString("username"));
JLabel passwordLbl = new JLabel(r.getString("password"));
JTextFieldImmo usernameFld = new JTextFieldImmo(15);
JPasswordField passwordFld = new JPasswordField(15);
JButton loginBtn = new JButton(r.getString("login"));
JButton registerUserBtn = new JButton(r.getString("newUser"));
public void panelMethod(final JFrame window) {
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// Insets
c.insets = new Insets(4, 5, 0, 0);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
this.add(usernameLbl, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 0;
this.add(usernameFld, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;
this.add(passwordLbl, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 1;
this.add(passwordFld, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 2;
this.add(loginBtn, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 2;
this.add(registerUserBtn, c);
// Actions Listener
loginBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
MySQL.connect();
String username = usernameFld.getText().trim();
String password = String.valueOf(passwordFld.getPassword()).trim();
String sql = "SELECT username,password from per_user where username = '"
+ username + "'and password = '" + password + "'";
stnt = MySQL.getCon().createStatement();
rs = stnt.executeQuery(sql);
int count = 0;
while (rs.next()) {
count = count + 1;
}
if (count == 1) {
//JOptionPane.showMessageDialog(null, "User Found, Access Granded!"); //TODO String
window.setVisible(false);
window.dispose();
new ButtonPanel();
} else if (count > 1) {
JOptionPane.showMessageDialog(null,
"Duplicate User, Access Denied!"); // TODO String einfügen
} else {
JOptionPane.showMessageDialog(null, r.getString("userNotFound"));
}
} catch (Exception e1) {
JOptionPane.showMessageDialog(null, r.getString("unableToConnectMySQL"));
e1.printStackTrace();
}
}
});
registerUserBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
new UserDetails();
}
});
passwordFld.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
loginBtn.doClick();
}
});
}
}
MySQLConnectionTab.java
package de.immozukunft.tabs;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.swing.*;
import de.immozukunft.overwrittenClasses.JTextFieldImmo;
import de.immozukunft.programs.MySQL;
public class MySQLConnectionTab extends JPanel { //Subclass of Jframe, with ActionListener as interface
/** MySQLConnectionTab is a JPanel which can be implemented
* in other JTabbedPanes in order to change the MySQL connection settings
*/
private static final long serialVersionUID = 1L;
private JButton connectBtn = new JButton(r.getString("connect")); //Connect-Button
private JButton cancelBtn = new JButton(r.getString("cancel")); //Cancel-Button
private JTextFieldImmo hostFld = new JTextFieldImmo(MySQL.getHost(), 20); // Host text field
private JTextFieldImmo usernameFld = new JTextFieldImmo(MySQL.getUsername(), 20); // Username text field
private JTextFieldImmo databaseFld = new JTextFieldImmo(MySQL.getDatabase(), 20); // Database text field
private JTextFieldImmo portFld = new JTextFieldImmo(String.valueOf(MySQL.getPort()), 20); // Port text field
private JPasswordField passwordFld = new JPasswordField(MySQL.getPassword(), 20); // Password text field
private JLabel hostLbl = new JLabel(r.getString("host")); // Host text label
private JLabel usernameLbl = new JLabel(r.getString("username")); // Username text label
private JLabel databaseLbl = new JLabel(r.getString("database")); // Database text label
private JLabel portLbl = new JLabel(r.getString("port")); // Port text label
private JLabel passwordLbl = new JLabel(r.getString("password")); // Password text label
static Locale locale = new Locale("de");
static ResourceBundle r = ResourceBundle.getBundle("Strings", locale);
//Constructor
public MySQLConnectionTab() {
panelMethod();
}
public void panelMethod(){
//Create GridBagConstraints
GridBagConstraints c2 = new GridBagConstraints();
//SetLayout to GridBagLayout
this.setLayout(new GridBagLayout());
//Insets
c2.insets = new Insets(4, 5, 0, 0);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 0;
c2.gridy = 0;
this.add(hostLbl, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 1;
c2.gridy = 0;
this.add(hostFld, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 0;
c2.gridy = 1;
this.add(usernameLbl, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 1;
c2.gridy = 1;
this.add(usernameFld, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 0;
c2.gridy = 2;
this.add(databaseLbl, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 1;
c2.gridy = 2;
this.add(databaseFld, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 0;
c2.gridy = 3;
this.add(portLbl, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 1;
c2.gridy = 3;
this.add(portFld, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 0;
c2.gridy = 4;
this.add(passwordLbl, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 1;
c2.gridy = 4;
this.add(passwordFld, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 1;
c2.gridy = 5;
this.add(connectBtn, c2);
c2.fill = GridBagConstraints.HORIZONTAL;
c2.gridx = 0;
c2.gridy = 5;
this.add(cancelBtn, c2);
connectBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
//All the field data is being set for the MySQL-connection
MySQL.setHost(hostFld.getText());
MySQL.setUsername(usernameFld.getText());
MySQL.setDatabase(databaseFld.getText());
MySQL.setPort(Integer.parseInt(portFld.getText()));
MySQL.setPassword(String.valueOf(passwordFld.getPassword()));
JOptionPane.showMessageDialog(null, String.format("%s", MySQL.getStatus()));
}
}); // Add ActionListener for connect Button
cancelBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
hostFld.setText(MySQL.getHost());
usernameFld.setText(MySQL.getUsername());
databaseFld.setText(MySQL.getDatabase());
portFld.setText(String.valueOf(MySQL.getPort()));
passwordFld.setText(MySQL.getPassword());
}
}); // Add ActionListener for cancel Button
}
}
I am still a beginner.
It's because you are calling setVisible before you add components. Call setVisible after you add components on your JFrame.
Basically:
//Frame method
private void frame() {
//Tab-panel
JTabbedPane tabbedPane = new JTabbedPane();
//Tabs
tabbedPane.addTab("Login", new LoginTab(window));
tabbedPane.addTab("MySQL Verbindung", new MySQLConnectionTab()); //TODO Strings einfügen
//Add tab-panel to frame
window.add(tabbedPane, BorderLayout.CENTER);
//window.setSize(400,250);
window.pack();
window.setLocationRelativeTo(null);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
}
Also, call pack instead of setSize. Size of your JFrame will be based on preferred sizes of components within of JFrame and gaps between those components.

JDBC + Swing: Not able to get table contents

I am learning JDBC, completely new to it. I know MySQL very well. I have a search form in my applet (tab 2), where I search for food. And when I click search, I want it to search for the exact food from the Database and return the table contents of that particular row alone. But I am not getting any result. Only an empty frame opens. But when I put the query as "SELECT * FROM table", I am getting the complete table. But I want only one row, the one that is searched for. Can anyone please tell me where I am going wrong? Here's my code:
import java.awt.*;
import java.awt.event.*;
import java.sql.DriverManager;
import java.util.Vector;
import javax.swing.*;
import com.mysql.jdbc.*;
public class Tryout extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
final Vector columnNames = new Vector();
final Vector data = new Vector();
private JTabbedPane tabbedPane = new JTabbedPane();
private JPanel inputpanel;
private JPanel searchpanel;
public String s;
public Tryout() {
inputpanel = createPage1();
searchpanel = createPage2();
tabbedPane.addTab("Input Form", inputpanel);
tabbedPane.addTab("Search Form", searchpanel);
this.add(tabbedPane, BorderLayout.CENTER);
}
public JPanel createPage1() {
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
//Some code
return panel;
}
public JPanel createPage2() {
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.LINE_START;
c.weightx = 0.5;
c.weighty = 0.5;
JLabel region = new JLabel("Enter Region");
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.gridx = 0;
c.gridy = 0;
panel.add(region, c);
JTextField field = new JTextField(20);
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.gridx = 1;
c.gridy = 0;
panel.add(field, c);
JButton search = new JButton("SEARCH");
c.anchor = GridBagConstraints.FIRST_LINE_START;
c.gridx = 2;
c.gridy = 0;
panel.add(search, c);
s = field.getText();
search.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
try{
Connection con = null;
Class.forName("com.mysql.jdbc.Driver");
con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/delikat", "root", "");
PreparedStatement statement = (PreparedStatement) con.prepareStatement("SELECT * FROM delicious WHERE name = ?");
statement.setString(1,s);
ResultSet rs= (ResultSet) statement.executeQuery();
ResultSetMetaData md = (ResultSetMetaData) rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.addElement( md.getColumnName(i) );
}
while (rs.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
rs.close();
statement.close();
}
catch(Exception e) {}
JFrame tab=new JFrame();
JTable table = new JTable(data, columnNames);
JScrollPane scrollPane = new JScrollPane( table );
tab.add( scrollPane );
tab.setVisible(true);
tab.setSize(300,100);
}
});
return panel;
}
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Tryout ex = new Tryout();
ex.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ex.setSize(500,500);
ex.setVisible(true);
}
});
}
}
Here is my table:
Also, I am trying to display the table in the panel itself below the search form but it gives error when I add
panel.add(scrollpane);
How do I rectify this problem too?
Thanks
What Sudhanshu means is:
PreparedStatement statement = con.preparedStatement("SELECT * FROM delicious WHERE name = ?");
statement.setString(1,s);
ResultSet rs= (ResultSet) statement.executeQuery();
Enclose name is quotes if its of type string (varchar). Better use PreparedStatement in such cases.
Basic debugging. Did you display the value of "s" that is being used in the PreparedStatement?
s = field.getText();
From what I can see, this statement is executed when you build the GUI which means nothing because the user hasn't even entered any text into this text field.
That statement needs to be executed when you actually invoke the SQL.

Update frame or revalidate/repaint panel

How to update a Java frame with changed content?
I want to update a frame or just the panel with updated content. What do I use for this
Here is where I want to revalidate the frame or repaint mainpanel or whatever will work
I have tried a number of things, but none of them have worked.
public void actionPerformed(ActionEvent e) {
//System.out.println(e.getActionCommand());
if (e.getActionCommand().equals("advance")) {
multi--;
// Revalidate update repaint here <<<<<<<<<<<<<<<<<<<
}
else if (e.getActionCommand().equals("reverse")) {
multi++;
// Revalidate update repaint here <<<<<<<<<<<<<<<<<<<
}
else {
openURL(e.getActionCommand());
}
}
Here is the whole java file
/*
*
*
*/
package build;
import java.lang.reflect.Method;
import javax.swing.JOptionPane;
import java.util.Arrays;
import java.util.*;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.AbstractButton;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
/*
* ButtonDemo.java requires the following files:
* images/right.gif
* images/middle.gif
* images/left.gif
*/
public class StockTable extends JPanel
implements ActionListener {
static int multi = 1;
int roll = 0;
static TextVars textvars = new TextVars();
static final String[] browsers = { "firefox", "opera", "konqueror", "epiphany",
"seamonkey", "galeon", "kazehakase", "mozilla", "netscape" };
JFrame frame;
JPanel mainpanel, panel1, panel2, panel3, panel4, panel2left, panel2center, panel2right;
JButton stknames_btn[] = new JButton[textvars.getNumberOfStocks()];
JLabel label[] = new JLabel[textvars.getNumberOfStocks()];
JLabel headlabel, dayspan, namelabel;
JRadioButton radioButton;
JButton button;
JScrollPane scrollpane;
int wid = 825;
public JPanel createContentPane() {
mainpanel = new JPanel();
mainpanel.setPreferredSize(new Dimension(wid, 800));
mainpanel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
panel1 = new JPanel();
panel1.setPreferredSize(new Dimension(wid, 25));
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(0,0,0,0);
mainpanel.add(panel1, c);
// Panel 2------------
panel2 = new JPanel();
panel2.setPreferredSize(new Dimension(wid, 51));
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(0,0,0,0);
mainpanel.add(panel2, c);
panel2left = new JPanel();
panel2left.setPreferredSize(new Dimension(270, 51));
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(0,0,0,0);
panel2.add(panel2left, c);
panel2center = new JPanel();
panel2center.setPreferredSize(new Dimension(258, 51));
c.gridx = 1;
c.gridy = 1;
c.insets = new Insets(0,0,0,0);
panel2.add(panel2center, c);
panel2right = new JPanel();
panel2right.setPreferredSize(new Dimension(270, 51));
c.gridx = 2;
c.gridy = 1;
c.insets = new Insets(0,0,0,0);
panel2.add(panel2right, c);
// ------------------
panel3 = new JPanel();
panel3.setLayout(new GridBagLayout());
scrollpane = new JScrollPane(panel3);
scrollpane.setPreferredSize(new Dimension(wid, 675));
c.gridx = 0;
c.gridy = 2;
c.insets = new Insets(0,0,0,0);
mainpanel.add(scrollpane, c);
ImageIcon leftButtonIcon = createImageIcon("images/right.gif");
//b1 = new JButton("Disable middle button", leftButtonIcon);
//b1.setVerticalTextPosition(AbstractButton.CENTER);
//b1.setHorizontalTextPosition(AbstractButton.LEADING); //aka LEFT, for left-to-right locales
//b1.setMnemonic(KeyEvent.VK_D);
//b1.setActionCommand("disable");
//Listen for actions on buttons 1
//b1.addActionListener(this);
//b1.setToolTipText("Click this button to disable the middle button.");
//Add Components to this container, using the default FlowLayout.
//add(b1);
headlabel = new JLabel("hellorow1");
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(0, 0, 0, 0);
panel1.add(headlabel, c);
radioButton = new JRadioButton("Percentage");
c.gridx = 2;
c.gridy = 0;
c.insets = new Insets(0, 0, 0, 0);
panel1.add(radioButton, c);
radioButton = new JRadioButton("Days Range");
c.gridx = 3;
c.gridy = 0;
c.insets = new Insets(0, 0, 0, 0);
panel1.add(radioButton, c);
radioButton = new JRadioButton("Open / Close");
c.gridx = 4;
c.gridy = 0;
c.insets = new Insets(0, 0, 0,0 );
panel1.add(radioButton, c);
button = new JButton("<<");
button.setPreferredSize(new Dimension(50, 50));
button.setActionCommand("reverse");
button.addActionListener(this);
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(0, 0, 0, 0);
panel2left.add(button, c);
dayspan = new JLabel("hellorow2");
dayspan.setHorizontalAlignment(JLabel.CENTER);
dayspan.setVerticalAlignment(JLabel.CENTER);
dayspan.setPreferredSize(new Dimension(270, 50));
c.gridx = 1;
c.gridy = 1;
c.insets = new Insets(0, 0, 0, 0);
panel2center.add(dayspan, c);
button = new JButton(">>");
button.setPreferredSize(new Dimension(50, 50));
button.setActionCommand("advance");
button.addActionListener(this);
if (multi == 0) {
button.setEnabled(false);
}
else {
button.setEnabled(true);
}
c.gridx = 2;
c.gridy = 1;
c.insets = new Insets(0, 0, 0, 0);
panel2right.add(button, c);
int availSpace_int = textvars.getStocks().size()-textvars.getNumberOfStocks()*7;
ArrayList<String[]> stocknames = textvars.getStockNames();
ArrayList<String[]> stocks = textvars.getStocks();
for (int column = 0; column < 8; column++) {
for (int row = 0; row < textvars.getNumberOfStocks(); row++) {
if (column==0) {
if (row==0) {
namelabel = new JLabel(stocknames.get(0)[0]);
namelabel.setVerticalAlignment(JLabel.CENTER);
namelabel.setHorizontalAlignment(JLabel.CENTER);
namelabel.setPreferredSize(new Dimension(100, 25));
c.gridx = column;
c.gridy = row;
c.insets = new Insets(0, 0, 0, 0);
panel3.add(namelabel, c);
}
else {
stknames_btn[row] = new JButton(stocknames.get(row)[0], leftButtonIcon);
stknames_btn[row].setVerticalTextPosition(AbstractButton.CENTER);
stknames_btn[row].setActionCommand(stocknames.get(row)[1]);
stknames_btn[row].addActionListener(this);
stknames_btn[row].setToolTipText("go to Google Finance "+stocknames.get(row)[0]);
stknames_btn[row].setPreferredSize(new Dimension(100, 25));
c.gridx = column;
c.gridy = row;
c.insets = new Insets(0, 0, 0, 0);
//scrollpane.add(stknames[row], c);
panel3.add(stknames_btn[row], c);
}
}
else {
label[row]= new JLabel(textvars.getStocks().get(columnMulti(multi))[1]);
label[row].setBorder(BorderFactory.createLineBorder(Color.black));
label[row].setVerticalAlignment(JLabel.CENTER);
label[row].setHorizontalAlignment(JLabel.CENTER);
label[row].setPreferredSize(new Dimension(100, 25));
c.gridx = column;
c.gridy = row;
c.insets = new Insets(0,0,0,0);
panel3.add(label[row], c);
}
}
}
return mainpanel;
}
public void actionPerformed(ActionEvent e) {
//System.out.println(e.getActionCommand());
if (e.getActionCommand().equals("advance")) {
multi--;
}
else if (e.getActionCommand().equals("reverse")) {
multi++;
}
else {
openURL(e.getActionCommand());
}
}
/** Returns an ImageIcon, or null if the path was invalid. */
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = StockTable.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
public static void openURL(String url) {
String osName = System.getProperty("os.name");
try {
if (osName.startsWith("Mac OS")) {
Class<?> fileMgr = Class.forName("com.apple.eio.FileManager");
Method openURL = fileMgr.getDeclaredMethod("openURL",
new Class[] {String.class});
openURL.invoke(null, new Object[] {url});
}
else if (osName.startsWith("Windows")) {
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
}
else { //assume Unix or Linux
boolean found = false;
for (String browser : browsers)
if (!found) {
found = Runtime.getRuntime().exec(
new String[] {"which", browser}).waitFor() == 0;
if (found)
Runtime.getRuntime().exec(new String[] {browser, url});
}
if (!found)
throw new Exception(Arrays.toString(browsers));
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(null,
"Error attempting to launch web browser\n" + e.toString());
}
}
int reit = 0;
int start = textvars.getStocks().size()-((textvars.getNumberOfStocks()*5)*7)-1;
public int columnMulti(int multi) {
reit++;
start++;
if (reit == textvars.getNumberOfStocks()) {
reit = 0;
start=start+64;
}
//start = start - (multi*(textvars.getNumberOfStocks()));
return start;
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Stock Table");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
StockTable newContentPane = new StockTable();
//newContentPane.setOpaque(true); //content panes must be opaque
//frame.setContentPane(newContentPane);
frame.setContentPane(newContentPane.createContentPane());
frame.setSize(800, 800);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
The moment you find yourself wanting to "re-create" a UI based on a small change, should raise alarm bells. There are situations when this is going to be a good idea, but in most cases, it's a sign of a bad design.
Let's start with...
frame.setContentPane(newContentPane.createContentPane());
This is a bad idea. You create a JPanel just to create another JPanel. All of sudden, you've not lost context to the UI.
Instead of the createContentPane, simple construct you UI from the constructor of the StockTable pane and add that to the frame...More like...
frame.setContentPane(newContentPane);
Get rid of mainPanel and use the StockTable panel directly.
I can't run your code, but it looks speciously like your trying to "emulate" a table layout. Instead, simplify your life and learn to use JTable. Updating the table more be significantly easier (not to mention look nicer) if you do...
My suggestion is if you want to update a swing component always use the Event Dispatcher Thread.
I think this may helps you
public void actionPerformed(ActionEvent e) {
//System.out.println(e.getActionCommand());
if (e.getActionCommand().equals("advance")) {
multi--;
Runnable edt = new Runnable() {
public void run() {
/*Update your components here*/
}
};
SwingUtilities.invokeLater(edt);
}
else if (e.getActionCommand().equals("reverse")) {
multi++;
Runnable edt= new Runnable() {
public void run() {
/*Update your components here*/
}
};
SwingUtilities.invokeLater(edt);
}
else {
openURL(e.getActionCommand());
}
}
}

Categories