Can someone please tell me why the Timer is trying to Convert an int into a String. Here is the error that keeps coming up.
CurrentTimePrinter.java:48: error: incompatible types: int cannot be
converted to String
time = new Timer(1000,listener);
CurrentTimePrinter.java:49: error: cannot find symbol
time.start();
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.Date;
import java.util.Timer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.BorderLayout;
public class CurrentTimePrinter extends JFrame
{
private JButton Exitbutton;
private JTextField textField;
private static final int FIELD_WIDTH = 10;
private static final int FRAME_WIDTH = 600;
private static final int FRAME_HEIGHT = 400;
private ActionListener listener;
public Timer time;
public CurrentTimePrinter()
{
//listener = new CtpListener();
createComponents();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
public void createComponents()
{
Color orange = new Color(255,165,0);
Font font = new Font("Times New Roman", Font.BOLD, 14);
textField = new JTextField(FIELD_WIDTH);
Exitbutton = new JButton("EXIT");
class CtpListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
textField.setText("" + new Date());
Date now = new Date();
System.out.println(now);
}
}
ActionListener listener = new CtpListener();
time = new Timer(1000,listener);
time.start();
Exitbutton.setFont(font);
Exitbutton.setForeground(Color.BLACK);
ExitButtonListener exitListener = new ExitButtonListener();
Exitbutton.addActionListener(exitListener);
JPanel panel1 = new JPanel();
time = new Timer(1000, listener);
time.start();
JPanel panel2 = new JPanel();
panel1.setBackground(orange);
panel1.add(Exitbutton);
panel2.add(textField);
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.add(panel1, BorderLayout.SOUTH);
contentPane.add(panel2, BorderLayout.CENTER);
setContentPane(contentPane);
}
class ExitButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);
}
}
public static void main(String[] args)
{
JFrame frame = new CurrentTimePrinter();
frame.setTitle("Current Time");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
You are using java.util.Timer. You want javax.swing.Timer here.
Replace that in the imports, it should be:
import javax.swing.Timer;
Related
I am trying to make a menu class for a small game I'm making, and it all works fine, except now, the KeyListener does not work at all, I tried applying it to JFrame and JPanel, but nothing is working...
Here is my MainClass:
package bombermangame;
import javax.swing.JFrame;
public class MainClass {
public static int WIDTH = 870, HEIGHT = 800;
public static JFrame frame = new JFrame();
public static Menu menu = new Menu();
public static void main(String[] args) {
frame.setContentPane(menu);
frame.pack();
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("BomberMan V0.3");
frame.setSize(WIDTH, HEIGHT);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
`
And here is my Menu class:
package bombermangame;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JButton;
import javax.swing.JPanel;
public class Menu extends JPanel implements ActionListener {
private static final long serialVersionUID = 1L;
private JButton startButton = new JButton("Play");
private int x = 0, y = 500;
private boolean down = false;
private boolean up = true;
private Timer timer = new Timer();
public Menu() {
setBackground(Color.blue);
startButton = new JButton("Start");
startButton.setBounds(0,0, 100, 40);
startButton.setPreferredSize(new Dimension(100, 40));
startButton.addActionListener(this);
startButton.setFocusPainted(true);
add(startButton);
}
public void actionPerformed(ActionEvent ae) {
Object a = ae.getSource();
Game game = new Game();
Listener keys = new Listener();
if (a == startButton) {
timer.cancel();
MainClass.frame.remove(MainClass.menu);
MainClass.frame.setContentPane(game);
MainClass.frame.addKeyListener(keys);
game.addKeyListener(keys);
game.setBackground(Color.BLACK);
game.setDoubleBuffered(true);
game.setBounds(0, 0, WIDTH, HEIGHT);
Game.running = true;
}
}
}
I am trying to add the buttons to the centerPanel that I created, then add that panel to the main center borderlayout. for some reason though my tab will not repaint anymore. It worked fine a while ago when I had the DrawFieldsListener class in the same class file as the MagicSquare, but nothing in the code has changed from my splitting them into two class files. So i really don't know what is going on. When it did repaint before, it would also take a long time. Any help? thanks!
All source for the project is on GitHub if it is easier to read and understand there: https://github.com/andrefecto/Academic-Convivium-Project
MagicSquare Class:
package magicSquare;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class MagicSquare extends JPanel {
JLabel sizeLabel = new JLabel("Enter A Square Size: ");
JButton setSize;
static JButton calculate;
static JButton reset;
static JTextField squareSize;
static JTextField field;
public static ArrayList<JTextField> inputFields = new ArrayList<JTextField>();
public static ArrayList<Integer> inputs = new ArrayList<Integer>();
public static ArrayList<Integer> totals = new ArrayList<Integer>();
public static int squared = 0;
public static int square = 0;
public static JPanel centerPanel = new JPanel();
public static JPanel bottomPanel = new JPanel();
public MagicSquare (){
setLayout(new BorderLayout());
JPanel subPanel = new JPanel();
subPanel.add(sizeLabel);
squareSize = new JTextField();
squareSize.setColumns(6);
subPanel.add(squareSize);
setSize = new JButton("Enter");
subPanel.add(setSize);
setSize.addActionListener(new DrawFieldsListener());
add(subPanel, BorderLayout.NORTH);
add(new DrawFieldsListener(), BorderLayout.CENTER);
}
}
my DrawFieldsListener class:
package magicSquare;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
class DrawFieldsListener extends JPanel implements ActionListener {
int square = MagicSquare.square;
int squared = MagicSquare.squared;
JPanel centerPanel = MagicSquare.centerPanel;
JTextField squareSize = MagicSquare.squareSize;
JTextField field = MagicSquare.field;
ArrayList<JTextField> inputFields = MagicSquare.inputFields;
JButton calculate = MagicSquare.calculate;
JButton reset = MagicSquare.reset;
JPanel bottomPanel = MagicSquare.bottomPanel;
public void actionPerformed(ActionEvent e){
square = Integer.parseInt(squareSize.getText());
squared = square*square;
centerPanel.setLayout(new GridLayout(square, square));
for(int i = 0; i < squared; i++){
field = new JTextField();
field.setColumns(3);
inputFields.add(field);
centerPanel.add(inputFields.get(i));
System.out.println("DRAWING");
}
add(centerPanel, BorderLayout.CENTER);
System.out.println("ADDING ADDITINOAL BUTTONS");
additionalButtons();
System.out.println("ADDED ADDITINOAL BUTTONS");
System.out.println("REPAINTING");
repaint();
System.out.println("REPAINTED");
}
public void additionalButtons(){
calculate = new JButton("Calculate");
reset = new JButton("Reset");
bottomPanel.setLayout(new GridLayout(2, 2));
bottomPanel.add(reset);
bottomPanel.add(calculate);
add(bottomPanel, BorderLayout.SOUTH);
calculate.addActionListener(new CalculateListener());
reset.addActionListener(new ResetListener());
}
}
Mistake #1
public static JPanel centerPanel = new JPanel();
Followed by...
class DrawFieldsListener extends JPanel implements ActionListener {
//...
JPanel centerPanel = MagicSquare.centerPanel;
static is not a cross object communication mechanism...and now I have no idea who is suppose to be responsible for managing the centerPanel...
Remember, static is not your friend, beware of how it is used
Mistake #2
setSize.addActionListener(new DrawFieldsListener());
add(subPanel, BorderLayout.NORTH);
add(new DrawFieldsListener(), BorderLayout.CENTER);
You are creating two instances of DrawFieldsListener (which is a panel), one is acting as the ActionListener and one is acting as the view, but which one is actually housing MagicSquare.centerPanel as a component can only have one parent...
Mistake #3
Not revalidating the container after you have changed it...
public void actionPerformed(ActionEvent e) {
square = Integer.parseInt(squareSize.getText());
squared = square * square;
centerPanel.setLayout(new GridLayout(square, square));
for (int i = 0; i < squared; i++) {
field = new JTextField();
field.setColumns(3);
inputFields.add(field);
centerPanel.add(inputFields.get(i));
System.out.println("DRAWING");
}
add(centerPanel, BorderLayout.CENTER);
System.out.println("ADDING ADDITINOAL BUTTONS");
additionalButtons();
System.out.println("ADDED ADDITINOAL BUTTONS");
System.out.println("REPAINTING");
revalidate();
repaint();
System.out.println("REPAINTED");
}
Swing is lazy when it comes to container management, it assumes that you will want to do a number of adds or removes, so it won't update the container hierarchy layout until you ask it to, as the operation can be expensive
A better solution...
Isolate responsibility and provide information to your objects in a de-coupled manner.
For example, the DrawFieldsListener shouldn't care about MagicSquare, but should provide a means by which "some body" can tell it how many squares it should create.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class MagicSquare extends JPanel {
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();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new MagicSquare());
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
JLabel sizeLabel = new JLabel("Enter A Square Size: ");
JButton setSize;
private JSpinner squareSize;
JTextField field;
public MagicSquare() {
setLayout(new BorderLayout());
JPanel subPanel = new JPanel();
subPanel.add(sizeLabel);
squareSize = new JSpinner();
subPanel.add(squareSize);
setSize = new JButton("Enter");
subPanel.add(setSize);
DrawFieldsListener dfl = new DrawFieldsListener();
setSize.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int gridSize = (int) squareSize.getValue();
dfl.makeGrid(gridSize);
}
});
add(subPanel, BorderLayout.NORTH);
add(dfl, BorderLayout.CENTER);
}
class DrawFieldsListener extends JPanel {
private JButton calculate;
private JButton reset;
private ArrayList<JTextField> inputFields = new ArrayList<JTextField>();
private ArrayList<Integer> inputs = new ArrayList<Integer>();
private ArrayList<Integer> totals = new ArrayList<Integer>();
private int squared = 0;
private int square = 0;
private JPanel centerPanel = new JPanel();
private JPanel bottomPanel = new JPanel();
public void makeGrid(int gridSize) {
square = gridSize;
squared = square * square;
centerPanel.setLayout(new GridLayout(square, square));
for (int i = 0; i < squared; i++) {
field = new JTextField();
field.setColumns(3);
inputFields.add(field);
centerPanel.add(inputFields.get(i));
System.out.println("DRAWING");
}
add(centerPanel, BorderLayout.CENTER);
System.out.println("ADDING ADDITINOAL BUTTONS");
additionalButtons();
System.out.println("ADDED ADDITINOAL BUTTONS");
System.out.println("REPAINTING");
revalidate();
repaint();
System.out.println("REPAINTED");
}
public void additionalButtons() {
calculate = new JButton("Calculate");
reset = new JButton("Reset");
bottomPanel.setLayout(new GridLayout(2, 2));
bottomPanel.add(reset);
bottomPanel.add(calculate);
add(bottomPanel, BorderLayout.SOUTH);
// calculate.addActionListener(new CalculateListener());
// reset.addActionListener(new ResetListener());
}
}
}
I am trying to create a Java GUI application that contains a label and button. When the button is clicked the background color of the first panel is changed. I've got the label and button but getting errors whenever I click the button. Also, I wanted the first panel to originally have a yellow background then switch to whatever color. Here's my code:
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
public class ChangeDemo extends JFrame implements ActionListener
{
public static final int WIDTH = 300;
public static final int HEIGHT= 200;
private JPanel biggerPanel;
public static void main(String[] args)
{
ChangeDemo gui = new ChangeDemo();
gui.setVisible(true);
}
public ChangeDemo()
{
super ("ChangeBackgroundDemo");
setSize(WIDTH,HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(2,3));
JPanel biggerPanel = new JPanel();
biggerPanel.setLayout(new BorderLayout());
biggerPanel.setBackground(Color.YELLOW);
JLabel namePanel = new JLabel("Click the button to change the background color");
biggerPanel.add(namePanel, BorderLayout.NORTH);
add(namePanel);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.setBackground(Color.LIGHT_GRAY);
JButton changeButton = new JButton("Change Color");
changeButton.addActionListener(this);
buttonPanel.add(changeButton);
add(buttonPanel);
}
public void actionPerformed(ActionEvent e)
{
String buttonString = e.getActionCommand();
if(buttonString.equals("Change Color"))
biggerPanel.setBackground(Color.RED);
else
System.out.println("Unexpected Error!");
}
}
I made a few changes to your code.
First, you must start a Swing application with a call to SwingUtilities.invokeLater.
public static void main(String[] args) {
SwingUtilities.invokeLater(new ChangeDemo());
}
Second, you use Swing components. You only extend a Swing component when you want to override a method of the Swing component.
Third, I made a action listener specifically for your JButton. That way, you don't have to check for a particular JButton string. You can create as many action listeners as you need for your GUI.
JButton changeButton = new JButton("Change Color");
changeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
isYellow = !isYellow;
if (isYellow) buttonPanel.setBackground(Color.YELLOW);
else buttonPanel.setBackground(Color.RED);
}
});
Finally, I changed the background color of the JButton panel.
Here's the entire ChangeDemo class.
package com.ggl.testing;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ChangeDemo implements Runnable {
private boolean isYellow;
private JFrame frame;
public static void main(String[] args) {
SwingUtilities.invokeLater(new ChangeDemo());
}
#Override
public void run() {
frame = new JFrame("Change Background Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
JPanel namePanel = new JPanel();
JLabel nameLabel = new JLabel(
"Click the button to change the background color");
nameLabel.setAlignmentX(JLabel.CENTER_ALIGNMENT);
namePanel.add(nameLabel);
mainPanel.add(namePanel);
final JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.setBackground(Color.YELLOW);
isYellow = true;
JButton changeButton = new JButton("Change Color");
changeButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
isYellow = !isYellow;
if (isYellow) buttonPanel.setBackground(Color.YELLOW);
else buttonPanel.setBackground(Color.RED);
}
});
buttonPanel.add(changeButton);
mainPanel.add(buttonPanel);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
Here is working demo based on amendments to your code, haven't had time to tidy it up but hopefully you'll get the gist of it. Problem was you hand't added Panels to the borders (north, south etc.) in order to color them. Hopefully this helps.
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JLabel;
public class ChangeDemo extends JFrame implements ActionListener
{
public static final int WIDTH = 300;
public static final int HEIGHT= 200;
private JPanel biggerPanel = new JPanel();
private JPanel namePanel = new JPanel();
public static void main(String[] args)
{
ChangeDemo gui = new ChangeDemo();
gui.setVisible(true);
}
public ChangeDemo()
{
super ("ChangeBackgroundDemo");
setSize(WIDTH,HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(2,3));
//JPanel biggerPanel = new JPanel();
this.biggerPanel.setLayout(new BorderLayout());
this.biggerPanel.setBackground(Color.YELLOW);
JLabel nameLabel = new JLabel("Click the button to change the background color");
namePanel.add(nameLabel);
namePanel.setBackground(Color.YELLOW);
//this.biggerPanel.add(namePanel, BorderLayout.NORTH);
add(namePanel);
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.setBackground(Color.LIGHT_GRAY);
JButton changeButton = new JButton("Change Color");
changeButton.addActionListener(this);
changeButton.setActionCommand("Change Color");
buttonPanel.add(changeButton);
add(buttonPanel);
}
public void actionPerformed(ActionEvent e)
{
String buttonString = e.getActionCommand();
if(buttonString.equals("Change Color"))
this.namePanel.setBackground(Color.RED);
else
System.out.println("Unexpected Error!");
}
}
This is my program below and I am trying to figure out where my main method should be. I have seen a few examples of it being implemented at the very end of the program but there main is different from mine.
Main method (to be implemented):
public class JFrame
{
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setTitle("Components File");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
My Program
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.JTextField;
public class Lab_10 extends JFrame
{
private final double EARTHQUAKE_RATE= 8.0;
private final int FRAME_WIDTH= 300;
private final int FRAME_HEIGHT= 200;
private JLabel rLabel;
private JTextField eField;
private JButton button;
private JLabel earthLabel;
public Lab_10()
{
JLabel earthLabel = new JLabel("Most structures fall");
makeTextField();
makeButton();
makePanel();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
private void makeTextField()
{
JLabel rLabel = new JLabel("Richter");
final int FIELD_WIDTH = 10;
eField = new JTextField(FIELD_WIDTH);
eField.setText("" + EARTHQUAKE_RATE);
}
class AddLabelListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
earthLabel.setText("Most structures fall");
}
}
private void makeButton()
{
JButton button = new JButton("Enter");
ActionListener listener = new AddLabelListener();
button.addActionListener(listener);
}
private void makePanel()
{
JPanel panel = new JPanel();
panel.add(rLabel);
panel.add(eField);
panel.add(button);
panel.add(earthLabel);
add(panel);
}
}
Updated Code (which is compiling but and running but with logic errors because it implements an empty frame [guess as much from the main method I have]):
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.JTextField;
public class Lab_10 extends JFrame
{
private final double EARTHQUAKE_RATE= 8.0;
private final int FRAME_WIDTH= 300;
private final int FRAME_HEIGHT= 200;
private JLabel rLabel;
private JTextField eField;
private JButton button;
private JLabel earthLabel;
public Lab_10()
{
JLabel earthLabel = new JLabel("Most structures fall");
makeTextField();
makeButton();
makePanel();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
private void makeTextField()
{
JLabel rLabel = new JLabel("Richter");
final int FIELD_WIDTH = 10;
eField = new JTextField(FIELD_WIDTH);
eField.setText("" + EARTHQUAKE_RATE);
}
class AddLabelListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
earthLabel.setText("Most structures fall");
}
}
private void makeButton()
{
JButton button = new JButton("Enter");
ActionListener listener = new AddLabelListener();
button.addActionListener(listener);
}
private void makePanel()
{
JPanel panel = new JPanel();
panel.add(rLabel);
panel.add(eField);
panel.add(button);
panel.add(earthLabel);
add(panel);
}
public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable(){
#Override
public void run()
{ JFrame frame = new JFrame();
frame.setTitle("Components File");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
Your 'main' probably looks different because you are not using SwingUtilities.invokeLater(Runnable doRun) ?
Well, to put it simply, you must use it always. So, modify your code and use this:
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run(){
// copy-paste your main() code
}
});
Also, why is your class named JFrame ? Refrain from using names that are already used by Java classes already.
package bt;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class login extends javax.swing.JFrame implements ActionListener, javax.swing.RootPaneContainer {
private static final long serialVersionUID = 1L;
private JTextField TUserID=new JTextField(20);
private JPasswordField TPassword=new JPasswordField(20);
protected int role;
public JButton bLogin = new JButton("continue");
private JButton bCancel = new JButton("cancel");
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new login().createAndShowGUI();
}
});
}
public void createAndShowGUI() {
ImageIcon icon = new ImageIcon("");
JLabel l = new JLabel();
JLabel l2 = new JLabel("(2011)");
l2.setFont(new Font("Courier New", Font.BOLD, 10));
l.setIcon(icon);
JLabel LUserID=new JLabel("Your User ID: ");
JLabel LPassword=new JLabel("Your Password: ");
TUserID.addActionListener(this);
TPassword.addActionListener(this);
TUserID.setText("correct");
TPassword.setEchoChar('*');
TPassword.setText("correct");
bLogin.setOpaque(true);
bLogin.addActionListener(this);
bCancel.setOpaque(true);
bCancel.addActionListener(this);
JFrame f = new JFrame("continue");
f.setUndecorated(true);
f.setSize(460,300);
AWTUtilitiesWrapper.setWindowOpaque(f, false);
AWTUtilitiesWrapper.setWindowOpacity(f, ((float) 80) / 100.0f);
Container pane = f.getContentPane();
pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS) );
pane.setBackground(Color.BLACK);
Box box0 = Box.createHorizontalBox();
box0.add(Box.createHorizontalGlue());
box0.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
box0.add(l);
box0.add(Box.createRigidArea(new Dimension(100, 0)));
pane.add(box0);
Box box = Box.createHorizontalBox();
box.add(Box.createHorizontalGlue());
box.setBorder(BorderFactory.createEmptyBorder(10, 20, 20, 100));
box.add(Box.createRigidArea(new Dimension(100, 0)));
box.add(LUserID);
box.add(Box.createRigidArea(new Dimension(32, 0)));
box.add(TUserID);
LUserID.setMaximumSize( LUserID.getPreferredSize() );
TUserID.setMaximumSize( TUserID.getPreferredSize() );
pane.add(box);
Box box2 = Box.createHorizontalBox();
box2.add(Box.createHorizontalGlue());
box2.setBorder(BorderFactory.createEmptyBorder(10, 20, 20, 100));
box2.add(Box.createRigidArea(new Dimension(100, 0)));
box2.add(LPassword,LEFT_ALIGNMENT);
box2.add(Box.createRigidArea(new Dimension(15, 0)));
box2.add(TPassword,LEFT_ALIGNMENT);
LPassword.setMaximumSize( LPassword.getPreferredSize() );
TPassword.setMaximumSize( TPassword.getPreferredSize() );
pane.add(box2);
Box box3 = Box.createHorizontalBox();
box3.add(Box.createHorizontalGlue());
box3.setBorder(BorderFactory.createEmptyBorder(20, 20, 0, 100));
box3.add(bLogin);
box3.add(Box.createRigidArea(new Dimension(10, 0)));
box3.add(bCancel);
pane.add(box3);
f.setLocation(450,300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setBackground(Color.BLACK);
f.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent evt) {
String TBUsername = TUserID.getText();
Object src = evt.getSource();
char[] CHPassword1 = TPassword.getPassword();
String TBPassword = String.valueOf(CHPassword1);
login mLogin = this;
if (src==bLogin) {
if (authenticate(TBUsername,TBPassword)) {
System.out.println(this);
exitApp(this);
} else {
exitApp(this);
}
} else if (src==bCancel) {
exitApp(mLogin);
}
}
public void exitApp(JFrame mlogin) {
mlogin.setVisible(false);
}
private boolean authenticate(String uname, String pword) {
if ((uname.matches("correct")) && (pword.matches("correct"))) {
new MyJFrame().createAndShowGUI();
return true;
}
return false;
}
}
and MyJFrame.java
package bt;
import java.awt.Color;
import java.awt.Container;
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.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class MyJFrame extends javax.swing.JFrame implements ActionListener {
private static final long serialVersionUID = 2871032446905829035L;
private JButton bExit = new JButton("Exit (For test purposes)");
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MyJFrame().createAndShowGUI();
}
});
}
public void createAndShowGUI() {
JPanel p = new JPanel();
p.setBackground(Color.black);
ImageIcon icon = new ImageIcon("");
JLabel l = new JLabel("(2011)"); //up to here
l.setIcon(icon);
p.add(l);
p.add(bExit);
bExit.setOpaque(true);
bExit.addActionListener(this);
JFrame f = new JFrame("frame");
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setUndecorated(true);
p.setOpaque(true);
f.getContentPane().add(p);
f.pack();
f.setSize(1000,600);
Container pane=f.getContentPane();
pane.setLayout(new GridLayout(0,1) );
//p.setPreferredSize(200,200);
AWTUtilitiesWrapper.setWindowOpaque(f, false);
AWTUtilitiesWrapper.setWindowOpacity(f, ((float) 90) / 100.0f);
f.setLocation(300,300);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent evt) {
Object src = evt.getSource();
if (src==bExit) {
System.exit(0);
}
}
}
I cannot get the exitApp() method to work, although it worked before I expanded on my code, I've been trying for hours to get it to work but no avail! The login button suceeds in opening the new frame but will not close the preious(login) frame. It did earlier till I added the validation method etc ....
Create only one JFrame as parent and for another Top-level Containers create only once JDialog (put there JPanel as base), and re-use that for another Action, then you only to remove all JComponents from Base JPanel and add there another JPanel
don't forget for as last lines after switch betweens JPanels inside Base JPanel
revalidate();
repaint();
you can pretty to forgot about that by implements CardLayout