New Button Window and UI Alignment - java

I created a main window where the user will click if he's a system admin, an employee or a member a finance, one of my problem is that they are not centered in the screen, how would I do that? Second, I want it to work like, when I click the Finance Button, the Mainwindow Will close and it will bring me to my log in screen, how would I do that?? Here's my MainWindow Code
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.CardLayout;
import javax.swing.JEditorPane;
import javax.swing.SpringLayout;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JFormattedTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MainWindow extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow frame = new MainWindow();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public MainWindow() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 333, 191);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JButton btnNewButton = new JButton("Employee");
contentPane.add(btnNewButton, BorderLayout.WEST);
JButton btnNewButton_1 = new JButton("Finance");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Login login = new Login();
}
});
contentPane.add(btnNewButton_1, BorderLayout.CENTER);
JButton btnNewButton_2 = new JButton("System Admin");
contentPane.add(btnNewButton_2, BorderLayout.EAST);
JLabel lblNewLabel = new JLabel("Welcome");
contentPane.add(lblNewLabel, BorderLayout.NORTH);
}
}
here is my code for a login form
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class Login extends JFrame {
private JLabel label1, label2;
private JButton submit;
private JTextField textfield1;
private JPasswordField passfield;
private JPanel panel;
public Login() {
setSize(300, 100);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
label1 = new JLabel("User ID:");
textfield1 = new JTextField(15);
label2 = new JLabel("Password:");
passfield = new JPasswordField(15);
submit = new JButton("Submit");
panel = new JPanel(new GridLayout(3, 1));
panel.add(label1);
panel.add(textfield1);
panel.add(label2);
panel.add(passfield);
panel.add(submit);
add(panel, BorderLayout.CENTER);
ButtonHandler handler = new ButtonHandler();
submit.addActionListener(handler);
}// end login constructor
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
String user = textfield1.getText();
char[] passChars = passfield.getPassword();
Connection conn = Jdbc.dbConn();
PreparedStatement ps = null;
ResultSet rs = null;
String pass = new String(passChars);
if (passChars != null) {
String sql = "SELECT employee_ID, employee_password FROM user WHERE employee_ID = ? AND employee_password = ?";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, user);
ps.setString(2, pass);
rs = ps.executeQuery();
if (rs.next()) {
JOptionPane.showMessageDialog(null,"Welcome! "+user);
} else {
JOptionPane.showMessageDialog(null, "Wrong Input");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
rs.close();
ps.close();
conn.close();
} catch (Exception ee) {
ee.printStackTrace();
}
}
}// end actionPerformed
}// End ButtonHandler
}// End of class
}

Some suggestions:
Do not use setBounds() for MainWindow (JFrame). Use some Layout and at end use pack(). If you want to set size manually then you can also use setSize().
To close current window and open Login frame add setVisible(false) or dispose() and create Login object and make it visible.
For making frame to be at center try setLocationRelativeTo(null);.
Do not use variable names like label1, textFiled2, btnNewButton, etc... Use proper names for proper variable that reflects it usage.
Example for point 2:
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
setVisible(false);
Login login = new Login();
}
});

You need to carefully choose a layout manager to suit your needs. You are currently using BorderLayout which doesn't seem to do what you want.
Try adding your three buttons to a JPanel and then setting that panel as your frame's content pane. JPanel uses FlowLayout by default which should do the trick.

Related

How to add a JButton to a JFrame?

