Making a log in window to direct to another GUI in java - java

I am making a Log in window, so after enter username, password and click login button it will direct you to another frame, which is my GUI that use to insert, retrieve, update, and delete database. However, after click, it displayed nothing. Thank you! Here is my code:
It should redirect to GUI like this:
Login
public class Log extends JFrame {
public static void main(String[] args) {
Log frameTabel = new Log();
}
JButton blogin = new JButton("Login");
JPanel panel = new JPanel();
JTextField txuser = new JTextField(15);
JPasswordField pass = new JPasswordField(15);
Log() {
super("Login Autentification");
setSize(300, 200);
setLocation(500, 280);
panel.setLayout(null);
txuser.setBounds(70, 30, 150, 20);
pass.setBounds(70, 65, 150, 20);
blogin.setBounds(110, 100, 80, 20);
panel.add(blogin);
panel.add(txuser);
panel.add(pass);
getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
actionlogin();
}
public void actionlogin() {
blogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String puname = txuser.getText();
String ppaswd = pass.getText();
if ( puname.equals("test") && ppaswd.equals("12345") ) {
CarSearch regFace = new CarSearch();
// regFace.setVisible(true);
dispose();
} else {
JOptionPane.showMessageDialog(null,
"Wrong Password / Username");
txuser.setText("");
pass.setText("");
txuser.requestFocus();
}
}
});
}
Here is the CarSearch
public class CarSearch {
public static void main(String[] args) {
MainPanel logoPanel = new MainPanel();
JFrame frame = new JFrame("Cars Search");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(logoPanel, BorderLayout.NORTH);
JTabbedPane tabPage = new JTabbedPane();
// tabPage.addTab("Log In", new Log());
tabPage.addTab("Insert Data", new InsertPanel());
tabPage.addTab("Retrieve Data", new RetrievePanel());
tabPage.addTab("Update Data", new UpdatePanel());
tabPage.addTab("Delete Data", new DeletePanel());
frame.getContentPane().add(tabPage, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}

First of all, I don't encourage the use of multiple frames, instead you should use a CardLayout, how ever. Your CarSearch class doesn't do anything, it only has static main method, which you never call.
I would change the class so it has a constructor which initialises the class and a method you can call so you can control when you want to the window shown
public class CarSearch {
private MainPanel logoPanel;
private JFrame frame;
public CarSearch() {
logoPanel = new MainPanel();
frame = new JFrame("Cars Search");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(logoPanel, BorderLayout.NORTH);
JTabbedPane tabPage = new JTabbedPane();
// tabPage.addTab("Log In", new Log());
tabPage.addTab("Insert Data", new InsertPanel());
tabPage.addTab("Retrieve Data", new RetrievePanel());
tabPage.addTab("Update Data", new UpdatePanel());
tabPage.addTab("Delete Data", new DeletePanel());
frame.getContentPane().add(tabPage, BorderLayout.CENTER);
}
public void show() {
frame.pack();
frame.setVisible(true);
}
}
Now, having said that, I'd strongly encourage you to use a CardLayout.
Start by creating a LoginPanel and a CarSearchPanel, then you can add each to the same frame and use the CardLayout to switch between them as needed
For (a slight over the top) example

If that is what you want to do then in your CarSearch class should be a JFrame and in your main method you should have CarSearch frame = new CarSearch("Cars Search") instead of JFrame frame = new JFrame("Cars Search"). Then introduce a method public void authenticated() which should contain the code for enabling the other tabs. Also your initialisation should have all the tabs other than the login tab disabled.
Now in your method public void actionlogin() in your validation condition if ( puname.equals("test") && ppaswd.equals("12345") ) you should have CarSearch frame = (CarSearch)getRootPane(); and after that you could call frame.authenticated(); which will disable the login tab and enable the other tabs.

Related

How to make the roll button the default allowing enter press?

I wrote a program to randomly select an image and display it in the window every time a button is pressed. Mow I am trying to figure out how to make the "Roll Dice" button the default allowing enter press.
Driver:
public class MCobbM10A1 {
static int SCREEN_WIDTH = 500;
static int SCREEN_HEIGHT = 600;
static WidgetPanel widget;
static GraphicPanel myPanel;
public static void main(String[] args) {
JFrame myFrame = new JFrame("Dice Roller");
JFrame.setDefaultLookAndFeelDecorated(true);
myPanel = new GraphicPanel();
myPanel.setBounds(0, 0, 500, 200);
myFrame.add(myPanel);
JPanel lastPanel = new JPanel();
myFrame.add(lastPanel);
widget = new WidgetPanel();
widget.setBounds(0, 250, 500, 300);
myFrame.add(widget);
widget.rollButton.addActionListener((ActionEvent newRoll) -> {
new MCobbM10A1().myNewRollButtonPressed();
});
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.pack();
myFrame.setVisible(true);
myFrame.setBounds(0, 0, 500, 300);
}
private void myNewRollButtonPressed() {
myPanel.newRoll();
}
}
And here is the WidgetPanel:
public class WidgetPanel extends JPanel {
JButton rollButton;
WidgetPanel() {
this.setBackground(Color.WHITE);
this.setLayout(new BorderLayout());
rollButton = new JButton();
rollButton.setBounds(350, 200, 100, 25);
rollButton.setText("Roll Dice");
this.add(rollButton);
JLabel fixBug = new JLabel();
this.add(fixBug);
}
}
how to make the "Roll Dice" button the default allowing enter press.
You assign the default button to the JRootPane of your frame.
frame.getRootPane().setDefaultButton(…);
One way to do this is:
#Override
public void addNotify()
{
super.addNotify();
JFrame frame = (JFrame)SwingUtilities.windowForComponent( rollButton );
frame.getRootPane().setDefaultButton(rollButton);
}
The addNotify() method is invoked when a panel is added to the frame.
Unrelated to your question but why are you creating a new object for each roll?
widget.rollButton.addActionListener((ActionEvent newRoll) -> {
new MCobbM10A1().myNewRollButtonPressed(); // <--- new MCobbM10A1 object
});
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.pack();
myFrame.setVisible(true);
myFrame.setBounds(0, 0, 500, 300);
}
private void myNewRollButtonPressed() {
myPanel.newRoll();
}
Why not just do this?
widget.rollButton.addActionListener((ae) ->
myPanel.newRoll());

How to close JDialog and save the setting ?

Hi I'm working on a program and I faced a problem when I choose some settings from JDialog then click "ok", which is that the setting didn't save but come back to the original settings.
PS : I'm not English speaker so maybe you observe some mistakes in my text above.
picture
enter image description here
class DrawingSettingWindow extends JDialog {
public DrawingSettingWindow() {
this.setTitle("Drawing Setting Window");
this.setSize(550, 550);
this.setLocationRelativeTo(null);
this.setModal(true);
this.setLayout(new GridLayout(4, 1));
JLabel selectColorText = new JLabel("Select Drawing Color");
colorsList = new JComboBox(colors);
JPanel panel1 = new JPanel();
panel1.add(selectColorText);
panel1.add(colorsList);
add(panel1);
JLabel selectStyleText = new JLabel("Select Drawing Style");
JPanel panel2 = new JPanel();
normal = new JRadioButton("Normal");
normal.setSelected(true);
filled = new JRadioButton("Filled");
ButtonGroup bg = new ButtonGroup();
bg.add(normal);
bg.add(filled);
panel2.add(selectStyleText);
panel2.add(normal);
panel2.add(filled);
add(panel2);
JButton ok = new JButton("OK");
add(ok);
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
this.pack();
this.setVisible(true);
}
The information is there, you just have to extract it from the dialog after the user is done using it. I would give the code above at least two new methods, one a public getColor() method that returns colorsList.getSelectedItem();, the color selection of the user (I'm not sure what type of object this is, so I can't show the method yet). Also another one that gets the user's filled setting, perhaps
public boolean getFilled() {
return filled.isSelected();
}
Since the dialog is modal, you'll know that the user has finished using it immediately after you set it visible in the calling code. And this is where you call the above methods to extract the data.
In the code below, I've shown this in this section: drawingSettings.setVisible(true);
// here you extract the data
Object color = drawingSettings.getColor();
boolean filled = drawingSettings.getFilled();
textArea.append("Color: " + color + "\n");
textArea.append("Filled: " + filled + "\n");
}
For example (see comments):
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class UseDrawingSettings extends JPanel {
private JTextArea textArea = new JTextArea(20, 40);
private DrawingSettingWindow drawingSettings;
public UseDrawingSettings() {
JPanel topPanel = new JPanel();
topPanel.add(new JButton(new ShowDrawSettings()));
setLayout(new BorderLayout());
add(new JScrollPane(textArea));
add(topPanel, BorderLayout.PAGE_START);
}
private class ShowDrawSettings extends AbstractAction {
public ShowDrawSettings() {
super("Get Drawing Settings");
}
#Override
public void actionPerformed(ActionEvent e) {
if (drawingSettings == null) {
Window win = SwingUtilities.getWindowAncestor(UseDrawingSettings.this);
drawingSettings = new DrawingSettingWindow(win);
}
drawingSettings.setVisible(true);
// here you extract the data
Object color = drawingSettings.getColor();
boolean filled = drawingSettings.getFilled();
textArea.append("Color: " + color + "\n");
textArea.append("Filled: " + filled + "\n");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
private static void createAndShowGui() {
UseDrawingSettings mainPanel = new UseDrawingSettings();
JFrame frame = new JFrame("UseDrawingSettings");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
#SuppressWarnings("serial")
class DrawingSettingWindow extends JDialog {
private static final String TITLE = "Drawing Setting Window";
private JComboBox<String> colorsList;
private JRadioButton normal;
private JRadioButton filled;
// not sure what colors is, but I'll make it a String array for testing
private String[] colors = {"Red", "Orange", "Yellow", "Green", "Blue"};
public DrawingSettingWindow(Window win) {
super(win, TITLE, ModalityType.APPLICATION_MODAL);
// this.setTitle("Drawing Setting Window");
this.setSize(550, 550); // !! this is not recommended
this.setLocationRelativeTo(null);
this.setModal(true);
this.setLayout(new GridLayout(4, 1));
JLabel selectColorText = new JLabel("Select Drawing Color");
colorsList = new JComboBox(colors);
JPanel panel1 = new JPanel();
panel1.add(selectColorText);
panel1.add(colorsList);
add(panel1);
JLabel selectStyleText = new JLabel("Select Drawing Style");
JPanel panel2 = new JPanel();
normal = new JRadioButton("Normal");
normal.setSelected(true);
filled = new JRadioButton("Filled");
ButtonGroup bg = new ButtonGroup();
bg.add(normal);
bg.add(filled);
panel2.add(selectStyleText);
panel2.add(normal);
panel2.add(filled);
add(panel2);
JButton ok = new JButton("OK");
add(ok);
ok.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
this.pack();
// this.setVisible(true); // this should be the calling code's responsibility
}
public Object getColor() {
return colorsList.getSelectedItem();
}
public boolean getFilled() {
return filled.isSelected();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Foo");
}
}
Side notes:
I've changed your class's constructor to accept a Window parameter, the base class for JFrame, JDialog, and such, and have added a call to the super's constructor. This way, the dialog is a true child window of the calling code (or you can pass in null if you want it not to be).
I recommend not making the dialog visible within its constructor. It is the calling code's responsibility for doing this, and there are instances where the calling code will wish to not make the dialog visible after creating it, for example if it wanted to attach a PropertyChangeListener to it before making it visible. This is most important for modal dialogs, but is just good programming practice.
I didn't know the type of objects held by your combo box, and so made an array of String for demonstration purposes.

passing frame as parameter in method

i want to pass a JFrame as parameter in a method,
is it possible to do that ?
here is what i want :
private void mouseClickedButtonsActions(JLabel l, Class c){
l.addMouseListener(new java.awt.event.MouseAdapter() {
#Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
c ma = new c();
ma.setVisible(true);
setVisible(false);
}
});
}
You shouldn't be sending Class in this situation, if you want to learn more about sending class as parameter check this out Passing class as parameter.
Now since you want to pass JFrame as parameter you can simply write methodName(JFrame frame), otherwise if you just want to make new JFrame you don't need to pass it but just create new one inside method:
myMethod(){
JFrame frame = new JFrame();
// Do something with it
}
So as you can see there is no need to pass an Class in other to make object of that class.
Here you can see example of how to pass JFrame as parameter and make new JFrame:
public void jframe() {
JFrame frame = new JFrame("Frame 1");
JButton btn = new JButton("Click Me");
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
jframeAsParam(new JLabel("You added label to old JFrame"), frame);
//makeNewJFrame(new JLabel("You opened new JFrame"));
}
};
btn.addActionListener(al);
JPanel panel = new JPanel(new GridLayout(2, 1));
panel.add(btn);
frame.setContentPane(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 250);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void jframeAsParam(JLabel lbl, JFrame frame) {
frame.getContentPane().add(lbl);
frame.setVisible(true);
}
public void makeNewJFrame(JLabel lbl) {
JFrame frame = new JFrame("Frame 2");
JPanel panel = new JPanel(new BorderLayout());
panel.add(lbl, BorderLayout.CENTER);
frame.setContentPane(panel);
frame.setSize(300, 250);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
Uncomment makeNewJFrame(new JLabel("You opened new JFrame")); to see how opening new JFrame works.
c ma = new c();
First of all class names should:
Start with an upper case character
Be descriptive
i want to pass a JFrame as parameter in a method, is it possible to do that ?
There is no need to pass the frame as a parameter you can access the current frame by using code like:
Component component = (Component)evt.getSource();
Window window = SwingUtilities.windowForComponent( component );
window.setVisible( false );

I've created a basic GUI but buttons won't interact with textfield

I've been working on creating a simple GUI through the use of JPanels. I've managed to what I believe fluke a reasonably looking layout and now I would like the user to be able to input values into the Mass textbox and the Acceleration textbox so when they hit calculate they are given a message telling them the Force.
The issue I am having is within the public void that is added to the buttons, I can't seem to figure out how to refer to values within the text field. I've tried to just refer to it generally by:
String mass = txts[1].getText();
However this doesn't recognise txts as existing?
Any help on this would be much appreciated.
Below is the full code in case it helps.
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.event.*;
import java.awt.*;
public class InitScreen {
public static void createHomeScreen() {
/*Creates a Java Frame with the Window Name = HomeScreen*/
JFrame frame = new JFrame("HomeScreen");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.getContentPane().setPreferredSize(new Dimension(400,300));
frame.pack();
/*Creates the main JPanel in form of GridLayout*/
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.setBorder(new EmptyBorder(new Insets(20,20,20,20)));
/*Creates the first sub panel*/
JPanel firstPanel = new JPanel();
firstPanel.setLayout(new GridLayout(1,2,75,100));
firstPanel.setMaximumSize(new Dimension(300,100));
/*Creates the buttons in the first sub panel*/
JButton[] btns = new JButton[2];
String bText[] = {"Calculate", "Clear"};
for (int i=0; i<2; i++) {
btns[i] = new JButton(bText[i]);
btns[i].setPreferredSize(new Dimension(100, 50));
btns[i].setActionCommand(bText[i]);
btns[i].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String choice = e.getActionCommand();
/*JOptionPane.showMessageDialog(null, "Clicked "+choice);*/
JOptionPane.showMessageDialog(null, "Force = ");
}
});
firstPanel.add(btns[i]);
}
/*Creates the second sub panel*/
JPanel secondPanel = new JPanel();
secondPanel.setLayout(new BorderLayout());
/*Creates the labels for the second sub panel*/
JLabel label = new JLabel("Calculate the Force of an Object", SwingConstants.CENTER);
secondPanel.add(label,BorderLayout.NORTH);
/*Creates the third sub Panel for entering values*/
JPanel thirdPanel = new JPanel();
thirdPanel.setLayout(new GridLayout(3,1,10,10));
thirdPanel.setMaximumSize(new Dimension(400,100));
/*Create labels and text fields for third sub panel*/
String lText[] = {"Mass of Body", "Acceleration of Body", "Force"};
JLabel[] lbls = new JLabel[3];
JTextField[] txts = new JTextField[3];
for (int i=0; i<3; i++) {
txts[i] = new JTextField();
lbls[i] = new JLabel(lText[i], SwingConstants.LEFT);
lbls[i].setPreferredSize(new Dimension(50, 50));
thirdPanel.add(lbls[i]);
thirdPanel.add(txts[i]);
}
mainPanel.add(secondPanel);
mainPanel.add(thirdPanel);
mainPanel.add(firstPanel);
frame.setContentPane(mainPanel);
frame.setVisible(true);
}
public static void main(final String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createHomeScreen();
}
});
}
}
First drop the reliance on static, and instead, create an instance of InitScreen and call it's createHomeScreen method
public class InitScreen {
public void createHomeScreen() {
//...
}
public static void main(final String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
InitScreen screen = new InitScreen();
screen.createHomeScreen();
}
});
}
Now, make txts and instance field of InitScreen and use it within your methods
public class InitScreen {
private JTextField[] txts;
public void createHomeScreen() {
//...
txts = new JTextField[3];
//...
}
This takes txts from a local context to a class instance context, meaning you can now access it from any method within InitScreen

JScrollPane does not work on JPanel

I have a frame that contains a mainPanel. This last will add other commandPanels (each one contains a button and a textField) Dynamically. the problem is that the JScrollPane does not appear to let me use the unseen commandPanels even if the mainPanel is full.
The below picture shows my case.
To initialize the window I wrote below code:
frame = new JFrame();
frame.setBounds(100, 100, 962, 639);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
mainPanel = new JPanel();
mainPanel.setBounds(264, 6, 692, 500);
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
scroll = new JScrollPane();
scroll.getViewport().add(mainPanel);
frame.getContentPane().add(scroll);
and the method that add dynamically the new commandPanels is:
public void loadCommandPanel(String commandName)
{
CommandPanel newCommandPanel = new CommandPanel();
newCommandPanel.getCommandBtn().setText(commandName);
mainPanel.add(newCommandPanel);
scroll.getViewport().add( newCommandPanel );
mainPanel.add( scroll, BorderLayout.EAST);
frame.add( mainPanel);
...
}
Any help to get the scrollPane, will be much more than appreciated.
scroll.getViewport().add(mainPanel); is not how you use JViewport or JScrollPane; instead you should using something like this:
scroll.getViewport().setView(newCommandPanel);
or
scroll.setViewportView(newCommandPanel);
Take a look at How to Use Scroll Panes for more details.
Note also, this doesn't makes sense:
CommandPanel newCommandPanel = new CommandPanel();
newCommandPanel.getCommandBtn().setText(commandName);
mainPanel.add(newCommandPanel);
scroll.getViewport().add( newCommandPanel );
You add newCommandPanel to mainPanel, then promptly add it to another container (albeit incorrectly).
A component can only reside on a single parent; the moment you add it to another container, it is automatically removed from the previous container.
I have made some changes and it works perfectly now. For those who want the same thing here's my code:
import ...
public class mainUserInterface {
private JFrame frame;
private JPanel mainPanel;
private JPanel commandsPanel;
private JScrollPane commandsScrollPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainUserInterface window = new mainUserInterface();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public mainUserInterface() {
initialize();
}
private void initialize() {
frame = new JFrame("CommandsExecutor");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(1000, 700));
mainPanel = new JPanel(new BorderLayout(5,5));
mainPanel.setBorder( new TitledBorder("") );
commandsPanel = new JPanel();
commandsPanel.setLayout(new BoxLayout(commandsPanel, BoxLayout.Y_AXIS));
for(int i=0; i<15;i++){
commandsPanel.add(new CommandPanel());
}
commandsScrollPane = new JScrollPane(commandsPanel);
mainPanel.add(commandsScrollPane,BorderLayout.CENTER);
frame.setContentPane(mainPanel);
frame.pack();
frame.setVisible(true);
}
}
and Here's the commandPanel class:
import ...
public class CommandPanel extends JPanel {
private JTextField commandResult;
private JButton commandBtn;
public CommandPanel()
{
this.setLayout( new BorderLayout(10,10));
this.setBorder( new TitledBorder("Command:") );
this.setMaximumSize(new Dimension(692,60));
this.setMinimumSize(new Dimension(692,60));
commandBtn = new JButton("Execute");
commandBtn.setMaximumSize(new Dimension(137, 34));
commandBtn.setMinimumSize(new Dimension(137, 34));
this.add(commandBtn, BorderLayout.WEST);
commandResult = new JTextField();
commandResult.setMaximumSize(new Dimension(518, 34));
commandResult.setMinimumSize(new Dimension(518, 34));
this.add(commandResult, BorderLayout.CENTER);
}
public JTextField getCommandResult() {
return commandResult;
}
public JButton getCommandBtn() {
return commandBtn;
}
public void setCommandResult(JTextField commandResult) {
this.commandResult = commandResult;
}
public void setCommandBtn(JButton commandBtn) {
this.commandBtn = commandBtn;
}
}
Thanks for all who answered my question, it really helped.

Categories

Resources