I have made a parentPanel that has a CardLayout on it, and under this I've made 4 more JPanel containers.
On the left side I have 4 buttons that when I press "Forside" (button) I want to switch to the panel on the card layout (Forside) and so on...
I've tried different youtube tutorials and tried to look on here without any success.
Everything I have tried has ended up with a NullPointerException
public class Main extends JFrame {
private JPanel contentPane;
int xx, xy;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setUndecorated(true); // Hides the jframe top bar
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 735, 506);
contentPane = new JPanel();
contentPane.setBackground(new Color(102, 102, 102));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panelLeft = new JPanel();
panelLeft.setBackground(new Color(51, 51, 51));
panelLeft.setForeground(Color.DARK_GRAY);
panelLeft.setBounds(0, 54, 150, 459);
contentPane.add(panelLeft);
panelLeft.setLayout(null);
JButton btnForside = new JButton("Forside");
btnForside.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
btnForside.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnForside.setForeground(Color.WHITE);
btnForside.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnForside.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Home_32px_1.png")));
btnForside.setContentAreaFilled(false);
btnForside.setBorderPainted(false);
btnForside.setBorder(null);
btnForside.setBounds(16, 60, 112, 30);
panelLeft.add(btnForside);
JButton btnDagbog = new JButton("Dagbog");
btnDagbog.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnDagbog.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnDagbog.setContentAreaFilled(false);
btnDagbog.setBorderPainted(false);
btnDagbog.setBorder(null);
btnDagbog.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnDagbog.setForeground(Color.WHITE);
btnDagbog.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Book_32px.png")));
btnDagbog.setBounds(16, 116, 112, 30);
panelLeft.add(btnDagbog);
JButton btnAftaler = new JButton("Aftaler");
btnAftaler.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnAftaler.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnAftaler.setContentAreaFilled(false);
btnAftaler.setBorderPainted(false);
btnAftaler.setBorder(null);
btnAftaler.setForeground(Color.WHITE);
btnAftaler.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnAftaler.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Planner_32px.png")));
btnAftaler.setBounds(16, 173, 112, 30);
panelLeft.add(btnAftaler);
JButton btnKontakt = new JButton("Kontakt");
btnKontakt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
btnKontakt.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnKontakt.setContentAreaFilled(false);
btnKontakt.setBorder(null);
btnKontakt.setBorderPainted(false);
btnKontakt.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnKontakt.setForeground(Color.WHITE);
btnKontakt.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Phone_32px.png")));
btnKontakt.setBounds(16, 231, 112, 30);
panelLeft.add(btnKontakt);
JPanel panelTop = new JPanel();
panelTop.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent arg0) {
int x = arg0.getXOnScreen(); // makes uggerhøj picture dragable
int y = arg0.getYOnScreen(); // makes uggerhøj picture dragable
Main.this.setLocation(x - xx, y - xy); // makes uggerhøj picture dragable
}
});
panelTop.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
xx = e.getX(); // makes uggerhøj picture dragable
xy = e.getY(); // makes uggerhøj picture dragable
}
});
panelTop.setBackground(new Color(51, 51, 51));
panelTop.setBounds(0, 0, 737, 60);
contentPane.add(panelTop);
panelTop.setLayout(null);
JButton btnX = new JButton("X");
btnX.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnX.setRolloverIcon(null);
btnX.setFont(new Font("Tahoma", Font.BOLD, 18));
btnX.setFocusTraversalKeysEnabled(false);
btnX.setFocusPainted(false);
btnX.setBorderPainted(false);
btnX.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
btnX.setContentAreaFilled(false);
btnX.setForeground(SystemColor.activeCaption);
btnX.setBorder(null);
btnX.setBounds(615, 13, 97, 25);
panelTop.add(btnX);
JPanel parentPanel = new JPanel();
parentPanel.setBackground(Color.GRAY);
parentPanel.setBounds(148, 54, 569, 405);
contentPane.add(parentPanel);
parentPanel.setLayout(new CardLayout(0, 0));
JPanel Forside = new JPanel();
parentPanel.add(Forside, "name_1472174211097300");
Forside.setFocusable(false);
JButton btnTest = new JButton("test");
Forside.add(btnTest);
JPanel Dagbog = new JPanel();
parentPanel.add(Dagbog, "name_1472176236196000");
JLabel lblTest = new JLabel("dagbog");
Dagbog.add(lblTest);
JPanel Aftaler = new JPanel();
parentPanel.add(Aftaler, "name_1472177885026100");
JPanel Kontakt = new JPanel();
parentPanel.add(Kontakt, "name_1472179607862700");
}
}
I'd just want it so the right buttons leads to the right cards.
first of all please next time take #AndrewThompson advise about making a MCVE of your code and #camickr advise about the test and debug in little steps before going to the real code (this is the expert programming 101).
the CardLayout object switches between the content of the container via the method
CardLayout.show(Container parent, String name);
keep in mind when making navigation in your swing code DO-NOT make your Components fields in a method instead make it local variables (at least in your case the parentPanel and the CardLayout)
so in order to make your parentPanel switch between your 4 panels (sorry am not familiar with your language) i did a fairly refactored version of your code .
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
public class Main extends JFrame {
private JPanel contentPane;
int xx, xy;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main frame = new Main();
frame.setUndecorated(true); // Hides the jframe top bar
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 735, 506);
contentPane = new JPanel();
contentPane.setBackground(new Color(102, 102, 102));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel Forside = new JPanel();
JPanel Dagbog = new JPanel();
JPanel Aftaler = new JPanel();
JPanel Kontakt = new JPanel();
JPanel panelLeft = new JPanel();
panelLeft.setBackground(new Color(51, 51, 51));
panelLeft.setForeground(Color.DARK_GRAY);
panelLeft.setBounds(0, 54, 150, 459);
contentPane.add(panelLeft);
panelLeft.setLayout(null);
JButton btnForside = new JButton("Forside");
btnForside.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
setCardLayoutView("name_1472174211097300");
}
});
btnForside.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnForside.setForeground(Color.WHITE);
btnForside.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnForside.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Home_32px_1.png")));
btnForside.setContentAreaFilled(false);
btnForside.setBorderPainted(false);
btnForside.setBorder(null);
btnForside.setBounds(16, 60, 112, 30);
panelLeft.add(btnForside);
JButton btnDagbog = new JButton("Dagbog");
btnDagbog.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setCardLayoutView("name_1472176236196000");
}
});
btnDagbog.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnDagbog.setContentAreaFilled(false);
btnDagbog.setBorderPainted(false);
btnDagbog.setBorder(null);
btnDagbog.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnDagbog.setForeground(Color.WHITE);
btnDagbog.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Book_32px.png")));
btnDagbog.setBounds(16, 116, 112, 30);
panelLeft.add(btnDagbog);
JButton btnAftaler = new JButton("Aftaler");
btnAftaler.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setCardLayoutView("name_1472177885026100");
}
});
btnAftaler.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnAftaler.setContentAreaFilled(false);
btnAftaler.setBorderPainted(false);
btnAftaler.setBorder(null);
btnAftaler.setForeground(Color.WHITE);
btnAftaler.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnAftaler.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Planner_32px.png")));
btnAftaler.setBounds(16, 173, 112, 30);
panelLeft.add(btnAftaler);
JButton btnKontakt = new JButton("Kontakt");
btnKontakt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setCardLayoutView("name_1472179607862700");
}
});
btnKontakt.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnKontakt.setContentAreaFilled(false);
btnKontakt.setBorder(null);
btnKontakt.setBorderPainted(false);
btnKontakt.setFont(new Font("Tahoma", Font.PLAIN, 17));
btnKontakt.setForeground(Color.WHITE);
btnKontakt.setIcon(new ImageIcon(Main.class.getResource("/Images/icons8_Phone_32px.png")));
btnKontakt.setBounds(16, 231, 112, 30);
panelLeft.add(btnKontakt);
JPanel panelTop = new JPanel();
panelTop.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent arg0) {
int x = arg0.getXOnScreen(); // makes uggerhøj picture dragable
int y = arg0.getYOnScreen(); // makes uggerhøj picture dragable
Main.this.setLocation(x - xx, y - xy); // makes uggerhøj picture dragable
}
});
panelTop.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
xx = e.getX(); // makes uggerhøj picture dragable
xy = e.getY(); // makes uggerhøj picture dragable
}
});
panelTop.setBackground(new Color(51, 51, 51));
panelTop.setBounds(0, 0, 737, 60);
contentPane.add(panelTop);
panelTop.setLayout(null);
JButton btnX = new JButton("X");
btnX.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
btnX.setRolloverIcon(null);
btnX.setFont(new Font("Tahoma", Font.BOLD, 18));
btnX.setFocusTraversalKeysEnabled(false);
btnX.setFocusPainted(false);
btnX.setBorderPainted(false);
btnX.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
btnX.setContentAreaFilled(false);
btnX.setForeground(SystemColor.activeCaption);
btnX.setBorder(null);
btnX.setBounds(615, 13, 97, 25);
panelTop.add(btnX);
parentPanel = new JPanel();
parentPanel.setBackground(Color.GRAY);
parentPanel.setBounds(148, 54, 569, 405);
contentPane.add(parentPanel);
cardLayoutObject = new CardLayout(0, 0);
parentPanel.setLayout(cardLayoutObject);
parentPanel.add(Forside, "name_1472174211097300");
Forside.setFocusable(false);
JButton btnTest = new JButton("test");
Forside.add(btnTest);
parentPanel.add(Dagbog, "name_1472176236196000");
JLabel lblTest = new JLabel("dagbog");
Dagbog.add(lblTest);
parentPanel.add(Aftaler, "name_1472177885026100");
parentPanel.add(Kontakt, "name_1472179607862700");
}
private CardLayout cardLayoutObject;
private JPanel parentPanel;
private void setCardLayoutView(String viewName) {
cardLayoutObject.show(parentPanel, viewName);
}
}
and happy coding ^-^.
Related
I'm making a program in Java Swing and so far I only have the GUI done but that's what's giving me the problem. I have no idea why, but when my "tasks" method is activated using the button, the JComponents that are supposed to show are not shown properly. The JPanel "tasks" is supposed to be 300x300 but it doesn't look like that unless the window is minimized and reopened. The sizes are wrong and some of the JLabels are cut off too. I don't know what to do, I've tried rearranging the code so that the main GUI frame is made visible after, but that didn't work either. I've been trying to solve this problem for so long. What should I do?
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.LocalDate;
import java.util.Date;
public class gui implements ActionListener {
static JFrame frame;
Container container;
JPanel title, open, choicePanel, date, tasks, ttitle, ntes;
JLabel titleName, date1, ttitle2, rmndAt, ntes1;
Font titleFont = new Font("Lucida Handwriting", Font.PLAIN, 70);
Font clickHereFont = new Font("Lucida Handwriting", Font.PLAIN, 18);
Font stitleFont = new Font("Lucida Handwriting", Font.PLAIN, 50);
JButton openButton, tasksButton, notesButton, adtButton, tnButton;
Date datee = new Date(); //date object
{
frame = new JFrame();
frame.setSize(1000,700);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); d
frame.getContentPane().setBackground(new Color(4, 102, 69));
frame.setResizable(false);
frame.setLayout(null);
date = new JPanel();
date.setBounds(350,150,300,200);
date.setBackground(new Color(14, 21, 7));
date1 = new JLabel("Today is "+ (LocalDate.now()).toString() + " ");
date1.setForeground(new Color(135, 233, 169));
date1.setFont(clickHereFont);
title = new JPanel();
title.setBounds(170,250,650,120);
title.setBackground(new Color(135, 233, 169));
titleName = new JLabel("Daily Planner");
titleName.setForeground(new Color(14, 21, 7));
titleName.setFont(titleFont);
open = new JPanel();
open.setBounds(400,420,150,75);
open.setBackground(new Color(4, 102, 69));
openButton = new JButton("CLICK HERE");
openButton.setBounds(300,420,200,100);
openButton.setBackground(new Color(14, 21, 7));
openButton.setForeground(new Color(135, 233, 169));
openButton.setFont(clickHereFont);
openButton.addActionListener(this);
date.add(date1);
frame.add(date);
title.add(titleName);
frame.add(title);
frame.add(open);
open.add(openButton);
frame.setVisible(true);
}
public static void main(String[] args) {
new gui();
}
public gui() {
}
public void choice() {
title.setVisible(false);
open.setVisible(false);
date.setVisible(false);
choicePanel = new JPanel();
choicePanel.setBounds(160,100,650,500);
choicePanel.setBackground(new Color(135, 233, 169));
choicePanel.setLayout(new GridLayout(1,2));
tasksButton = new JButton("TASKS");
tasksButton.setBackground(new Color (6, 122, 82));
tasksButton.setFont(titleFont); //reused the "titleFont" font
tasksButton.setForeground(Color.white);
tasksButton.addActionListener(this);
notesButton = new JButton("NOTES");
notesButton.setBackground(new Color(63, 194, 131));
notesButton.setFont(titleFont);
notesButton.setForeground(Color.white);
notesButton.addActionListener(this);
choicePanel.add(tasksButton);
choicePanel.add(notesButton);
frame.add(choicePanel);
}
public void tasks() {
choicePanel.setVisible(false);
tasks = new JPanel();
tasks.setBounds(30,150,300,300);
tasks.setBackground(new Color(6, 122, 76));
ttitle = new JPanel();
ttitle.setBackground(new Color(4, 102, 69));
ttitle.setBounds(20,50,500,100);
ttitle2 = new JLabel("TASKS");
ttitle2.setBounds(50,50,150,45);
ttitle2.setBackground(new Color(4, 102, 69));
ttitle2.setForeground(Color.white);
ttitle2.setFont(stitleFont);
adtButton = new JButton("+");
adtButton.setBounds(550,50,80,80);
adtButton.setBackground(new Color(4, 102, 69));
adtButton.setForeground(Color.white);
adtButton.setFont(stitleFont);
rmndAt = new JLabel("REMIND AT");
rmndAt.setBounds(750,50,200,95);
rmndAt.setBackground(new Color(4, 102, 69));
rmndAt.setForeground(Color.white);
rmndAt.setFont(clickHereFont);
frame.add(tasks);
ttitle.add(ttitle2);
frame.add(ttitle);
frame.add(adtButton);
frame.add(rmndAt);
}
public void ntess() {
choicePanel.setVisible(false);
title.setVisible(false);
ntes = new JPanel();
ntes.setBackground(new Color(6, 122, 76));
ntes.setBounds(30,150,200,200);
frame.add(ntes);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == openButton) {
choice();
}
else if (e.getSource()==notesButton) {
ntess();
}
else if (e.getSource() == tasksButton) {
tasks();
}
}
}
I just want an answer and want to make this program work
Be very careful what you wish for...
The following makes use of the following concepts...
Creating a GUI With Swing
Laying Out Components Within a Container* How to Use CardLayout
Dependency Injection in Java
Observer Pattern
The example is also incomplete and you're going to need to take the time to understand the above concepts in order to fill out the missing parts
I also think you're going to want to have a look at How to Use Tables at some point.
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
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 NavigationPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static class Support {
public static final Font TITLE_FONT = new Font("Lucida Handwriting", Font.PLAIN, 70);
public static final Font NORMAL_FONT = new Font("Lucida Handwriting", Font.PLAIN, 18);
public static final Font SMALL_FONT = new Font("Lucida Handwriting", Font.PLAIN, 18);
}
public class NavigationPane extends JPanel {
protected enum View {
MAIN, CHOICE, NOTES, TASKS;
}
private CardLayout cardLayout;
public NavigationPane() {
cardLayout = new CardLayout();
setLayout(cardLayout);
add(new MainPane(new MainPane.Observer() {
#Override
public void navigateToChoices(MainPane source) {
navigateTo(View.CHOICE);
}
}), View.MAIN);
add(new ChoicePane(new ChoicePane.Observer() {
#Override
public void navigateToTasks(ChoicePane source) {
navigateTo(View.TASKS);
}
#Override
public void navigateToNotes(ChoicePane source) {
navigateTo(View.NOTES);
}
}), View.CHOICE);
add(new TasksPane(), View.TASKS);
add(new NotesPane(), View.NOTES);
navigateTo(View.MAIN);
}
protected void navigateTo(View view) {
cardLayout.show(this, view.name());
}
// Because I'm lazy
protected void add(Component comp, View view) {
super.add(comp, view.name());
}
}
public class MainPane extends JPanel {
public interface Observer {
public void navigateToChoices(MainPane source);
}
private Observer observer;
public MainPane(Observer observer) {
this.observer = observer;
setBorder(new EmptyBorder(32, 32, 32, 32));
setBackground(new Color(4, 102, 69));
setLayout(new GridBagLayout());
JLabel todayLabel = new JLabel("Today is " + DateTimeFormatter.ISO_LOCAL_DATE.format(LocalDate.now()));
todayLabel.setFont(Support.NORMAL_FONT);
todayLabel.setForeground(new Color(135, 233, 169));
todayLabel.setBackground(new Color(14, 21, 7));
todayLabel.setOpaque(true);
todayLabel.setBorder(new EmptyBorder(16, 16, 16, 16));
JLabel titleLabel = new JLabel("Daily Planner");
titleLabel.setFont(Support.TITLE_FONT);
titleLabel.setBackground(new Color(135, 233, 169));
titleLabel.setOpaque(true);
titleLabel.setBorder(new EmptyBorder(32, 32, 32, 32));
JButton clickHereButton = new JButton("Click Here");
clickHereButton.setFont(Support.SMALL_FONT);
clickHereButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
observer.navigateToChoices(MainPane.this);
}
});
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridy = 0;
gbc.gridwidth = gbc.REMAINDER;
gbc.insets = new Insets(8, 8, 32, 8);
add(todayLabel, gbc);
gbc.gridy++;
gbc.insets = new Insets(0, 8, 32, 8);
add(titleLabel, gbc);
gbc.gridy++;
gbc.insets = new Insets(0, 8, 8, 8);
add(clickHereButton, gbc);
}
}
public class ChoicePane extends JPanel {
public interface Observer {
public void navigateToTasks(ChoicePane source);
public void navigateToNotes(ChoicePane source);
}
private Observer observer;
public ChoicePane(Observer observer) {
this.observer = observer;
setBorder(new EmptyBorder(32, 32, 32, 32));
setBackground(new Color(4, 102, 69));
setLayout(new GridLayout(1, 2, 8, 8));
JButton tasksButton = new JButton("TASKS");
tasksButton.setOpaque(true);
tasksButton.setBorderPainted(false);
tasksButton.setBackground(new Color(63, 194, 131));
tasksButton.setFont(Support.TITLE_FONT); //reused the "titleFont" font
tasksButton.setForeground(Color.white);
tasksButton.setFocusPainted(false);
tasksButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
observer.navigateToTasks(ChoicePane.this);
}
});
JButton notesButton = new JButton("NOTES");
notesButton.setOpaque(true);
notesButton.setBorderPainted(false);
notesButton.setBackground(new Color(63, 194, 131));
notesButton.setFont(Support.TITLE_FONT);
notesButton.setForeground(Color.white);
notesButton.setFocusPainted(false);
notesButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
observer.navigateToNotes(ChoicePane.this);
}
});
add(tasksButton);
add(notesButton);
}
}
public class TasksPane extends JPanel {
public TasksPane() {
setBorder(new EmptyBorder(32, 32, 32, 32));
setBackground(new Color(4, 102, 69));
setLayout(new BorderLayout(8, 8));
JPanel titlePane = new JPanel(new GridBagLayout());
titlePane.setOpaque(false);
JLabel titleLabel = new JLabel("Tasks");
titleLabel.setBackground(new Color(4, 102, 69));
titleLabel.setForeground(Color.WHITE);
titleLabel.setFont(Support.SMALL_FONT);
JButton addButton = new JButton("+");
addButton.setBorderPainted(false);
addButton.setFocusPainted(false);
addButton.setBackground(new Color(63, 194, 131));
addButton.setForeground(Color.white);
addButton.setFont(Support.SMALL_FONT);
addButton.setOpaque(true);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.anchor = gbc.LINE_START;
titlePane.add(titleLabel, gbc);
gbc.weightx = 0;
gbc.gridx++;
titlePane.add(addButton, gbc);
add(titlePane, BorderLayout.NORTH);
// Personally, I think you need a JTable
JPanel fillerPane = new JPanel();
fillerPane.setBackground(new Color(6, 122, 76));
add(fillerPane);
}
}
public class NotesPane extends JPanel {
public NotesPane() {
setBorder(new EmptyBorder(32, 32, 32, 32));
setBackground(new Color(4, 102, 69));
setLayout(new BorderLayout(8, 8));
JPanel titlePane = new JPanel(new GridBagLayout());
titlePane.setOpaque(false);
JLabel titleLabel = new JLabel("Notes");
titleLabel.setBackground(new Color(4, 102, 69));
titleLabel.setForeground(Color.WHITE);
titleLabel.setFont(Support.SMALL_FONT);
JButton addButton = new JButton("+");
addButton.setBorderPainted(false);
addButton.setFocusPainted(false);
addButton.setBackground(new Color(63, 194, 131));
addButton.setForeground(Color.white);
addButton.setFont(Support.SMALL_FONT);
addButton.setOpaque(true);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.anchor = gbc.LINE_START;
titlePane.add(titleLabel, gbc);
gbc.weightx = 0;
gbc.gridx++;
titlePane.add(addButton, gbc);
add(titlePane, BorderLayout.NORTH);
// Personally, I think you need a JTable
JPanel fillerPane = new JPanel();
fillerPane.setBackground(new Color(6, 122, 76));
add(fillerPane);
}
}
}
Side by comparison of your output (left) and mine (right)
Beside also getting reusability for free, imagine your client comes back and says, "I want to change the font" or even worse, "I just want to change the font on these few elements".
Which approach do you think will cope better?
Or, you get some user like me, whose blind as a bat and has the font accessibility of the system ramped right up?
I am writing a simple card game GUI with a JTextArea to display what is happening and who placed which card and so on. After I finished the layout, I added a method to append the text to the JTextArea character by character, so it has a nice writing effect. I have a class for creating the window and GUI, and a class for the game and the output to the TextArea.
This works however only for initializing the game. After that the player has to choose a card by pressing a button and when he does, I call a method within the game object so that it goes on. The problem here is it waits until the actionEvent from the button press is performed and then updates the TextArea with all text that the game processed without updating it character by character. Just adding textArea.update(... after every character doesnt solve the problem because the area begins to flicker.
Here is my window class:
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.border.LineBorder;
import javax.swing.JTable;
import javax.swing.border.MatteBorder;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import javax.swing.JPanel;
import java.awt.ComponentOrientation;
public class window {
private JFrame frmStinkt;
private JLabel label;
private JTextArea textArea;
private JTable table;
private static ArrayList<JButton> buttons = new ArrayList<JButton>();
private JTextField textField;
private static WindowGame newGame;
private static int test = 0;
/**
* Launch the application.
*/
public static void main(String[] args)
{
window window = new window(104, 4);
window.frmStinkt.setVisible(true);
newGame = new WindowGame(104, 4, window.textArea, window.table);
newGame.initGame();
setButtonNames(newGame.players.get(0).cards);
window.enableButtons();
}
/**
* Create the application.
*/
public window(int numberOfCards, int numberOfRows)
{
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
Font defaultFont = new Font("Gill Sans MT",Font.BOLD,14);
frmStinkt = new JFrame();
frmStinkt.setTitle("6 STINKT!");
frmStinkt.getContentPane().setForeground(Color.GREEN);
frmStinkt.getContentPane().setFocusTraversalPolicyProvider(true);
frmStinkt.getContentPane().setBackground(Color.BLACK);
frmStinkt.setBounds(400, 200, 600, 450);
frmStinkt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmStinkt.getContentPane().setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBorder(null);
scrollPane.setBounds(83, 18, 420, 130);
frmStinkt.getContentPane().add(scrollPane);
textArea = new JTextArea();
textArea.setBorder(new LineBorder(new Color(0, 255, 0), 2, true));
textArea.setEditable(false);
scrollPane.setViewportView(textArea);
textArea.setWrapStyleWord(true);
textArea.setForeground(Color.GREEN);
textArea.setBackground(Color.BLACK);
textArea.setLineWrap(true);
textArea.setFont(new Font("Gill Sans MT", Font.BOLD, 13));
label = new JLabel("CARDS");
label.setEnabled(false);
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setForeground(Color.GREEN);
label.setBackground(Color.DARK_GRAY);
label.setFont(defaultFont);
label.setBounds(254, 264, 78, 23);
frmStinkt.getContentPane().add(label);
table = new JTable();
table.setShowVerticalLines(false);
table.setGridColor(new Color(0, 255, 0));
table.setForeground(Color.GREEN);
table.setBorder(new MatteBorder(1, 1, 1, 1, (Color) new Color(0, 255, 0)));
table.setBackground(Color.BLACK);
table.setBounds(165, 160, 255, 64);
table.setFont(new Font("Gill Sans MT", Font.BOLD, 14));
frmStinkt.getContentPane().add(table);
textField = new JTextField();
textField.setEditable(false);
textField.setForeground(new Color(0, 255, 0));
textField.setBackground(Color.DARK_GRAY);
textField.setFont(new Font("Gill Sans MT", Font.BOLD, 14));
textField.setBounds(277, 235, 32, 25);
frmStinkt.getContentPane().add(textField, BorderLayout.CENTER);
textField.setHorizontalAlignment(JTextField.CENTER);
textField.setColumns(10);
JPanel panel = new JPanel();
panel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
panel.setBackground(Color.BLACK);
panel.setBounds(10, 284, 564, 66);
frmStinkt.getContentPane().add(panel);
JButton button0 = new JButton("---");
panel.add(button0);
button0.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
button0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
button0.setVisible(false);
test = buttons.indexOf(button0);
textField.setText(Integer.toString(newGame.players.get(0).cards.get(0)));
disableButtons();
newGame.HumanTurn(test);
buttons.remove(0);
}
});
button0.setForeground(new Color(0, 255, 0));
button0.setBackground(Color.decode("#000000"));
button0.setFont(defaultFont);
button0.setOpaque(true);
button0.setRequestFocusEnabled(false);
button0.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttons.add(button0);
JButton button1 = new JButton("---");
panel.add(button1);
button1.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newGame.HumanTurn(1);
textField.setText(Integer.toString(newGame.players.get(0).cards.get(1)));
disableButtons();
panel.remove(button0);
}
});
button1.setForeground(new Color(0, 255, 0));
button1.setBackground(Color.decode("#000000"));
button1.setFont(defaultFont);
button1.setOpaque(true);
button1.setRequestFocusEnabled(false);
button1.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttons.add(button1);
JButton button2 = new JButton("---");
panel.add(button2);
button2.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newGame.HumanTurn(2);
textField.setText(Integer.toString(newGame.players.get(0).cards.get(2)));
disableButtons();
}
});
button2.setForeground(new Color(0, 255, 0));
button2.setBackground(Color.decode("#000000"));
button2.setFont(defaultFont);
button2.setOpaque(true);
button2.setRequestFocusEnabled(false);
button2.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttons.add(button2);
JButton button3 = new JButton("---");
panel.add(button3);
button3.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newGame.HumanTurn(3);
textField.setText(Integer.toString(newGame.players.get(0).cards.get(3)));
disableButtons();
}
});
button3.setRequestFocusEnabled(false);
button3.setForeground(new Color(0, 255, 0));
button3.setBackground(Color.decode("#000000"));
button3.setFont(defaultFont);
button3.setOpaque(true);
button3.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttons.add(button3);
JButton button4 = new JButton("---");
panel.add(button4);
button4.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
button4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newGame.HumanTurn(4);
textField.setText(Integer.toString(newGame.players.get(0).cards.get(4)));
disableButtons();
}
});
button4.setRequestFocusEnabled(false);
button4.setForeground(new Color(0, 255, 0));
button4.setBackground(Color.decode("#000000"));
button4.setFont(defaultFont);
button4.setOpaque(true);
button4.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttons.add(button4);
JButton button5 = new JButton("---");
panel.add(button5);
button5.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
button5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newGame.HumanTurn(5);
textField.setText(Integer.toString(newGame.players.get(0).cards.get(5)));
disableButtons();
}
});
button5.setRequestFocusEnabled(false);
button5.setForeground(new Color(0, 255, 0));
button5.setBackground(Color.decode("#000000"));
button5.setFont(defaultFont);
button5.setOpaque(true);
button5.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttons.add(button5);
JButton button6 = new JButton("---");
panel.add(button6);
button6.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
button6.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newGame.HumanTurn(6);
textField.setText(Integer.toString(newGame.players.get(0).cards.get(6)));
disableButtons();
}
});
button6.setRequestFocusEnabled(false);
button6.setForeground(new Color(0, 255, 0));
button6.setBackground(Color.decode("#000000"));
button6.setFont(defaultFont);
button6.setOpaque(true);
button6.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttons.add(button6);
JButton button7 = new JButton("---");
panel.add(button7);
button7.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
button7.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newGame.HumanTurn(7);
textField.setText(Integer.toString(newGame.players.get(0).cards.get(7)));
disableButtons();
}
});
button7.setRequestFocusEnabled(false);
button7.setForeground(new Color(0, 255, 0));
button7.setBackground(Color.decode("#000000"));
button7.setFont(defaultFont);
button7.setOpaque(true);
button7.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttons.add(button7);
JButton button8 = new JButton("---");
panel.add(button8);
button8.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
button8.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newGame.HumanTurn(8);
textField.setText(Integer.toString(newGame.players.get(0).cards.get(8)));
disableButtons();
}
});
button8.setRequestFocusEnabled(false);
button8.setForeground(new Color(0, 255, 0));
button8.setBackground(Color.decode("#000000"));
button8.setFont(defaultFont);
button8.setOpaque(true);
button8.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttons.add(button8);
JButton button9 = new JButton("---");
panel.add(button9);
button9.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
button9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newGame.HumanTurn(9);
textField.setText(Integer.toString(newGame.players.get(0).cards.get(9)));
disableButtons();
}
});
button9.setRequestFocusEnabled(false);
button9.setForeground(new Color(0, 255, 0));
button9.setBackground(Color.decode("#000000"));
button9.setFont(defaultFont);
button9.setOpaque(true);
button9.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttons.add(button9);
JButton random_1 = new JButton("RANDOM");
random_1.setBounds(238, 361, 105, 25);
frmStinkt.getContentPane().add(random_1);
random_1.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
random_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int random = (int)(Math.random() * newGame.players.get(0).cards.size());
newGame.HumanTurn(random);
textField.setText(Integer.toString(newGame.players.get(0).cards.get(random)));
disableButtons();
}
});
random_1.setRequestFocusEnabled(false);
random_1.setForeground(new Color(0, 255, 0));
random_1.setBackground(Color.decode("#000000"));
random_1.setFont(defaultFont);
random_1.setOpaque(true);
random_1.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
buttons.add(random_1);
disableButtons();
}
public void enableButtons()
{
for(int i=0; i<buttons.size(); i++)
buttons.get(i).setEnabled(true);
label.setEnabled(true);
}
public void disableButtons()
{
for(int i=0; i<buttons.size(); i++)
buttons.get(i).setEnabled(false);
label.setEnabled(false);
}
public static void setButtonNames(ArrayList<Integer> cards)
{
for(int i=0; i<buttons.size() - 1; i++)
buttons.get(i).setText(cards.get(i).toString());
}
}
I have read that I probably could work around this by using a swingWorker. I found a useful demo for a progressBar, but I can't figure out how to use it with my approach. I would appreciate any help. Thanks in advance!
This is how it looks like:
Here the method which is called by the button press and print:
public void HumanTurn(int cardIndex)
{
print("Du hast " + players.get(0).cards.get(cardIndex) + " gewählt.", textSpeedNormal);
next += 1;
BotTurn();
}
public void print(String text, int speed)
{
for(int i=0; i<text.length(); i++)
{
textArea.append(text.substring(i, (i+1)));
try {
Thread.sleep(speed);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
textArea.append("\n");
textArea.setCaretPosition(textArea.getDocument().getLength());
}
Thread.sleep(speed);
Don't use Thread.sleep(...).
This puts the Event Dispatch Thread (EDT) to sleep so the GUI can't respond to events or repaint itself. Read the Swing tutorial on Concurrency for more information.
Instead use a Swing Timer to schedule the animation. The Swing Timer replaces the looping code. Every time the timer fires you do some Action, in this case add a character to the text area.
One way might be to add the text to a StringBuilder. Then every time the Timer fires you remove the first character from the StringBuilder and append it to the text area. When the StringBuilder is empty you stop the Timer.
I am making a program which will open a class GUI called "Menu" when correct login info is put into a text field password field and a button called "login" is pressed. The problem is that the Menu window will open blank, not displaying what I have programmed into the Menu.
This is my code for Login class,
package ems;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.SystemColor;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Login extends JFrame implements ActionListener{
private JFrame loginFrame;
private JTextField usernameField;
private JPasswordField passwordField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login window = new Login();
window.loginFrame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Login() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
loginFrame = new JFrame();
loginFrame.setTitle("Login");
loginFrame.setBounds(100, 100, 450, 300);
loginFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
loginFrame.getContentPane().setLayout(null);
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(112, 116, 74, 16);
loginFrame.getContentPane().add(lblUsername);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(112, 165, 74, 16);
loginFrame.getContentPane().add(lblPassword);
usernameField = new JTextField();
usernameField.setBounds(198, 110, 134, 28);
loginFrame.getContentPane().add(usernameField);
usernameField.setColumns(10);
passwordField = new JPasswordField();
passwordField.setBounds(198, 159, 134, 28);
loginFrame.getContentPane().add(passwordField);
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String uname = usernameField.getText();
String pword = passwordField.getText();
if (uname.equals("test") && pword.equals("test")){
JOptionPane.showMessageDialog(loginFrame, "Login successful.");
loginFrame.setVisible(false);
Menu menu = new Menu ();
menu.setVisible (true);
}else{
JOptionPane.showMessageDialog(loginFrame, "Login unsuccessful.");
}
}
});
btnLogin.setBounds(238, 210, 90, 30);
loginFrame.getContentPane().add(btnLogin);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnExit.setBounds(108, 210, 90, 30);
loginFrame.getContentPane().add(btnExit);
JPanel panel = new JPanel();
panel.setBackground(new Color(192, 192, 192));
panel.setBounds(91, 86, 258, 163);
loginFrame.getContentPane().add(panel);
JLabel lblLoginToThe = new JLabel("LOGIN TO THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
lblLoginToThe.setBounds(26, 23, 418, 16);
loginFrame.getContentPane().add(lblLoginToThe);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
panel_1.setBounds(0, 0, 450, 63);
loginFrame.getContentPane().add(panel_1);
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
This is the code for the Menu class,
package ems;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import ems.Login;
public class Menu extends Login implements ActionListener{
private JFrame menuFrame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu window = new Menu();
window.menuFrame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Menu() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
menuFrame = new JFrame();
menuFrame.setTitle("Menu");
menuFrame.setBounds(100, 100, 450, 300);
menuFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
menuFrame.getContentPane().setLayout(null);
JLabel lblLoginToThe = new JLabel("THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
lblLoginToThe.setBounds(64, 22, 331, 16);
menuFrame.getContentPane().add(lblLoginToThe);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
panel_1.setBounds(0, 0, 450, 63);
menuFrame.getContentPane().add(panel_1);
JButton btnLogout = new JButton("Logout");
btnLogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
menuFrame.setVisible(false);
Login login = new Login ();
login.setVisible(true);
}
});
btnLogout.setBounds(307, 222, 117, 29);
menuFrame.getContentPane().add(btnLogout);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnExit.setBounds(10, 222, 117, 29);
menuFrame.getContentPane().add(btnExit);
}
}
Both of these classes are under a package called ems.
I am very new to programming and help would be greatly appreciated.
Thank you
You are creating another JFrame inside of Login and Menu, which is wrong, theres also no need that Menu extends Login
Here is the fixed version for Login:
package ems;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Login extends JFrame {
private static final long serialVersionUID = 1L;
private JTextField usernameField;
private JPasswordField passwordField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login window = new Login();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Login() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
this.setTitle("Login");
this.setBounds(100, 100, 450, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout(null);
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(112, 116, 74, 16);
this.getContentPane().add(lblUsername);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(112, 165, 74, 16);
this.getContentPane().add(lblPassword);
usernameField = new JTextField();
usernameField.setBounds(198, 110, 134, 28);
this.getContentPane().add(usernameField);
usernameField.setColumns(10);
passwordField = new JPasswordField();
passwordField.setBounds(198, 159, 134, 28);
this.getContentPane().add(passwordField);
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String uname = usernameField.getText();
String pword = passwordField.getText();
if (uname.equals("test") && pword.equals("test")){
JOptionPane.showMessageDialog(Login.this, "Login successful.");
Login.this.setVisible(false);
Menu menu = new Menu ();
menu.setVisible (true);
}else{
JOptionPane.showMessageDialog(Login.this, "Login unsuccessful.");
}
}
});
btnLogin.setBounds(238, 210, 90, 30);
this.getContentPane().add(btnLogin);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnExit.setBounds(108, 210, 90, 30);
this.getContentPane().add(btnExit);
JPanel panel = new JPanel();
panel.setBackground(new Color(192, 192, 192));
panel.setBounds(91, 86, 258, 163);
this.getContentPane().add(panel);
JLabel lblLoginToThe = new JLabel("LOGIN TO THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
lblLoginToThe.setBounds(26, 23, 418, 16);
this.getContentPane().add(lblLoginToThe);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
panel_1.setBounds(0, 0, 450, 63);
this.getContentPane().add(panel_1);
}
}
And for Menu
package ems;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Menu extends JFrame{
private static final long serialVersionUID = 1L;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu window = new Menu();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Menu() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
this.setTitle("Menu");
this.setBounds(100, 100, 450, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.getContentPane().setLayout(null);
JLabel lblLoginToThe = new JLabel("THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
lblLoginToThe.setBounds(64, 22, 331, 16);
this.getContentPane().add(lblLoginToThe);
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
panel_1.setBounds(0, 0, 450, 63);
this.getContentPane().add(panel_1);
JButton btnLogout = new JButton("Logout");
btnLogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Menu.this.setVisible(false);
Login login = new Login ();
login.setVisible(true);
}
});
btnLogout.setBounds(307, 222, 117, 29);
this.getContentPane().add(btnLogout);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnExit.setBounds(10, 222, 117, 29);
this.getContentPane().add(btnExit);
}
}
Still looking, but:
menuFrame.getContentPane().add(lblLoginToThe);
The content pane isn't a container, you can't add multiple things to it. You need to put everything in a panel (note panel != pane) and then add one panel to the content pane.
Also don't call setBounds() directly, use a layout manager. That's another reason you could be seeing nothing: all your components are drawn outside of the window or some other similar error. Layout managers will fix that.
EDIT: And as Edwardth said you have a habit of declaring your classes to be a thing (like JFrame) and then creating a second JFrame inside the initialize method. Don't do that.
public class Login extends JFrame implements ActionListener{
...
private void initialize() {
loginFrame = new JFrame(); // BAD!
The JFrame was already made when you declared that Login extends JFrame you don't need a second frame.
Edwardth got the answer before me so go ahead and study his example and then mark his answer correct. Ask in the comments below if you have further questions.
Here's my example of the Login class, without the setBounds().
class Login extends JFrame implements ActionListener{
private JTextField usernameField;
private JPasswordField passwordField;
/**
* Create the application.
*/
public Login() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
setTitle("Login");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lblUsername = new JLabel("Username");
JLabel lblPassword = new JLabel("Password");
usernameField = new JTextField();
usernameField.setColumns(10);
passwordField = new JPasswordField();
JPanel loginPanel = new JPanel( new GridLayout( 0,2 ) );
loginPanel.add( lblUsername );
loginPanel.add( usernameField );
loginPanel.add( lblPassword );
loginPanel.add( passwordField );
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String uname = usernameField.getText();
String pword = passwordField.getText();
if (uname.equals("test") && pword.equals("test")){
JOptionPane.showMessageDialog( Login.this, "Login successful.");
setVisible(false);
Menu menu = new Menu ();
menu.setVisible (true);
}else{
JOptionPane.showMessageDialog( Login.this, "Login unsuccessful.");
}
}
});
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
JPanel panel = new JPanel();
panel.setBackground(new Color(192, 192, 192));
panel.add( btnLogin );
panel.add( btnExit );
JLabel lblLoginToThe = new JLabel("LOGIN TO THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
panel_1.add( lblLoginToThe );
Box topBox = Box.createVerticalBox();
topBox.add( panel_1 );
topBox.add( loginPanel );
topBox.add( panel );
add( topBox );
pack();
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
And the Main class:
class Menu extends JFrame {
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Menu window = new Menu();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Menu() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
setTitle("Menu");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Box topBox = Box.createVerticalBox();
JLabel lblLoginToThe = new JLabel("THE ELECTRICITY MONITORING SYSTEM");
lblLoginToThe.setForeground(new Color(255, 255, 255));
lblLoginToThe.setFont(new Font("Arial", Font.BOLD, 16));
topBox.add( lblLoginToThe ); // **********
JPanel panel_1 = new JPanel();
panel_1.setBackground(new Color(46, 139, 87));
topBox.add( panel_1 ); // *************
JButton btnLogout = new JButton("Logout");
btnLogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Menu.this.setVisible(false);
Login login = new Login ();
login.setVisible(true);
}
});
topBox.add( btnLogout ); //****************
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
topBox.add( btnExit );
add( topBox );
pack();
}
}
I've made a JPanel with a image as background. But while loading the JPanel first time the rest of the added components but the image are not visible. After rolling the mouse over the image, the buttons become visible. How to make the JButtons visible along with the image as background while loading the panel.
Here is the piece of my code:
contentPane = new JPanel();
contentPane.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
setContentPane(contentPane);
contentPane.setLayout(null);
homePanel.setBounds(10, 11, 959, 620);
homePanel.setLayout(null);
JPanel wizardPanel = new JPanel();
wizardPanel.setBounds(10, 295, 545, 336);
wizardPanel.setLayout(null);
homePanel.add(wizardPanel);
JLabel backgroundLabel;
try {
backgroundLabel = new JLabel(new ImageIcon(ImageIO.read(new File("images/nature.jpg"))));
backgroundLabel.setBounds(0, 0, 545, 336);
wizardPanel.add(backgroundLabel);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(309, 95, 89, 23);
wizardPanel.add(btnNewButton);
JButton btnNewButton_1 = new JButton("New button");
btnNewButton_1.setBounds(309, 150, 89, 23);
wizardPanel.add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("New button");
btnNewButton_2.setBounds(309, 212, 89, 23);
wizardPanel.add(btnNewButton_2);
It's a bad idea to place button over label. Better way is to paint image as panel background or to use JLayer. Here is an example for the first solution:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.LayoutManager;
import java.util.Objects;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
public class JImagePanel extends JPanel {
private final Image image;
private boolean scale;
public JImagePanel(Image anImage) {
image = Objects.requireNonNull(anImage);
}
public JImagePanel(Image anImage, LayoutManager aLayout) {
super(aLayout);
image = Objects.requireNonNull(anImage);
}
/**
* {#inheritDoc}
*/
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
final Image toDraw = scale? image.getScaledInstance(getWidth(), getHeight(), Image.SCALE_SMOOTH) : image;
g.drawImage(toDraw, 0, 0, this);
}
/**
* {#inheritDoc}
*/
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
} else {
return new Dimension(image.getWidth(this), image.getHeight(this));
}
}
public boolean isScale() {
return scale;
}
public void setScale(boolean scale) {
this.scale = scale;
}
public static void main(String[] args) throws Exception {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
final JImagePanel p =
new JImagePanel(ImageIO.read(JImagePanel.class.getResource("myImage.png")), new FlowLayout());
p.setScale(true);
p.add(new JButton("Button"));
final JFrame frm = new JFrame("Image test");
frm.add(p);
frm.pack();
frm.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frm.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
A quick solution might be directly setting JFrame content pane to the image and adding your components to the content pane of this JFrame. Assuming your code is from the body of a JFrame class. My suggestion would more or less look like this:
JRootPane rootpane = new JRootPane();
JPanel contentPane = new JPanel();
contentPane.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
rootpane.setContentPane(contentPane);
contentPane.setLayout(null);
JPanel homePanel = new JPanel();
homePanel.setBounds(10, 11, 959, 620);
homePanel.setLayout(null);
JRootPane wizardPanel = new JRootPane();
wizardPanel.setBounds(10, 295, 545, 336);
wizardPanel.setLayout(null);
JLabel backgroundLabel;
try {
File f = new File("D:\\work\\eclipse\\workspace_eclipse_4.4.1\\trialExamples\\src\\main\\images\\nature.jpg");
backgroundLabel = new JLabel(new ImageIcon(ImageIO.read(f)));
backgroundLabel.setBounds(0, 0, 545, 336);
wizardPanel.setContentPane(backgroundLabel);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(309, 95, 89, 23);
wizardPanel.getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("New button");
btnNewButton_1.setBounds(309, 150, 89, 23);
wizardPanel.getContentPane().add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("New button");
btnNewButton_2.setBounds(309, 212, 89, 23);
wizardPanel.getContentPane().add(btnNewButton_2);
homePanel.add(wizardPanel.getContentPane());
add(homePanel);
this is crazy !! I got it working by placing the JButtons initialization code block above the Image loading portion it works .....
package demo;
import java.awt.EventQueue;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
public class demoframe extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1436190962490331120L;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
demoframe frame = new demoframe();
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
SwingUtilities.updateComponentTreeUI(frame);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public demoframe() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 988, 678);
JPanel contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(10, 11, 501, 361);
contentPane.add(panel);
panel.setLayout(null);
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(322, 112, 89, 23);
panel.add(btnNewButton);
JButton button = new JButton("New button");
button.setBounds(322, 172, 89, 23);
panel.add(button);
JButton button_1 = new JButton("New button");
button_1.setBounds(322, 244, 89, 23);
panel.add(button_1);
JLabel backgroundLabel;
try {
backgroundLabel = new JLabel(new ImageIcon(ImageIO.read(new File("images/nature.jpg"))));
backgroundLabel.setBounds(0, 0, 501, 361);
panel.add(backgroundLabel);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JPanel panel_1 = new JPanel();
panel_1.setBounds(521, 11, 441, 361);
contentPane.add(panel_1);
JPanel panel_2 = new JPanel();
panel_2.setBounds(10, 383, 952, 246);
contentPane.add(panel_2);
}
}
I was looking in to my Java project when I realized I have yet to make my title screen. But one problem came to mind: How do I make it in where when they press on the new file button it will clear everything on the screen and put the new stuff in?
In simpler words, how to make a action listener so when they click the button the screen will clear and put a new screen on?
package Main_Config;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class SET_UP extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JLabel consol;
public static Dimension size = new Dimension(800, 700);
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SET_UP frame = new SET_UP();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public SET_UP() {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(370, 70, 0, 0);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
setSize(size);
setLocationRelativeTo(null);
textField = new JTextField();
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String input = textField.getText();
consol.setText(input);
}
});
textField.setBounds(10, 452, 243, 20);
contentPane.add(textField);
textField.setColumns(10);
JButton enter = new JButton("Enter");
enter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
enter.setBounds(253, 452, 89, 20);
contentPane.add(enter);
JLabel consol = new JLabel("");
consol.setBounds(0, 483, 335, 189);
contentPane.add(consol);
JButton btnNewButton = new JButton("New button");
btnNewButton.setBounds(352, 451, 200, 23);
contentPane.add(btnNewButton);
JButton btnNewButton_1 = new JButton("New button");
btnNewButton_1.setBounds(584, 451, 200, 23);
contentPane.add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("New button");
btnNewButton_2.setBounds(0, 0, 89, 23);
contentPane.add(btnNewButton_2);
}
}
To clear the screen, I do this:
Button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
frame.setVisible(false);
frame.remove(panelTwo);
frame.remove(panelThree);
frame.add(panelFour);
frame.setVisible(true);
}
});