I am making application, using IDEA Forms. I want to have different forms. First for login, then for displaying information from database after login. I created two different forms. First one: MenuMain and second AdminForm. After clicking a login button in MenuMain I want to open AdminForm, I tried with setContentPane and passing main panel from AdminForm, but it does not work. How to solve this?
public class MenuMainForm extends JFrame implements ActionListener {
private JPanel panel1;
private JTextPane logowanieText;
private JTextField userField;
private JTextField passField;
private JButton logowanieButton;
public MenuMainForm(){
logowanieButton.addActionListener(this);
public void actionPerformed(ActionEvent e) {
AdminForm adminForm = new AdminForm();
this.setContentPane(adminForm);
}
public static void main( String[] args){
JFrame menuFrame = new JFrame("Kawiarnia");
menuFrame.setContentPane(new MenuMainForm().panel1);
menuFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menuFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
menuFrame.setVisible(true);
}
And the AdminForm Code:
public class AdminForm extends JPanel{
private JPanel adminPanel;
private JButton infoKawiarniaButton;
private JTable tabelaInfo;
private static String QUERY_INFO = "SELECT * FROM NATALIAGAZDA.KAWIARNIE ";
public AdminForm() {
DefaultTableModel model = (DefaultTableModel) tabelaInfo.getModel();
model.addRow(new Object[]{"Atrybut", "Wartosc"});
public JPanel getAdminPanel() {
return adminPanel;
}
Related
I'm a little confused about where the best class is for ActionListener instances in a small Swing application.
If I have a Controller, a MainFrame for the main JFrame and various JPanel containers such as LeftPanel, RightPanel etc, each with buttons, a list etc.
Where's the best place to put the action listeners? Should I have them in the same class as the components (as an inner class or class implementing action listener), in the MainFrame as this is the 'parent' of all the panels, or in the Controller, which really only has the main() method and a few other Swing details?
Each approach seems to have its pros and cons. I am trying to un-couple features from functionality but I'm finding it hard to work this out.
Or have I missed another (better) way?
One possible for the panels to communicate with each other is through the main frame. Each panel would have a reference to the main frame and the main frame provides all the operations such as reading data from the form, updating data to the form. Below is an example:
class UserForm extends JPanel {
private final MyApp app;
private final JTextField userNameField = new JTextField(20);
public UserForm(MyApp app){
this.app = app;
this.add(userNameField);
}
public String getUserName(){
return userNameField.getText();
}
public void setUserName(String name){
userNameField.setText(name);
}
}
class FormControl extends JPanel {
private final MyApp app;
private final JButton randNameButton = new JButton("Random");
private final JButton saveButton = new JButton("Save");
private final String[] names = {"john", "mike", "bill", "joe"};
private final Random r = new Random();
public FormControl(MyApp app){
this.app = app;
this.setLayout(new FlowLayout());
this.add(randNameButton);
this.add(saveButton);
randNameButton.addActionListener(e->app.setUserName(names[r.nextInt(4)]));
saveButton.addActionListener(e->app.save());
}
}
public class MyApp extends JFrame{
private final UserForm form = new UserForm(this);
private final FormControl control = new FormControl(this);
public MyApp(){
this.setTitle("Demo");
this.setSize(200, 100);
JPanel pane = new JPanel();
pane.setSize(200,100);
pane.setLayout(new BorderLayout());
pane.add(form, BorderLayout.NORTH);
pane.add(control, BorderLayout.SOUTH);
this.setContentPane(pane);
}
// all the operations are here.
public String getUserName(){
return form.getUserName();
}
public void setUserName(String userName){
form.setUserName(userName);
}
public void save(){
System.out.println("Saving");
System.out.println(getUserName());
System.out.println("Done saving.");
}
public static void main(String[] args) {
new MyApp().setVisible(true);
}
}
I would use lambda for action listener. See example below:
public class JavaApplication7 extends JFrame{
public JavaApplication7(){
this.setTitle("Demo");
this.setSize(100, 100);
JButton b = new JButton("Click");
b.addActionListener(e->{
System.out.println("hello");
System.out.println("from " + this.getTitle());
});
this.setContentPane(b);
}
public static void main(String[] args) {
new JavaApplication7().setVisible(true);
}
}
This is my code:
package saaaaaaaaaa;
public class xd {
public static JFrame frame = new JFrame("Halo");
public static JLabel lab = new JLabel("learning ",JLabel.CENTER);
public static JButton but = new JButton("but");
public static JButton but1 = new JButton("butt");
public static CustomAct act = new CustomAct(lab);
public static void main(String[] args) {
but.addMouseListener(act);
but1.addMouseListener(act);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(640, 480);
frame.setLayout(new BorderLayout());
frame.setResizable(false);
frame.add(lab, BorderLayout.CENTER);
frame.add(but, BorderLayout.SOUTH);
frame.add(but1, BorderLayout.NORTH);
}
}
This is extra class for mouse click, I need 2x mouse click for 2 buttons.
package saaaaaaaaaa;
public class CustomAct implements MouseListener {
private static final long serialVersionUID = 1L;
private String halo = "this is ";
private int getClickCount = 1;
private JLabel lab;
private JLabel lab1;
public CustomAct(JLabel lab) {
this.lab = lab;
}
public void mouseClicked(MouseEvent e) {
if(e.getSource()==but) {
lab.setText("cau"+getClickCount++);
}
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
}
How can I do a multiple buttons for each different mouse click action?
How can I get ID of button, which is used?
This is if(e.getSource()==but) --- but cannot be resolved to a variable
I really don't know how to do it.
First of all you don't use a MouseListener to listen for clicks on a button.
Instead you should be using an ActionListener.
If the Action for each button is unrelated, then you need to create a separate ActionListener for each button with each ActionListener containing the specific code for the button. For example the "Add" and "Subtract" methods of a simple calculator would require a separate Action.
If the Action is related, then you would create a generic ActionListener that can be shared by the buttons. For example, entering digits 0, 1, 2, ... could be a shared ActionListener. For a working example of this approach check out: How to add a shortcut key for a jbutton in java?
Also, you should NOT be using static variables. Instead you should be create a class that extends a JPanel where you define all your variables and Swing components. The ActionListeners would also be defined in that class so they can update the labels as required.
So I'm new to programming and I've been making a program that uses multiple JPanels on a JFrame and other JPanels. I'm using CardLayout to go between different JPanels and I have it working on two different JButtons, but I can't get the last one to return to the main screen.
I've looked for answers, but it seems like most people just forget to use an ActionListener, something that I know I've done. Here's some of the involved classes in my code (There are a lot so I won't include them all, but I can provide any others that are needed).
Here's the JFrame class:
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.*;
public class ElephantCare extends JFrame {
private static final long serialVersionUID = 1L;
private final String MAIN_STRING = "Main";
public JPanel container, main;
private Staff1Panel staff1 = new Staff1Panel();
private Staff2Panel staff2 = new Staff2Panel();
private StaffConfirmPanel staffConfirm = new StaffConfirmPanel();
private WelcomePanel welcome = new WelcomePanel();
private StaffPanel staff = new StaffPanel();
private GallonsPanel gallons = new GallonsPanel();
private ToysPanel toys= new ToysPanel();
private ActionPanel action = new ActionPanel();
public CardLayout card = new CardLayout();
public ElephantCare() {
setSize(400,300);
setTitle("Elephant Care");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
add(container);
setVisible(true);
}
private void buildPanel() {
main = new JPanel();;
container = new JPanel(card);
container.add(main, MAIN_STRING);
container.add(staff1, "Staff 1");
container.add(staff2, "Staff 2");
main.setLayout(new BorderLayout());
main.add(welcome, BorderLayout.NORTH);
main.add(staff, BorderLayout.WEST);
main.add(gallons, BorderLayout.CENTER);
main.add(toys, BorderLayout.EAST);
main.add(action, BorderLayout.SOUTH);
staff.getStaff1Button().addActionListener(new Staff1Listener());
staff.getStaff2Button().addActionListener(new Staff2Listener());
staffConfirm.getConfirmButton().addActionListener(new ConfirmButtonListener());
}
private class Staff1Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
card.show(container, "Staff 1");
}
}
private class Staff2Listener implements ActionListener {
public void actionPerformed(ActionEvent e) {
card.show(container, "Staff 2");
}
}
private class ConfirmButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
card.show(container, MAIN_STRING);
}
}
}
Here's the JPanel with the Button:
import javax.swing.*;
public class StaffConfirmPanel extends JPanel{
private static final long serialVersionUID = 1L;
public JButton confirm;
public StaffConfirmPanel() {
confirm = new JButton("OK");
add(confirm);
}
public JButton getConfirmButton() {
return confirm;
}
}
And here's the JPanels where the button is used:
import java.awt.BorderLayout;
import javax.swing.*;
public class Staff1Panel extends JPanel{
private static final long serialVersionUID = 1L;
private Staff1NamePanel name = new Staff1NamePanel();
private Staff1JobPanel job = new Staff1JobPanel();
private StaffConfirmPanel confirm = new StaffConfirmPanel();
public Staff1Panel() {
setLayout(new BorderLayout());
add(name, BorderLayout.WEST);
add(job, BorderLayout.EAST);
add(confirm, BorderLayout.SOUTH);
}
}
And:
import java.awt.BorderLayout;
import javax.swing.*;
public class Staff2Panel extends JPanel{
private static final long serialVersionUID = 1L;
private Staff2NamePanel name = new Staff2NamePanel();
private Staff2JobPanel job = new Staff2JobPanel();
private StaffConfirmPanel confirm = new StaffConfirmPanel();
public Staff2Panel() {
setLayout(new BorderLayout());
add(name, BorderLayout.WEST);
add(job, BorderLayout.EAST);
add(confirm, BorderLayout.SOUTH);
}
}
Thanks for any help!
There are a lot of things happening in this code that are not quite right, and they contribute to your issue. So lets address the biggest issue and then you will need to do the rest yourself.
First edit this code to have some debug text:
private class ConfirmButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
//NEW LINE OF CODE
System.out.println("ConfirmButtonListener was triggered");
card.show(container, MAIN_STRING);
}
}
Now when you run your code you will notice that the message "ConfirmButtonListener was triggered" will never be printed to the console, meaning that the code never runs, so you can never return to the main screen.
This happens because you create a StaffConfirmPanel named staffConfirm in your ElephantCare class. Then you add an action listener to staffConfirm. The problem is that you never use that staffconfirm panel anywhere because you create a new StaffConfirmPanel inside Staff1Panel and Staff2Panel so the action listener you have made will do nothing.
So the solution is to move the whole ConfirmButtonListener method and the staffConfirm.getConfirmButton().addActionListener line into the StaffConfirmPanel class like so:
import javax.swing.*;
public class StaffConfirmPanel extends JPanel{
private static final long serialVersionUID = 1L;
public JButton confirm;
public StaffConfirmPanel() {
confirm = new JButton("OK");
add(confirm);
//NEW LINE: SET THE ACTION LISTENER
confirm.addActionListener(new ConfirmButtonListener());
}
public JButton getConfirmButton() {
return confirm;
}
//NEW CODE, MOVE THE ACTION LISTENER METHOD HERE
//ACTION LISTENER MOVED HERE
private class ConfirmButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
//NEW LINE OF CODE
System.out.println("ConfirmButtonListener was triggered");
card.show(ElephantCare.container, ElephantCare.MAIN_STRING);
}
}
}
Now it should work correctly and return to the main screen.
EDIT: you will need to make MAIN_STRING a public variable in the ElephantCare class.
I have two jFrames: Frame1 and Frame2.
Frame1 has a jComboBox and a jButton; Frame2 has just a jButton.
Frame1 can open Frame2.
I have this code on Frame 1:
public class Frame1 extends javax.swing.JFrame {
public void addTextToComboBox(){
this.jComboBox1.removeAllItems();
this.jComboBox1.addItem("Hello");
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
this.addTextToComboBox();
}
}
It works fine: The "Hello" string is added to the jComboBox when i click the jButton.
Now I have this code on Frame2:
public class Frame2 extends javax.swing.JFrame {
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Frame1 frame1=new Frame1();
frame1.addTextToComboBox();
}
}
This way, the "Hello" string is not added to the jComboBox on Frame1 when i click on the jButton on Frame2.
Why? Could someone get me a solution please?
Thanks in advance.
Because you are trying to add string to another instance of jComboBox on Frame1 that is not showing now.
If you want to add string to jComboBox that is showing now, you need to pass the object of Frame1 to Frame2 then call addTextToComboBox();.
Example:
One of the way you can write your Frame2 class as
public class Frame2 extends javax.swing.JFrame {
Frame1 frame1;
public Frame2(Frame1 frame1) {
this.frame1 = frame1;
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
frame1 = new Frame1();
frame1.addTextToComboBox();
}
}
And using it
public static void main(String[] args) {
Frame1 f1 = new Frame1();
Frame2 f2 = new Frame2(f);
}
You can read Object-Oriented Programming Concepts for better understanding of OOP concept.
First I have a GUI (gui1), when I press a button, a different GUI (gui2) is created. My question is: How I can get access to elements from gui2, using methods from gui1?
Example: When I press a button from gui1, I want to QuesHandText.setText(myVector[0]); QuesHandText is a JTextField from gui1 and myVector[0] a var from gui2. The result error message: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
When I press Ok from Gui2 , I want to setText for the JTextField on Gui1
http://img72.imageshack.us/img72/2822/36185233.png
//imports
public class Gui extends JFrame{
public JButton Simulate, Particular, Start, HandSelection;
public JTextField QuesHandText, FlopTurnRiverText, RezultatText;
public Gui g;
public Gui()
{
QuesHandText = new JTextField(4);
//instruct
ClassParticular handler1 = new ClassParticular();
Particular.addActionListener(handler1);
}
public Gui(String t)
{
//instruct
myVector[0]="some_string";
myVector[1]="some_string2";
}
public class ClassParticular implements ActionListener{
public void actionPerformed(ActionEvent event){
//instruc
HandSelection hs = new HandSelection();
HandSelection.addActionListener(hs);
StartClass hndlr = new StartClass();
Start.addActionListener(hndlr);
add(HandSelection);
add(Start);
}
}
public class HandSelection implements ActionListener{
public void actionPerformed(ActionEvent e){
g = new Gui("Hand selection");
g.setVisible(true);
g.setSize(1135,535);
g.setDefaultCloseOperation(HIDE_ON_CLOSE);
g.setResizable(false);
}
}
public class StartClass implements ActionListener{
public void actionPerformed(ActionEvent event){
QuesHandText.setText(myVector[0]); // THE PROBLEM IS HERE, I KNOW IT !!
}
}
}
You have two constructors of Gui.
public Gui()
And
public Gui(String t)
You have initialized QuesHandText in the first one, but not in the second one.
If you use the second one to initialize the Gui you are supposed to get a NullPointerException.
I think you should do this in constructors:
[Edited as suggested by Kleopetra]
public Gui(){
this("");
}
public Gui(String t){
//instruct (I am not sure what it means)
quesHandText = new JTextField(4);
classParticular handler1 = new ClassParticular();
particular.addActionListener(handler1);
myVector = new String[2]; // or some other size you need.
myVector[0]="some_string";
myVector[1]="some_string2";
}
1.your problem is
public class Gui extends Jframe{
that should be
public class Gui extends JFrame{
2.another problems are
public JButton Simulate, Particular, Start, HandSelection;
public JTextField QuesHandText, FlopTurnRiverText, RezultatText;
public Gui g;
remove JButton and JTextField because they are JComponents and API names
or declare JButton and JTextField correctly
.
public JButton myButton, ...
public JTextField myTextField, ...
3.don't extends JFrame create that as local variable
4.don't re_create a new GUI from ActionPerformed use CardLayout