I'm trying to learn Java (not a programmer by profession).
I'm currently working on a calendar app with Postgres backend.
My app consists of a JFrame with two JPanels. One of those Panels is a CalendarView(MonthView, WeekView, or DayView), and the other a ButtonPanel.
The ButtonPanel has a button to add a new Event to the Calendar. This button opens a JDialog for entering Event details (startDate, endDate, title, etc).
The owner of the dialog is the JFrame. The dialog is modular.
The issues I have is that when the dialog is open, if I click on the parent window, the dialog disappears. If I then move the cursor outside the main application window and back in, the dialog reappears. I was under the impression that this should not happen with a modal component.
All feedback appreciated. I made a slimmed down SSCCE:
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import java.awt.*;
public class Calendar extends JFrame {
public Calendar() {
super("Calendar");
initGUI();
}
public void initGUI() {
JPanel calendarView = new JPanel();
calendarView.setPreferredSize(new Dimension(400, 400));
calendarView.setBorder(BorderFactory.createTitledBorder(new LineBorder(Color.BLACK), "Calendar view", TitledBorder.CENTER, TitledBorder.CENTER));
JPanel buttonPanel = new ButtonPanel();
buttonPanel.setBorder(BorderFactory.createTitledBorder(new LineBorder(Color.RED), "Button panel", TitledBorder.CENTER, TitledBorder.CENTER));
buttonPanel.setPreferredSize(new Dimension(200, 400));
this.getContentPane().add(calendarView, BorderLayout.CENTER);
this.getContentPane().add(buttonPanel, BorderLayout.WEST);
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Calendar();
}
});
}
}
mport java.awt.*;
import java.awt.event.ActionListener;
import javax.swing.*;
public class ButtonPanel extends JPanel {
public ButtonPanel() {
initGui();
}
private void initGui() {
GridBagLayout gbag = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
this.setLayout(gbag);
JButton button = new JButton("Open dialog");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
new MyDialog((JFrame) ButtonPanel.this.getTopLevelAncestor());
}
});
gbag.setConstraints(button, gbc);
this.add(button);
}
}
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import java.awt.*;
public class MyDialog extends JDialog {
public MyDialog(JFrame owner) {
super(owner, "My dialog", true);
initGUI(owner);
}
private void initGUI(JFrame owner){
JOptionPane optionPane = new JOptionPane(createPanel(), JOptionPane.PLAIN_MESSAGE, JOptionPane.DEFAULT_OPTION, null, createButtons(), createButtons()[0]);
this.add(optionPane, BorderLayout.CENTER);
this.pack();
this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
this.setLocationRelativeTo(owner);
this.setVisible(true);
}
private JPanel createPanel() {
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createTitledBorder(new LineBorder(Color.BLACK), "My dialog", TitledBorder.CENTER, TitledBorder.CENTER));
return panel;
}
private JButton[] createButtons() {
JButton[] buttons = new JButton[1];
JButton button = new JButton("Exit");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event){
MyDialog.this.dispose();
}
});
buttons[0] = button;
return buttons;
}
}
Related
This class represents the button panel of a UI I have created, the second JButton named 'btnNext' doesn't display text however the first JButton does, why is this?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
public class ButtonPanel extends JPanel {
private MainPanel mainPanel;
// Buttons
private JButton btnRunTheAlgorithm = new JButton("Run the Algorithm");
public static JButton btnNext = new JButton("Next Step");
public ButtonPanel(MainPanel mainPanel) {
this.mainPanel = mainPanel;
this.setLayout(new FlowLayout());
this.add(btnRunTheAlgorithm);
this.add(btnNext);
this.btnRunTheAlgorithm.addActionListener(e -> {
Algorithm main = new Algorithm(mainPanel);
main.Run();
});
this.btnNext.setAction(new AbstractAction() {
public void actionPerformed(ActionEvent ae) {
synchronized (btnNext) {
btnNext.notify();
}
}
});
}
}
The buttons displays to the panel as on the image below:
Buttons:
I'm also not sure the AbstractAction works, so I suppose that could be the cause of the text not displaying but I have no idea why if that is the case.
I have a cardLayout in the main class that the Gui classes are added to layout via panels and when the Room1Button is pressed how would it switch the card in the main method to the Gui2 card
is this the best way to go about this any help would be apreatiated
Main Method
import javax.swing.*;
import java.awt.*;
class Main
{
CardLayout cl=new CardLayout();
GridBagConstraints gb=new GridBagConstraints();
JFrame frame=new JFrame("Frame");
JPanel panel =new JPanel();
Gui1 g1= Gui1();
Gui2 g2= Gui2();
public Main()
{
panel.setLayout(cl);
panel.add(g1, "1");
panel.add(g2, "2");
frame.add(panel);
frame.pack();
frame.setVisible(true);
cl.show(panel,"1");
//how would the actionlistner in the Gui1 class switch the layout to "2"
cl.show(panel, "2");
}
public static void main(String[]param)
{
new Main();
}
}
The gui1 class
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
public class Gui1 extends JPanel implements ActionListener{
private JButton room1Button;
JPanel panel=new JPanel();
{
setSize(1000,1000);
panel.setVisible(true);
room1Button=new JButton("Go the next Panel");
this.setVisible(true);
room1Button.addActionListener(this);
add(room1Button);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==room1Button){
Window w = SwingUtilities.getWindowAncestor(R0.this);
w.setVisible(false);
}
}
}
The Gui2 class
public class Gui2 extends JPanel implements Actionlistener
{
// some code
}
The ActionEvent will contain the source object that generated the event. In this case the JButton. So generic code for the ActionListener in your GUI1 class would be something like:
JButton button = (JButton)e.getSource();
JPanel buttonPanel = (JPanel)button.getParent();
JPanel cardLayoutPanel = (JPanel)buttonPanel.getParent();
CardLayout layout = (CardLayout)cardLayoutPanel.getLayout();
layout.show(cardLayoutPanel, "2");
Hope this helps.
package cardlayoutsample;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CardLayoutSample {
JFrame frame = new JFrame("CardLayout Demo");
JPanel panelCont = new JPanel();
JPanel panelFirst = new JPanel();
JPanel panelSecond = new JPanel();
JButton btnOne = new JButton("Switch");
JButton btnTwo = new JButton("Back");
CardLayout cl = new CardLayout();
public CardLayoutSample(){
panelCont.setLayout(cl);
panelFirst.add(btnOne);
panelSecond.add(btnTwo);
panelFirst.setBackground(Color.red);
panelSecond.setBackground(Color.blue);
panelCont.add(panelFirst,"1");
panelCont.add(panelSecond,"2");
cl.show(panelCont, "1");
btnOne.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0){
cl.show(panelCont, "2");
}
});
btnTwo.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0){
cl.show(panelCont, "1");
}
});
frame.add(panelCont);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public static void main(String[] args) {
CardLayoutSample a = new CardLayoutSample();
}
}
Try to play this button you can see it's switching the panels when you clicked the buttons.
Syntax for ActionListener
Component.addActionListener(new ActionListener (){
#Override
public void actionPerformed(ActionEvent e){
//do this
}
});
Example
LogoutButton.addActionListener(new ActionListener (){
#Override
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
I want to keep my Controller panel as type JPanel as I will be incorporating into a tab later, I want to swap between Main and NextPage using buttons on those specific screens, I don't want to have consistent buttons on the bottom for both screens that switch between cards(i.e I don't want to have add & back to be appearing on both screens), I am trying to get the add button in Main to go to NextPage and back button in NextPage to go to Main. This is what I have so far:
For Controller:
import java.awt.CardLayout;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Controller extends JPanel {
private static Controller instance = new Controller();
JPanel cards;
Main mainPanel;
NextPage nextPage;
public Controller() {
setLayout(new BorderLayout());
setSize(810, 510);
cards = new JPanel(new CardLayout());
mainPanel = new Main();
nextPage = new NextPage();
cards.add(mainPanel, "Main");
cards.add(nextPage, "Next");
add(cards);
setVisible(true);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("MainPanel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Controller con = new Controller();
frame.getContentPane().add(con);
frame.setSize(800, 600);
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public void changeCard(String card) {
CardLayout cl = (CardLayout) (cards.getLayout());
cl.show(cards, card);
}
public static Controller getInstance() {
return instance;
}
}
For main:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
public class Main extends JPanel implements ActionListener {
private JButton search, add, delete;
private JTextField textField;
public Main() {
search = new JButton("Search");
add = new JButton("Add");
delete = new JButton("Delete");
textField = new JTextField(20);
add.addActionListener(this);
delete.addActionListener(this);
setLayout(new BorderLayout());
JPanel top = new JPanel();
top.add(search);
add(top, BorderLayout.NORTH);
JPanel bottom = new JPanel();
bottom.add(add);
bottom.add(delete);
add(bottom, BorderLayout.SOUTH);
setVisible(true);
setSize(400, 500);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == add) {
Controller.getInstance().changeCard("Next");
} else if (e.getSource() == delete) {
System.out.println("do something");
}
}
}
For NextPage:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
public class NextPage extends JPanel implements ActionListener {
private JButton back;
private JTextField textField;
public NextPage() {
back = new JButton("Back");
textField = new JTextField(20);
back.addActionListener(this);
setLayout(new BorderLayout());
add(back);
setVisible(true);
setSize(400, 500);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == back) {
Controller.getInstance().changeCard("Next");
}
}
}
Check out Card Layout Actions.
It is an extension of CardLayout that provides you with Previous/Next buttons that you can easily add to a panel separate from the CardLayout.
I'm in a bit of a situation here.I'm making a new program, when you click on the menu bar it opens a new window for the Licence, now here is the problem, how would I add text into that new window, here is my code for the new window:
JFrame frame = new JFrame("Licence");
frame.setSize(500,120);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
I know this is a easy question, I just can't think of the correct code for it.
You can try something like
JDialog dialog = new JDialog(your_frame_reference, "Licence");
dialog .setModal(true);
dialog .setLocationRelativeTo(null);
dialog. getContentPane().add(new JLabel(your_text);
dialog .setVisible(true);
You can use label
JFrame frame = new JFrame("Licence");
JLabel label = new JLabel("Text-Only Label");
label.setFont(new Font("Serif", Font.PLAIN, 36));
frame.add(label);
You can add text by creating JLabels like so:
JLabel label = new JLabel("Hello World");
This can then be added to your JFrame.
Try this Example
import java.awt.BorderLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestDialog {
protected static void initUI() {
JPanel pane = newPane("Label in frame");
JFrame frame = new JFrame("Title");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(pane);
frame.pack();
frame.setVisible(true);
}
public static JPanel newPane(String labelText) {
JPanel pane = new JPanel(new BorderLayout());
pane.add(newLabel(labelText));
pane.add(newButton("Open dialog"), BorderLayout.SOUTH);
return pane;
}
private static JButton newButton(String label) {
final JButton button = new JButton(label);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Window parentWindow = SwingUtilities.windowForComponent(button);
JDialog dialog = new JDialog(parentWindow);
dialog.setLocationRelativeTo(button);
dialog.setModal(true);
dialog.add(newPane("Label in dialog"));
dialog.pack();
dialog.setVisible(true);
}
});
return button;
}
private static JLabel newLabel(String label) {
JLabel l = new JLabel(label);
l.setFont(l.getFont().deriveFont(24.0f));
return l;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
initUI();
}
});
}
}
I've got a Frame (named here "MainApplication"), which mainly has a JPanel to show informations, depending on the context.
On startup, the MainApplication has an empty JPanel.
It then creates a "LoginRequest" class, which creates a simple login/password form, and send it back to the MainApplication, which displays it in its JPanel.
The "LoginRequest" class implements ActionListener, so when the user clicks on the "Login" button, it checks wheter or not the login/password is correct, and, if the user is granted, I want to unload that form, and display the main screen on the MainApplication Frame.
So, to do it, I came up with this :
public class LoginRequest implements ActionListener {
protected MainApplication owner_m = null;
public LoginRequest(MainApplication owner_p) {
owner_m = owner_p;
}
#Override
public void actionPerformed(ActionEvent event_p) {
// the user just clicked the "Login" button
if (event_p.getActionCommand().equals("RequestLogin")) {
// check if login/password are correct
if (getParameters().isUserGranted(login_l, password_l)) {
// send an ActionEvent to the "MainApplication", so as it will
// be notified to display the next screen
this.owner_m.actionPerformed(
new java.awt.event.ActionEvent(this, 0, "ShowSummary")
);
} else {
messageLabel_m.setForeground(Color.RED);
messageLabel_m.setText("Incorrect user or password");
}
}
}
}
Then, the "MainApplication" class (which extends JFrame) :
public class MainApplication extends JFrame implements ActionListener {
protected void load() {
// create the panel to display information
mainPanel_m = new JPanel();
// on startup, populate the panel with a login/password form
mainPanel_m.add(new LoginRequest(this).getLoginForm());
this.add(mainPanel_m);
}
#Override
public void actionPerformed(ActionEvent event_p) {
// show summary on request
if (event_p.getActionCommand().equals("ShowSummary")) {
// remove the previous information on the panel
// (which displayed the login form on this example)
mainPanel_m.removeAll();
// and populate the panel with other informations, from another class
mainPanel_m.add(...);
...
...
}
// and then refresh GUI
this.validate();
this.repaint();
this.pack();
}
}
When the ActionEvent is sent from the "LoginRequest" class to the "MainApplication" class, it executes the code, but at the end, nothing happens, as if the JFrame wasn't repainted.
Any ideas ?
Thanks,
The best way would be to use JDialog (main frame JFrame would be a parent component) for login form and CardLayout to switch between panels (so there is no need for removing, repainting and revalidating):
Your main form should look something like this:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MainFrame{
JFrame frame = new JFrame("Main frame");
JPanel welcomePanel = new JPanel();
JPanel workspacePanel = new JPanel();
JPanel cardPanel = new JPanel();
JButton btnLogin = new JButton("Login");
JLabel lblWelcome = new JLabel("Welcome to workspace");
CardLayout cl = new CardLayout();
LoginRequest lr = new LoginRequest(this);
public MainFrame() {
welcomePanel.add(btnLogin);
btnLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
lr.setVisible(true);
}
});
workspacePanel.add(lblWelcome);
cardPanel.setLayout(cl);
cardPanel.add(welcomePanel, "1");
cardPanel.add(workspacePanel, "2");
cl.show(cardPanel,"1");
frame.getContentPane().add(cardPanel);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setPreferredSize(new Dimension(320,240));
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String [] args){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MainFrame();
}
});
}
}
Your login form should look something like this:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginRequest extends JDialog{
/**You can add, JTextFields, JLabel, JPasswordField..**/
JPanel panel = new JPanel();
JButton btnLogin = new JButton("Login");
public LoginRequest(final MainFrame mf) {
setTitle("Login");
panel.add(btnLogin);
btnLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Put some login logic here
mf.cl.show(mf.cardPanel,"2");
dispose();
}
});
add(panel, BorderLayout.CENTER);
setModalityType(ModalityType.APPLICATION_MODAL);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
pack();
setLocationByPlatform(true);
}
}
EDIT:
Your way:
MainFrame class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MainFrame{
JFrame frame = new JFrame("Main frame");
JPanel welcomePanel = new JPanel();
JPanel workspacePanel = new JPanel();
JPanel cardPanel = new JPanel();
JButton btnLogin = new JButton("Login");
JLabel lblWelcome = new JLabel("Welcome");
LoginRequest lr = new LoginRequest(this);
public MainFrame() {
welcomePanel.add(btnLogin);
btnLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
lr.setVisible(true);
}
});
workspacePanel.add(lblWelcome);
frame.getContentPane().add(welcomePanel);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setPreferredSize(new Dimension(320,240));
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String [] args){
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MainFrame();
}
});
}
}
LoginRequest class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class LoginRequest extends JDialog{
/**You can add, JTextFields, JLabel, JPasswordField..**/
JPanel panel = new JPanel();
JButton btnLogin = new JButton("Login");
public LoginRequest(final MainFrame mf) {
setTitle("Login");
panel.add(btnLogin);
btnLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Put some login logic here
mf.frame.getContentPane().removeAll();
mf.frame.add(mf.workspacePanel);
mf.frame.repaint();
mf.frame.revalidate();
dispose();
}
});
add(panel, BorderLayout.CENTER);
setModalityType(ModalityType.APPLICATION_MODAL);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
pack();
setLocationByPlatform(true);
}
}