I tried to add a button to the JFrame, but it won't appear for some reason. How do I make it appear?
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.BorderFactory;
import java.awt.Color;
import java.awt.Container;
import java.awt.Rectangle;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.*;
public class GraficoconArreglo extends javax.swing.JFrame {
JPanel pan = (JPanel) this.getContentPane();
JLabel []lab = new JLabel[6];
JTextField []text = new JTextField[6];
Border border = BorderFactory.createLineBorder(Color.pink,1);
JButton b = new JButton("Calculate");
public GraficoconArreglo() {
initComponents();
pan.setLayout(null);
pan.setBackground(Color.GRAY);
for(int i=0; i<lab.length ;i++){
lab[i] = new JLabel();
text[i] = new JTextField();
lab[i].setBounds(new Rectangle(15,(i+1)*40, 60, 25));
lab[i].setText("Data " + (i+1));
lab[i].setBorder(border);
text[i].setBounds(new Rectangle(100,(i+1)*40, 60, 25));
pan.add(lab[i],null);
pan.add(text[i],null);
setSize(200,330);
setTitle("Arrays in forums.");
add(b);
b.addActionListener((ActionListener) this);
}
}
You are creating only one button and adding it to 6 different places. Therefore, you only would see it on the last place you added.
You should add the button to the contentPane, not the JFrame. A working code for this, provided from SwingDesigner from Eclipse Marketplace would be:
public class Window extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window frame = new Window();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Window() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
setContentPane(contentPane);
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(170, 110, 89, 23);
contentPane.add(btnNewButton);
}
}

Can't get the buttons to be on the center right position

