the JLabel's name is set to an int which changes as the user modifies the number, i tried label.revalidate and Label.repaint after the user changes the int value. i have seen in similar questions people suggest creating a new jlabel everytime, but im wondering if there is a simpler way? the code is very long so i will summerize when needed.
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 officia {
static JFrame Frame;
static JPanel Panel;
static JTextField healthPlace;
static String health="0";
static JButton begin;
static JLabel heart;
static int loop;
public static void main(String[] args) {
Panel = new JPanel();
Frame = new JFrame();
Frame.setSize(500,1000);
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.add(Panel);
Panel.setLayout(null);
//adds panel and frame
healthPlace = new JTextField();
healthPlace.setBounds(170, 130, 165, 25);
Panel.add(healthPlace);
begin = new JButton("Begin");
begin.setBounds(217, 185, 70, 25);
Panel.add(begin);
while(loop==1)
loop=0;
heart = new JLabel(health);
heart.setBounds(150, -85, 500, 500);
Panel.add(heart);
Frame.setVisible(true);
//inputs gui's
ActionListener beginPressed = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
health = healthPlace.getText();
loop=1;
}
};
begin.addActionListener(beginPressed);
}
}
You're working in a event driven environment, that is, something happens and you respond to it.
This means, you're while-loop is ill-conceived and is probably the source of your issue. How can the ActionListener for the button be added when the loop is running, but you seem to using the ActionListener to exit the loop...
I modified you code slightly, so when you press the button, it will update the label.
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 officia {
static JFrame Frame;
static JPanel Panel;
static JTextField healthPlace;
static String health = "0";
static JButton begin;
static JLabel heart;
static int loop;
public static void main(String[] args) {
Panel = new JPanel();
Frame = new JFrame();
Frame.setSize(500, 1000);
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.add(Panel);
Panel.setLayout(null);
//adds panel and frame
healthPlace = new JTextField();
healthPlace.setBounds(170, 130, 165, 25);
Panel.add(healthPlace);
begin = new JButton("Begin");
begin.setBounds(217, 185, 70, 25);
Panel.add(begin);
// This is ... interesting, but a bad idea
// while (loop == 1) {
// loop = 0;
// }
heart = new JLabel(health);
heart.setBounds(150, -85, 500, 500);
Panel.add(heart);
Frame.setVisible(true);
//inputs gui's
ActionListener beginPressed = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
health = healthPlace.getText();
loop ++;
heart.setText(Integer.toString(loop));
}
};
begin.addActionListener(beginPressed);
}
}
JLabel#setText is what's known as a stateful property, that is, it will trigger an update that will cause it to be painted, so, if it's not updating, you're doing something wrong.
Possible runnable example (of what I think you want to do)
You're working a very rich UI framework. One if it's, many, features, is the layout management framework, something you should seriously take the time to learn to understand and use.
See Laying Out Components Within a Container for more details.
Below is a relatively simple example which shows one way you might "swicth" between views based on a response to a user input
import java.awt.CardLayout;
import java.awt.EventQueue;
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.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new BasePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class BasePane extends JPanel {
private CardLayout cardLayout;
public BasePane() {
cardLayout = new CardLayout();
setLayout(cardLayout);
StartPane startPane = new StartPane(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cardLayout.show(BasePane.this, "HeartPane");
}
});
HeartPane heartPane = new HeartPane();
add(startPane, "StartPane");
add(heartPane, "HeartPane");
}
}
public class StartPane extends JPanel {
public StartPane(ActionListener actionListener) {
setBorder(new EmptyBorder(10, 10, 10, 10));
setLayout(new GridBagLayout());
JButton start = new JButton("Begin");
add(start);
start.addActionListener(actionListener);
}
}
public class HeartPane extends JPanel {
private JTextField heartTextField;
private JLabel heartLabel;
public HeartPane() {
setBorder(new EmptyBorder(10, 10, 10, 10));
setLayout(new GridBagLayout());
heartLabel = new JLabel("Heart");
heartTextField = new JTextField(10);
add(heartLabel);
add(heartTextField);
}
}
}
Related
I am writing in a notepad. And I want to implement text scaling in my notepad. But I don't know how to do it. I'm trying to find it but everyone is suggesting to change the font size. But I need another solution.
I am create new project and add buttons and JTextArea.
package zoomtest;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class zoom {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
zoom window = new zoom();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public zoom() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.NORTH);
JButton ZoomIn = new JButton("Zoom in");
ZoomIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//Code here...
}
});
panel.add(ZoomIn);
JButton Zoomout = new JButton("Zoom out");
Zoomout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//Code here...
}
});
panel.add(Zoomout);
JTextArea jta = new JTextArea();
frame.getContentPane().add(jta, BorderLayout.CENTER);
}
}
Introduction
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section. Pay close attention to the Laying Out Components Within a Container section.
I reworked your GUI. Here's how it looks when the application starts. I typed some text so you can see the font change.
Here's how it looks after we zoom out.
Here's how it looks after we zoom in.
Stack Overflow scales the images, so it's not as obvious that the text is zooming.
Explanation
Swing was designed to be used with layout managers. I created two JPanels, one for the JButtons and one for the JTextArea. I put the JTextArea in a JScrollPane so you could type more than 10 lines.
I keep track of the font size in an int field. This is a simple application model. Your Swing application should always have an application model made up of one or more plain Java getter/setter classes.
Code
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
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.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class ZoomTextExample {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
new ZoomTextExample();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private int pointSize;
private Font textFont;
private JFrame frame;
private JTextArea jta;
private JTextField pointSizeField;
public ZoomTextExample() {
this.pointSize = 16;
this.textFont = new Font(Font.DIALOG, Font.PLAIN, pointSize);
initialize();
}
private void initialize() {
frame = new JFrame("Text Editor");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createButtonPanel(), BorderLayout.NORTH);
frame.add(createTextAreaPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
JButton zoomIn = new JButton("Zoom in");
zoomIn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
incrementPointSize(+2);
updatePanels();
}
});
panel.add(zoomIn);
panel.add(Box.createHorizontalStrut(20));
JLabel label = new JLabel("Current font size:");
panel.add(label);
pointSizeField = new JTextField(3);
pointSizeField.setEditable(false);
pointSizeField.setText(Integer.toString(pointSize));
panel.add(pointSizeField);
panel.add(Box.createHorizontalStrut(20));
JButton zoomOut = new JButton("Zoom out");
zoomOut.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
incrementPointSize(-2);
updatePanels();
}
});
panel.add(zoomOut);
return panel;
}
private JPanel createTextAreaPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
jta = new JTextArea(10, 40);
jta.setFont(textFont);
JScrollPane scrollPane = new JScrollPane(jta);
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
private void updatePanels() {
pointSizeField.setText(Integer.toString(pointSize));
textFont = textFont.deriveFont((float) pointSize);
jta.setFont(textFont);
frame.pack();
}
private void incrementPointSize(int increment) {
pointSize += increment;
}
}
I would like my original window to close when someone enters the password and a new one to pop up, or if you have a better recommendation please tell me. Here is my code,
The main class,
package notebook;
import java.awt.EventQueue;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.CompoundBorder;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
public class mainPage extends JDialog {
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainPage frame = new mainPage();
frame.setVisible(true);
frame.setResizable(false);
Image icon = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB_PRE);
frame.setIconImage(icon);
frame.setTitle("Notebook");
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* #throws IOException
*/
public mainPage() throws IOException {
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setBounds(100, 100, 560, 390);
JLabel contentPane = new JLabel(
new ImageIcon(
ImageIO.read(new File(
"C:\\Users\\Gianmarco\\workspace\\notebook\\src\\notebook\\cool_cat.jpg"))));
contentPane.setBorder(new CompoundBorder());
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblEnterPassword = new JLabel(" Enter Password");
lblEnterPassword.setForeground(Color.LIGHT_GRAY);
lblEnterPassword.setBackground(Color.DARK_GRAY);
lblEnterPassword.setOpaque(true);
lblEnterPassword.setBounds(230, 60, 100, 15);
contentPane.add(lblEnterPassword);
security sInfo = new security();
textField = new JPasswordField(10);
nbTab notebook = new nbTab();
Action action = new AbstractAction()
{
#Override
public void actionPerformed(ActionEvent e)
{
String textFieldValue = textField.getText();
if (sInfo.checkPassword(textFieldValue)){
System.out.println("working");
notebook.setVisible(true);
//dispose();
}
}
};
JPanel panel = new JPanel();
textField.setBounds(230, 85, 100, 15);
contentPane.add(textField);
contentPane.add(panel);
textField.setColumns(10);
textField.addActionListener(action);
}
}
The password class,
package notebook;
public class security {
private String password = "kitten";
protected boolean checkPassword(String x){
if(x.length()<15 && x.equals(password)) return true;
return false;
}
}
The JTabbedPane class,
package notebook;
import javax.swing.JTabbedPane;
import javax.swing.JEditorPane;
import javax.swing.JList;
import javax.swing.JButton;
public class nbTab<E> extends JTabbedPane {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* Create the panel.
*/
public nbTab() {
JEditorPane editorPane = new JEditorPane();
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(480, 345, 40, 30);
editorPane.add(btnNewButton);
editorPane.setBounds(80, 45, 400, 300);
addTab("New tab", null, editorPane, null);
JList<? extends E> list = new JList();
addTab("New tab", null, list, null);
}
}
In my main class, on lines 76 - 82 (where the action event listner is located) I would like to have my current window close and a new window of notebook to open. I used dispose() to close the password window. Then I try to open the JTabbedPane with setVisible(), setSelectedComponent, and setSelectedIndex however I am either using them incorrectly or there must be some better way to do this because it is not working. Any advice is appreciated guys thanks for all help.
As already suggested by MadProgrammer and Frakcool, the CardLayout layout manager is an interesting option in your case. A nice introduction to several Layout Managers for Swing is available here: A Visual Guide to Layout Managers.
You can use the code below to get an idea of how it could work. I have made a few modifications to your main application class:
The main class now extends from JFrame (instead of JDialog).
A few more panels and layout managers are used.
In Java class names usually start with a capital letter, so I have renamed your classes to MainPage, NotebookTab, and Security.
Here is the modified MainPage class:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class MainPage extends JFrame {
private static final String LOGIN_PANEL_ID = "Login panel";
private static final String NOTEBOOK_ID = "Notebook tabbed pane";
private JPanel mainPanel;
private CardLayout cardLayout;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainPage frame = new MainPage();
frame.setResizable(false);
Image icon = new BufferedImage(1, 1,
BufferedImage.TYPE_INT_ARGB_PRE);
frame.setIconImage(icon);
frame.setTitle("Notebook");
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* #throws IOException
*/
public MainPage() throws IOException {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setBounds(100, 100, 560, 390);
cardLayout = new CardLayout();
mainPanel = new JPanel(cardLayout);
mainPanel.add(createLoginPanel(), LOGIN_PANEL_ID);
mainPanel.add(new NotebookTab(), NOTEBOOK_ID);
getContentPane().add(mainPanel);
}
private JPanel createLoginPanel() throws IOException {
JPanel loginPanel = new JPanel(new BorderLayout());
JPanel passwordPanel = new JPanel();
passwordPanel.setLayout(new BoxLayout(passwordPanel, BoxLayout.PAGE_AXIS));
JLabel lblEnterPassword = new JLabel("Enter Password");
lblEnterPassword.setForeground(Color.LIGHT_GRAY);
lblEnterPassword.setBackground(Color.DARK_GRAY);
lblEnterPassword.setOpaque(true);
lblEnterPassword.setHorizontalAlignment(SwingConstants.CENTER);
lblEnterPassword.setMaximumSize(new Dimension(100, 16));
lblEnterPassword.setAlignmentX(Component.CENTER_ALIGNMENT);
JTextField textField = new JPasswordField(10);
textField.setMaximumSize(new Dimension(100, 16));
textField.setAlignmentX(Component.CENTER_ALIGNMENT);
passwordPanel.add(Box.createRigidArea(new Dimension(0, 42)));
passwordPanel.add(lblEnterPassword);
passwordPanel.add(Box.createRigidArea(new Dimension(0, 10)));
passwordPanel.add(textField);
loginPanel.add(passwordPanel, BorderLayout.NORTH);
Action loginAction = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
if (new Security().checkPassword(textField.getText())) {
System.out.println("working");
cardLayout.show(mainPanel, NOTEBOOK_ID);
}
}
};
textField.addActionListener(loginAction);
String imagePath = "C:\\Users\\Gianmarco\\workspace\\" +
"notebook\\src\\notebook\\cool_cat.jpg";
BufferedImage bufferedImage = ImageIO.read(new File(imagePath));
JLabel imageLabel = new JLabel(new ImageIcon(bufferedImage));
loginPanel.add(imageLabel, BorderLayout.CENTER);
return loginPanel;
}
}
So I'm just checking and when I click my button it won't show my JPanel, any idea why?
Thanks.
I want the third class to show, really do appreciate the help - Thanks allot.
First class - JFrame class.
import javax.swing.JFrame;
public class Frame {
public static void main(String[] args ) {
JFrame frame = new JFrame("JFrame Demo");
Panel panel1 = new Panel();
frame.add(panel1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 500);
frame.setVisible(true);
}
}
Second class - Panel 1
import javax.swing.JPanel;
import java.awt.CardLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Panel extends JPanel{
public Panel() {
setLayout(null);
final Panel2 panel2 = new Panel2();
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
panel2.setVisible(true);
}
});
btnNewButton.setBounds(62, 197, 224, 122);
add(btnNewButton);
}
}
Third class - Panel 2 (I want this to show)
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.CardLayout;
import javax.swing.JTextField;
public class Panel2 extends JPanel {
private JTextField textField;
public Panel2() {
setLayout(null);
setVisible(true);
textField = new JTextField();
textField.setBounds(84, 84, 290, 77);
add(textField);
textField.setColumns(10);
}
}
You never add panel2 to anything. A JPanel isn't like a JFrame where setVisible makes it magically appear. You need to add it to a container. Just add it to your Panel.
Also avoid using null layouts. Learn to use Layout Managers
Also see Initial Threads. You want to run your swing apps from the Event Dispatch Thread like this
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new Frame();
}
});
}
This looks like a case where you may have been trying to do something along the lines of what a CardLayout achieves. See this example for a basic use. Also see How to Use Card Layout
In the second class, after the second line in the constructor, have you tried?
add(panel2);
See if this works.
Modify Panel.java to look like below. Tell me if this is good for your needs:
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Panel extends JPanel{
Panel2 panel2 = null;
JButton btnNewButton = null;
public Panel() {
setLayout(null);
panel2 = new Panel2();
panel2.setBounds(5,5,300,500);
add(panel2);
showPanel2(false);
btnNewButton = new JButton("New button");
btnNewButton.setBounds(62, 197, 224, 122);
add(btnNewButton);
showButton(true);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showButton(false);
showPanel2(true);
}
});
}
public void showPanel2(boolean bshow)
{
panel2.setVisible(bshow);
}
public void showButton(boolean bshow)
{
btnNewButton.setVisible(bshow);
}
}
I want to add textfields dynamically on the click of a button but the value to be fetched and the button are in one class and the panel where i want to add the textboxes and sliders adjacent to the are in a different class. Code is -
public class TipSplitting extends JPanel
JLabel lblNoOfGuests = new JLabel("No. Of guests");
lblNoOfGuests.setBounds(10, 26, 95, 14);
add(lblNoOfGuests);
private JTextField noofguests = new JTextField();
noofguests.setBounds(179, 23, 86, 20);
add(noofguests);
noofguests.setColumns(10);
JButton btnTiptailoring = new JButton("TipTailoring");
btnTiptailoring.setBounds(117, 286, 89, 23);
add(btnTiptailoring);
public class TipTailoring extends JPanel {}
In this class I need to create the text fields dynamically according to the no. entered. In the variable noofguests and the click of the button in the previous class.
I can't really see what the problem, but here some simple demo code of what you describe.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
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.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TestDynamicallyAddedTextFields {
private void initUI() {
JFrame frame = new JFrame(TestDynamicallyAddedTextFields.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel textfieldContainerPanel = new JPanel();
textfieldContainerPanel.setLayout(new GridBagLayout());
JLabel nrOfGuests = new JLabel("Nr. of guests");
final JFormattedTextField textfield = new JFormattedTextField();
textfield.setValue(Integer.valueOf(1));
textfield.setColumns(10);
JButton add = new JButton("Add");
add.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (textfield.getValue() != null) {
addTextFieldsToPanel((Integer) textfield.getValue(), textfieldContainerPanel);
}
}
});
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEADING));
panel.add(nrOfGuests);
panel.add(textfield);
panel.add(add);
frame.add(panel, BorderLayout.NORTH);
frame.add(new JScrollPane(textfieldContainerPanel));
frame.setSize(300, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
protected void addTextFieldsToPanel(Integer value, JPanel textfieldContainerPanel) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.gridheight = 1;
for (int i = 0; i < value; i++) {
textfieldContainerPanel.add(new JTextField(20), gbc);
}
textfieldContainerPanel.revalidate();
textfieldContainerPanel.repaint();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestDynamicallyAddedTextFields().initUI();
}
});
}
}
And the result:
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