I'm trying to figure out how to position my buttons in the center right position. I added what Ive done so far and I'll add a drawing of how I want it to be.
I'm trying to understand how to determine the position I want in Swing, can't really understand the advantages of each layout.
My code so far:
package Game;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JToolBar;
import javax.swing.Timer;
public class MainWindow extends JFrame implements ActionListener {
private JButton exit;
private JButton start_Game;
private ImageIcon puzzleBackground;
// private JLabel back_Label;
// private GridBagConstraints grid = new GridBagConstraints();
private JPanel menu;
public MainWindow()
{
super("Welcome");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setSize(450,300);
setLocationRelativeTo(null);
this.setLayout(new FlowLayout(FlowLayout.RIGHT));
menu = new JPanel();
menu.setLayout(new BorderLayout());
//setResizable(false);
//===== Background =====
puzzleBackground = new ImageIcon("MyBackground.jpg");
setContentPane(new JLabel(puzzleBackground));
exit = new JButton("Exit");
menu.add(exit, BorderLayout.CENTER);
exit.addActionListener(this);
start_Game = new JButton("Start to play");
menu.add(start_Game, BorderLayout.SOUTH);
exit.addActionListener(this);
start_Game.addActionListener(this);
//
// back_Label = new JLabel(puzzleBackground);
// back_Label.setLayout(new BorderLayout());
//===== Buttons =====
// back_Label.add(exit,BorderLayout.CENTER);
//
// back_Label.add(start_Game,BorderLayout.EAST);
//
add(menu);
setVisible(true);
}
public static void main(String args[])
{
MainWindow a = new MainWindow();
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == exit)
{
System.exit(0);
}
else
{
//open start up window.
}
}
}
A better way to add a BG image is to use a custom painted JPanel. Then set the layout of the panel and add other panels or components to it. Note that here the buttons are not appearing largely because they are being added to a JLabel.
Here is an alternative that works along the same lines, with the red panel being the panel which custom paints the background image and the menu panel being set to transparent (look for the opaque method).
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.border.*;
public class MainWindow extends JFrame {
private JPanel menu;
private JPanel contentPane = new JPanel(new BorderLayout(4,4));
public MainWindow() {
super("Welcome");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
//setSize(450, 300); // use pack() instead
setContentPane(contentPane);
contentPane.setBorder(new EmptyBorder(8,8,8,8));
contentPane.setBackground(Color.RED);
contentPane.add(new JLabel(new ImageIcon(
new BufferedImage(400,200,BufferedImage.TYPE_INT_RGB))));
menu = new JPanel(new GridLayout(0,1,10,10));
menu.add(new JButton("Exit"), BorderLayout.CENTER);
menu.add(new JButton("Start to play"), BorderLayout.SOUTH);
JPanel menuCenterPanel = new JPanel(new GridBagLayout());
menuCenterPanel.add(menu);
add(menuCenterPanel, BorderLayout.LINE_END);
pack();
setLocationRelativeTo(null); // do AFTER pack()
setMinimumSize(getSize());
setVisible(true);
}
public static void main(String args[]) {
MainWindow a = new MainWindow();
}
}
So, your basic problem boils down the following lines...
this.setLayout(new BorderLayout());
//...
//===== Background =====
puzzleBackground = new ImageIcon("MyBackground.jpg");
setContentPane(new JLabel(puzzleBackground));
Can you tell me what the layout manager in use actually is now? Wrong. The layout manager is now null, because JLabel doesn't actually have a default layout manager.
So, the "simple" answer would be to move the setLayout call to below the setContentPane call, but this would be a short sighted answer, as JLabel calculates it's preferred based on the icon and text properties only, not it's contents of child components.
A better solution would be to do something demonstrated in How to set a background picture in JPanel (see the second example)
This means that if the image is smaller then the required space, the components will disappear off the screen.
I went through and cleaned up the code slightly, only with the intention of getting the layout to work
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainWindow extends JFrame implements ActionListener {
private JButton exit;
private JButton start_Game;
private JPanel menu;
public MainWindow() {
super("Welcome");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
this.setLayout(new BorderLayout());
menu = new JPanel();
menu.setLayout(new GridBagLayout());
exit = new JButton("Exit");
exit.addActionListener(this);
start_Game = new JButton("Start to play");
exit.addActionListener(this);
start_Game.addActionListener(this);
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.fill = gbc.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
menu.add(exit, gbc);
menu.add(start_Game, gbc);
// This is just a filler, it can be removed, but it helps prove the point
add(new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
});
add(menu, BorderLayout.EAST);
pack();
setVisible(true);
}
public static void main(String args[]) {
MainWindow a = new MainWindow();
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == exit) {
System.exit(0);
} else {
//open start up window.
}
}
}
I'd also like to point out that extending directly from JFrame is also short sighted, it's locking you into a single use container and you're not actually adding any new functionality to the class.
Example of better structure...
The following is a simple example of a possibly better structure. It's missing the concept of a "controller", which controls stuff and "model" which maintains the state information which is used by the UI to display "stuff", but gives a starting point
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Main {
public static void main(String args[]) {
new Main();
}
public Main() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Welcome");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new MainPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MainPane extends JPanel {
public MainPane() {
setLayout(new BorderLayout());
// This is just a filler, it can be removed, but it helps prove the point
add(new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
});
add(new MenuPane(), BorderLayout.EAST);
}
}
public class MenuPane extends JPanel {
private JButton exit;
private JButton start_Game;
private JPanel menu;
public MenuPane() {
menu = new JPanel();
menu.setLayout(new GridBagLayout());
ActionHandler actionHandler = new ActionHandler();
exit = new JButton("Exit");
exit.addActionListener(actionHandler);
start_Game = new JButton("Start to play");
start_Game.addActionListener(actionHandler);
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.fill = gbc.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
menu.add(exit, gbc);
menu.add(start_Game, gbc);
}
public class ActionHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == exit) {
System.exit(0);
} else {
//open start up window.
// This should be used to notifiy a controller class
// that some new action needs to take place, the controller
// is then responsible for making it happen
}
}
}
}
}
Doing UI in Java is not advised, but ignoring that.
You get (calculate) the height and width of the screen. Then start drawing buttons depending on that. Drawing a button on screens 50% of pixel value width and 50% of pixel value of height will center the button.
Simply crate buttons with variable location that is calculated from main screen px size and place them where ever you want.

How to make my button do something in a BoxLayout?

I made a BoxLayout GUI and i'm wondering how i'd use an actionlistener to make the button close the window. If I try to put in RegisterNew.setVisible(false); in an actionlistener, it gives me an error
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RegisterNew extends JFrame
{
public RegisterNew(int axis){
// creates the JFrame
super("BoxLayout Demo");
Container con = getContentPane();
con.setLayout(new BoxLayout(con, axis));
con.add(new JLabel("Enter your desired username"));
con.add(new JTextField());
con.add(new JLabel("Enter your password"));
con.add(new JTextField());
con.add(new JButton("Create Account"));
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String args[])
{
RegisterNew newDemo = new RegisterNew(BoxLayout.Y_AXIS);
}
}
I'm also trying to link this to ANOTHER GUI so that when you press a button, this one appears, but it gives me the same error as if i put
RegisterNew.setVisible(true); into the action listener
If that's a subordinate dialog window, then use a JDialog, not a JFrame.
If your ActionListener is an inner class then use RegisterNew.this.close();
Else you can get the window ancestor for the JButton using SwingUtilities.getWindowAncestor(button) and call close() or better dispose() on the Window returned.
Note that BoxLayout and layout managers in general have nothing to do with your current problem.
e.g.,
Test class that shows the new register dialog and that extracts information from it.
import java.awt.BorderLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class TestRegistration extends JPanel {
private JTextArea textArea = new JTextArea(30, 60);
public TestRegistration() {
JPanel bottomPanel = new JPanel();
bottomPanel.add(new JButton(new ShowRegisterNewAction()));
textArea.setFocusable(false);
textArea.setEditable(false);
setLayout(new BorderLayout());
add(new JScrollPane(textArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED));
add(bottomPanel, BorderLayout.PAGE_END);
}
private class ShowRegisterNewAction extends AbstractAction {
private RegisterNew registerNew = null;
public ShowRegisterNewAction() {
super("Show Register New Dialog");
putValue(MNEMONIC_KEY, KeyEvent.VK_S);
}
#Override
public void actionPerformed(ActionEvent e) {
if (registerNew == null) {
JButton btn = (JButton) e.getSource();
Window window = SwingUtilities.getWindowAncestor(btn);
registerNew = new RegisterNew(window, BoxLayout.PAGE_AXIS);
}
registerNew.setVisible(true);
String userName = registerNew.getUserName();
String password = new String(registerNew.getPassword());
textArea.append("User Name: " + userName + "\n");
textArea.append("Password: " + password + "\n");
textArea.append("\n");
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("TestRegistration");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new TestRegistration());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
New Register class that holds the dialog and has code for displaying it and for extracting information from it. Uses BoxLayout.
import java.awt.Container;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
public class RegisterNew {
private JDialog dialog = null;
private JTextField nameField = new JTextField(10);
private JPasswordField passField = new JPasswordField(10);
public RegisterNew(Window window, int axis) {
dialog = new JDialog(window, "Register New", ModalityType.APPLICATION_MODAL);
Container con = dialog.getContentPane();
con.setLayout(new BoxLayout(con, axis));
con.add(new JLabel("Enter your desired username"));
con.add(nameField);
con.add(new JLabel("Enter your password"));
con.add(passField);
con.add(new JButton(new AcceptAction()));
dialog.pack();
dialog.setLocationRelativeTo(window);
}
public char[] getPassword() {
return passField.getPassword();
}
public String getUserName() {
return nameField.getText();
}
public void setVisible(boolean b) {
dialog.setVisible(b);
}
private class AcceptAction extends AbstractAction {
public AcceptAction() {
super("Accept");
putValue(MNEMONIC_KEY, KeyEvent.VK_A);
}
#Override
public void actionPerformed(ActionEvent e) {
dialog.dispose();
}
}
}

Why won't the JButtons, JLabels and JTextFields be displayed?

This code enables an employee to log in to the coffee shop system. I admit I have a lot of unneeded code. My problem is that when I run the program just the image is displayed above and no JButtons, JLabels or JTextFields.
Thanks in advance.
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.ImageIcon;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
public class login extends JFrame {
public void CreateFrame() {
JFrame frame = new JFrame("Welcome");
JPanel panel = new JPanel();
panel.setOpaque(true);
panel.setBackground(Color.WHITE);
panel.setLayout(new BorderLayout(1000,1000));
panel.setLayout(new FlowLayout());
getContentPane().add(panel);
ImagePanel imagePanel = new ImagePanel();
imagePanel.show();
panel.add(imagePanel, BorderLayout.CENTER);
frame.setContentPane(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.add(panel);
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
new login().CreateFrame();
}
});
}
}
class GUI extends JFrame{
private JButton buttonLogin;
private JButton buttonNewUser;
private JLabel iUsername;
private JLabel iPassword;
private JTextField userField;
private JPasswordField passField;
public void createGUI(){
setLayout(new GridBagLayout());
JPanel loginPanel = new JPanel();
loginPanel.setOpaque(false);
loginPanel.setLayout(new GridLayout(3,3,3,3));
iUsername = new JLabel("Username ");
iUsername.setForeground(Color.BLACK);
userField = new JTextField(10);
iPassword = new JLabel("Password ");
iPassword.setForeground(Color.BLACK);
passField = new JPasswordField(10);
buttonLogin = new JButton("Login");
buttonNewUser = new JButton("New User");
loginPanel.add(iUsername);
loginPanel.add(iPassword);
loginPanel.add(userField);
loginPanel.add(passField);
loginPanel.add(buttonLogin);
loginPanel.add(buttonNewUser);
add(loginPanel);
pack();
Writer writer = null;
File check = new File("userPass.txt");
if(check.exists()){
//Checks if the file exists. will not add anything if the file does exist.
}else{
try{
File texting = new File("userPass.txt");
writer = new BufferedWriter(new FileWriter(texting));
writer.write("message");
}catch(IOException e){
e.printStackTrace();
}
}
buttonLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
File file = new File("userPass.txt");
Scanner scan = new Scanner(file);;
String line = null;
FileWriter filewrite = new FileWriter(file, true);
String usertxt = " ";
String passtxt = " ";
String puname = userField.getText();
String ppaswd = passField.getText();
while (scan.hasNext()) {
usertxt = scan.nextLine();
passtxt = scan.nextLine();
}
if(puname.equals(usertxt) && ppaswd.equals(passtxt)) {
MainMenu menu = new MainMenu();
dispose();
}
else if(puname.equals("") && ppaswd.equals("")){
JOptionPane.showMessageDialog(null,"Please insert Username and Password");
}
else {
JOptionPane.showMessageDialog(null,"Wrong Username / Password");
userField.setText("");
passField.setText("");
userField.requestFocus();
}
} catch (IOException d) {
d.printStackTrace();
}
}
});
buttonNewUser.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
NewUser user = new NewUser();
dispose();
}
});
}
}
class ImagePanel extends JPanel{
private BufferedImage image;
public ImagePanel(){
setOpaque(true);
setBorder(BorderFactory.createLineBorder(Color.BLACK,5));
try
{
image = ImageIO.read(new URL("https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcQ8F5S_KK7uelpM5qdQXuaL1r09SS484R3-gLYArOp7Bom-LTYTT8Kjaiw"));
}
catch(Exception e)
{
e.printStackTrace();
}
GUI show = new GUI();
show.createGUI();
}
#Override
public Dimension getPreferredSize(){
return (new Dimension(430, 300));
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(image,0,0,this);
}
}
Seems to me like you have a class login (which is a JFrame, but never used as one). This login class creates a new generic "Welcome" JFrame with the ImagePanel in it. The ImagePanel calls GUI.createGUI() (which creates another JFrame, but doesn't show it) and then does absolutely nothing with it, thus it is immediately lost.
There are way to many JFrames in your code. One should be enough, perhaps two. But you got three: login, gui, and a simple new JFrame().

How can I have a writable text box?

Using pure java, I would like to have a player press a JButton, have a text box pop up which they can type in, and then have a certain action happen when the player presses "Enter".
How could I do this?
I have not yet attempted this because I do not know where to start, however my current code is
package Joehot200;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Image;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import javax.swing.ImageIcon;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
public class Main extends JFrame {
static boolean start = false;
private JPanel contentPane;
/**
* Launch the application.
*/
static Main frame = null;
String version = "0.4";
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new Main();
frame.setVisible(true);
frame.setTitle("Privateers");
} catch (Exception e) {
e.printStackTrace();
}
}
});
TerrainDemo.startGame();
}
boolean cantConnect = false;
/**
* Create the frame.
*/
public Main() {
setExtendedState(JFrame.MAXIMIZED_BOTH);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
final JButton btnEnterBattlefield = new JButton("Enter battlefield!");
btnEnterBattlefield.setForeground(Color.red);
//btnEnterBattlefield.setBackground(Color.green);
//btnEnterBattlefield.setOpaque(true);
menuBar.add(btnEnterBattlefield);
btnEnterBattlefield.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println(new File(System.getProperty("user.dir") + "res/images/heightmap.bmp").getAbsolutePath());
//System.out.println("You clicked the button");
if (cantConnect){
btnEnterBattlefield.setText("Unable to connect to the server!");
}else{
btnEnterBattlefield.setText("Connecting to server...");
}
start = true;
}
});
//JMenu mnLogIn = new JMenu("Log in");
JMenu mnLogIn = new JMenu("Currently useless button");
mnLogIn.setForeground(Color.magenta);
menuBar.add(mnLogIn);
JButton btnLogIntoGame = new JButton("Log into game.");
mnLogIn.add(btnLogIntoGame);
JButton btnRegisterNewAccount = new JButton("Register new account");
mnLogIn.add(btnRegisterNewAccount);
final JButton btnGoToWebsite = new JButton("We currently do not but soon will have a website.");
btnGoToWebsite.setForeground(Color.BLUE);
//btnGoToWebsite = new JButton("Go to website.");
btnGoToWebsite.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("Going to website!");
try {
java.awt.Desktop.getDesktop().browse(new URI("www.endcraft.net/none"));
} catch (Exception e1) {
btnGoToWebsite.setText("Error going to website!");
}
}
});
menuBar.add(btnGoToWebsite);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
FlowLayout flowLayout = (FlowLayout) contentPane.getLayout();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
//contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
ImageIcon icon = new ImageIcon(System.getProperty("user.dir") + "/res/background.png");
Image img = icon.getImage() ;
Image newimg = img.getScaledInstance(this.getWidth()*3, this.getHeight()*3, java.awt.Image.SCALE_SMOOTH ) ;
icon = new ImageIcon( newimg );
JLabel background=new JLabel(icon);
getContentPane().add(background);
background.setLayout(new FlowLayout());
//JProgressBar progressBar = new JProgressBar();
//contentPane.add(progressBar);
//JMenu mnWelcomeToA = new JMenu("Welcome to a pirate game!");
//contentPane.add(mnWelcomeToA);
//JButton btnStartGame = new JButton("Start game");
//mnWelcomeToA.add(btnStartGame);
//JSplitPane splitPane = new JSplitPane();
//mnWelcomeToA.add(splitPane);
//JButton btnRegister = new JButton("Register");
//splitPane.setLeftComponent(btnRegister);
//JButton btnLogin = new JButton("Login");
//splitPane.setRightComponent(btnLogin);
}
}
It is the "Register account" and "Log into game" button that I would like to have the above described action happen on.
Would be great if someone could tell me how to do this.
If you decide to implement a new frame (not best practice), with a new panel, and the JTextField or JTextArea within, you must bind a listener to the button that calls setVisible() on the newly created frame..
For example:
public void actionPerformed(ActionEvent e) {
yourFrame.setVisible(true);
}
Further, you could create the frame everytime the button is clicked, within the actionPerformed method aswell, however this is also not best practice..
A better alternative may be to implement a JOptionPane, see here or here..

Categories