I'm learning javax.swing right now and I'm just trying some things out. But now I'm facing a problem I just can't solve. When I click the JLabel for changing the page (jpanel), nothing happens. It won't remove and show the other jpanel.
I also added a
public final HomeGUI getMainFrame() {
return this;
}
and at the mouseClicked(MouseEvent e)
gui.getMainFrame().removeAll();
and I tried it also with
gui.getMainFrame().mainPanel.removeAll();
My GUI:
public class HomeGUI extends JFrame {
private static final long serialVersionUID = 1L;
JPanel mainPanel = new JPanel(new CardLayout());
final CardLayout cl = new CardLayout();
final JPanel mainPanel = new JPanel(cl);
Panel panel;
Page2 page2;
public HomeGUI() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1200, 650);
this.setTitle("Terminal");
this.setLocationRelativeTo(null);
this.setLayout(new BorderLayout(1,1));
panel = new Panel();
panel.Inhalt();
page2 = new Page2();
page2.Inhalt();
this.add(mainPanel);
mainPanel.add(panel, "Seite1");
mainPanel.add(page2, "Seite2");
cl.show(mainPanel, "panel");
}
public static void main(String[] args) {
HomeGUI terminal = new HomeGUI();
terminal.setResizable(false);
terminal.setVisible(true);
}
}
the Panel:
class Panel extends JPanel {
private HomeGUI gui;
Page2 page2;
private static final long serialVersionUID = 1L;
JPanel Panel;
JLabel title = new JLabel("Willkommen");
JLabel bgc = new JLabel("");
JLabel menuStrich = new JLabel();
JLabel menuTitle = new JLabel("Menu");
JLabel menuHome = new JLabel("Home");
JLabel menuSeite2 = new JLabel("Seite2");
public void Inhalt() {
this.setBackground(new Color(230, 230, 230));
this.add(title);
this.add(bgc);
this.setLayout(null);
//Seite1
title.setSize(300, 50);
title.setLocation(300, 20);
title.setFont(new Font("Alba Matter", Font.PLAIN, 48));
//Menu
bgc.setLayout(null);
bgc.setOpaque(true);
bgc.setBackground(new Color(66, 78, 245));
bgc.setSize(280, 650);
bgc.setLocation(0, 0);
bgc.add(menuTitle);
bgc.add(menuStrich);
bgc.add(menuHome);
bgc.add(menuSeite2);
menuTitle.setLocation(90, 10);
menuTitle.setSize(100, 50);
menuTitle.setFont(new Font("Bahnschrift", Font.PLAIN, 38));
menuTitle.setForeground(Color.white);
menuStrich.setLocation(10, 55);
menuStrich.setSize(260, 5);
menuStrich.setBackground(new Color(240, 240, 240));
menuStrich.setOpaque(true);
menuHome.setLocation(30, 70);
menuHome.setSize(200, 50);
menuHome.setFont(new Font("Concert One", Font.PLAIN, 36));
menuHome.setForeground(Color.white);
menuSeite2.setLocation(30, 130);
menuSeite2.setSize(200, 50);
menuSeite2.setForeground(Color.LIGHT_GRAY);
menuSeite2.setFont(new Font("Concert One", Font.PLAIN, 32));
menuSeite2.addMouseListener(new menuSeite2Event());
}
private class menuSeite2Event extends MouseAdapter {
#Override
public void mouseClicked(MouseEvent e) {
//show page2
gui.cl.show(gui.mainPanel, "page2");
}
#Override
public void mouseEntered(MouseEvent e) {
menuSeite2.setForeground(Color.CYAN);
}
#Override
public void mouseExited(MouseEvent e) {
menuSeite2.setForeground(Color.LIGHT_GRAY);
}
}
}
class Page2 extends JPanel {
private static final long serialVersionUID = 1L;
JPanel Panel;
JLabel title = new JLabel("Willkommen");
JLabel bgc = new JLabel("");
JLabel menuStrich = new JLabel();
JLabel menuTitle = new JLabel("Menu");
JLabel menuHome = new JLabel("Home");
JLabel menuSeite2 = new JLabel("Seite2");
public void Inhalt() {
this.setBackground(new Color(230, 230, 230));
this.add(title);
this.add(bgc);
this.setLayout(null);
//Seite1
title.setSize(300, 50);
title.setLocation(300, 20);
title.setFont(new Font("Alba Matter", Font.PLAIN, 48));
//Menu
bgc.setLayout(null);
bgc.setOpaque(true);
bgc.setBackground(new Color(66, 78, 245));
bgc.setSize(280, 650);
bgc.setLocation(0, 0);
bgc.add(menuTitle);
bgc.add(menuStrich);
bgc.add(menuHome);
bgc.add(menuSeite2);
menuTitle.setLocation(90, 10);
menuTitle.setSize(100, 50);
menuTitle.setFont(new Font("Bahnschrift", Font.PLAIN, 38));
menuTitle.setForeground(Color.white);
menuStrich.setLocation(10, 55);
menuStrich.setSize(260, 5);
menuStrich.setBackground(new Color(240, 240, 240));
menuStrich.setOpaque(true);
menuHome.setLocation(30, 70);
menuHome.setSize(200, 50);
menuHome.setFont(new Font("Concert One", Font.PLAIN, 36));
menuHome.setForeground(Color.white);
menuHome.addMouseListener(new menuHomeEvent());
menuSeite2.setLocation(30, 130);
menuSeite2.setSize(200, 50);
menuSeite2.setForeground(Color.white);
menuSeite2.setFont(new Font("Concert One", Font.PLAIN, 32));
}
private class menuHomeEvent extends MouseAdapter {
#Override
public void mouseClicked(MouseEvent e) {
//show Home
}
#Override
public void mouseEntered(MouseEvent e) {
menuHome.setForeground(Color.CYAN);
}
#Override
public void mouseExited(MouseEvent e) {
menuHome.setForeground(Color.LIGHT_GRAY);
}
}
}
INFO: all classes are in 1 file.
Related
I have tried telling it to dispose the file explorer and recreate it works but I cannot seem to get my file image on it now any help in making it not quit in the first place?
here is the code(btw I am on IntelliJ IDEA CE):
package os_pack;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class OS extends JFrame implements ActionListener {
String title = "waliOS";
String message = "please login";
int width = 600;
int height = 400;
JButton b;
JLabel label;
JTextField text;
JLabel c;
JPasswordField pass;
JFrame f;
JFrame f2;
JLabel username;
JLabel password;
JLabel welcomeMain;
JFrame folderFrame;
JFrame textFrame;
JLabel folderLabel;
OS() {
f = new JFrame(title);
f.setSize(width, height);
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel(message);
label.setBounds(200, 100, 200, 50);
label.setForeground(Color.WHITE);
text = new JTextField();
text.setBounds(200, 150, 200, 30);
b = new JButton("login");
b.setBounds(200, 250, 200, 50);
b.addActionListener(this);
pass = new JPasswordField();
pass.setBounds(200, 200, 200, 30);
c = new JLabel();
c.setBounds(200, 300, 200, 50);
c.setForeground(Color.WHITE);
username = new JLabel("username");
username.setBounds(130, 140, 200, 50);
username.setForeground(Color.WHITE);
password = new JLabel("password");
password.setBounds(130, 190, 200, 50);
password.setForeground(Color.WHITE);
f.add(password);
f.add(username);
f.add(c);
f.add(pass);
f.add(b);
f.add(label);
f.add(text);
f.setLayout(null);
f.setVisible(true);
f.setResizable(false);
f.getContentPane().setBackground(Color.BLACK);
}
public void mainPage(){
f.dispose();
f2 = new JFrame();
f2.setTitle(title);
f2.setSize(width, height);
f2.setLocationRelativeTo(null);
f2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f2.setResizable(false);
f2.setLayout(null);
f2.setVisible(true);
f2.setResizable(false);
f2.getContentPane().setBackground(Color.BLACK);
welcomeMain = new JLabel("this is the home page");
welcomeMain.setForeground(Color.WHITE);
welcomeMain.setBounds(200, 100, 200, 50);
f2.add(welcomeMain);
ImageIcon folder = new ImageIcon(getClass().getResource("OS_file.png"));
JLabel folderLabel = new JLabel(folder);
folderLabel.setBounds(300, 200, 80, 80);
folderLabel.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
folderPage();
}
});
ImageIcon textEdit = new ImageIcon(getClass().getResource("text_edit.png"));
JLabel textImage = new JLabel(textEdit);
textImage.setBounds(200, 200, 80, 80);
textImage.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent em){
textEditPage();
}
});
f2.add(folderLabel);
f2.add(textImage);
}
public void folderPage() {
f2.dispose();
folderFrame = new JFrame(title + " folder");
folderFrame.setSize(width, height);
folderFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
folderFrame.setLocationRelativeTo(null);
folderFrame.setResizable(false);
folderFrame.setLayout(null);
folderFrame.setVisible(true);
folderFrame.getContentPane().setBackground(Color.BLACK);
JLabel test = new JLabel("this is the folder page");
test.setForeground(Color.WHITE);
test.setBounds(300, 200, 200, 50);
JButton back = new JButton("back");
back.setBounds(10, 10, 100, 30);
back.addActionListener (new ActionListener() {
#Override
public void actionPerformed (ActionEvent e) {
mainPage();
folderFrame.dispose();
}
});
JPopupMenu menu = new JPopupMenu();
JMenuItem newFolder = new JMenuItem("new Folder");
newFolder.addActionListener(this);
newFolder.setActionCommand("NF");
menu.add(newFolder);
folderFrame.addMouseListener((new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {}
#Override
public void mousePressed(MouseEvent e) {
if(SwingUtilities.isRightMouseButton(e)){
menu.show(folderFrame, e.getX(), e.getY());
}
}
#Override
public void mouseReleased(MouseEvent e) {}
#Override
public void mouseEntered(MouseEvent e) {}
#Override
public void mouseExited(MouseEvent e) {}
}));
ImageIcon folder = new ImageIcon("folder.png");
folderLabel = new JLabel(folder);
folderLabel.setBounds(300, 200, 80, 80);
folderFrame.add(test);
folderFrame.add(back);
}
public void textEditPage() {
f2.dispose();
textFrame = new JFrame(title + " text editor");
textFrame.setResizable(false);
textFrame.setLayout(null);
textFrame.setSize(width, height);
textFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
textFrame.setVisible(true);
textFrame.setLocationRelativeTo(null);
textFrame.getContentPane().setBackground(Color.BLACK);
JTextArea textArea = new JTextArea();
Font font = new Font(
Font.MONOSPACED,
Font.PLAIN,
textArea.getFont().getSize());
textArea.setFont(font);
textArea.setBounds(1, 30, 599, 399);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
JLabel title = new JLabel("Text Editor");
title.setBounds(250, 2, 100, 30);
title.setForeground(Color.WHITE);
JButton back = new JButton("back");
back.setBounds(10, 4, 100, 30);
back.addActionListener (new ActionListener() {
#Override
public void actionPerformed (ActionEvent e) {
mainPage();
textFrame.dispose();
}
});
textFrame.add(back);
textFrame.add(title);
textFrame.add(textArea);
}
public static void main(String[] args){
new OS();
}
#Override
public void actionPerformed(ActionEvent e) {
String user = text.getText();
String pass1 = pass.getText();
if (user.trim().equals("wali") && pass1.trim().equals("haider")) {
c.setText("welcome wali");
mainPage();
} else if(user.trim().equals("admin") && pass1.trim().equals("admin")) {
c.setText("welcome admin");
mainPage();
} else {
c.setText("wrong user");
}
String command = e.getActionCommand();
switch (command) {
case "NF":
System.out.println("done");
folderPage();
folderFrame.dispose();
System.out.print("hello");
folderFrame.add(folderLabel);
}
}
}
can I please get some help on this because I am really stuck if you have questions tell me in the comments that will be very helpful
I have been working on some side project involving MySQL, with will use tree different screens: 'menu, ' add breed', 'browse breed'.
At this point section initialize is getting quite large and I would like to split it into 3 different classes.
Is it possible to initialize for example JPanel outside Window class?
public class Window {
public static void setBreed()
{
for(int i=0; i<16;i++) {
breedLabels[i].setText(breedInfo[i]);
breedLabels[i].setBounds(600,100+i*30,300, 100);
breedLabels[i].setFont(new Font("Verdana", Font.PLAIN, 20));
viewBreed.add(breedLabels[i]);
}
}
public static void setText()
{
for(int i=0; i<16;i++) {
textLabels[i].setText(text[i]);
textLabels[i].setBounds(300,100+i*30,300, 100);
textLabels[i].setFont(new Font("Verdana", Font.PLAIN, 20));
viewBreed.add(textLabels[i]);
}
}
public static String URL = "jdbc:mysql://localhost:3306/chooseyourpuppy";
public static String user = "root";
public static String password = "";
public static String query = "select * from breeds";
static String [] breedInfo = new String[16];
static String [] text = new String[16];
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Window window = new Window();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
View.connect(URL, user, password, query);
}
public Window() {
initialize();
}
private JFrame frame;
public JPanel addBreed;
public static JPanel viewBreed;
public JPanel menu;
public static JLabel[] textLabels;
public static JLabel[] breedLabels;
private void initialize() {
final int WIDTH = 1280, HEIGHT = 720;
frame = new JFrame();
frame.getContentPane().setBackground(Color.WHITE);
frame.getContentPane().setLayout(null);
frame.setBounds(100, 100, WIDTH, HEIGHT);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("MyBREEDS Viewer");
frame.setResizable(false);
frame.setVisible(true);
//header
JPanel red = new JPanel();
red.setBounds(400, 0, 888, 80);
frame.getContentPane().add(red);
red.setBackground(new Color(204, 0, 0));
red.setLayout(null);
JPanel darkGrey = new JPanel();
darkGrey.setBounds(0, 0, 387, 80);
frame.getContentPane().add(darkGrey);
darkGrey.setBackground(new Color(51, 51, 51));
darkGrey.setLayout(null);
JLabel txtpnChoose = new JLabel();
txtpnChoose.setForeground(new Color(240, 240, 240));
txtpnChoose.setBounds(56, 11, 367, 63);
txtpnChoose.setFont(new Font("Verdana", Font.BOLD, 46));
txtpnChoose.setText("Choose your");
txtpnChoose.setBackground(null);
darkGrey.add(txtpnChoose);
JLabel txtpnPuppy = new JLabel();
txtpnPuppy.setBounds(5, 11, 166, 63);
txtpnPuppy.setForeground(new Color(240, 240, 240));
txtpnPuppy.setFont(new Font("Nunito-Bold", Font.BOLD, 46));
txtpnPuppy.setText("puppy");
txtpnPuppy.setBackground(null);
red.add(txtpnPuppy);
JLayeredPane layeredPane = new JLayeredPane();
layeredPane.setBounds(0, 0, WIDTH, HEIGHT);
frame.getContentPane().add(layeredPane);
layeredPane.setLayout(new CardLayout(0, 0));
JButton btnMenu = new JButton("Back to menu");
btnMenu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
layeredPane.removeAll();
layeredPane.add(menu);
layeredPane.repaint();
layeredPane.revalidate();
}
});
btnMenu.setForeground(Color.WHITE);
btnMenu.setBackground(new Color(51, 51, 51));
btnMenu.setFont(new Font("Verdana", Font.BOLD, 18));
btnMenu.setBounds(660, 20, 180, 40);
btnMenu.setBorderPainted(false);
btnMenu.setFocusPainted(false);
red.add(btnMenu);
//menu
menu = new JPanel();
menu.setBackground(Color.WHITE);
layeredPane.add(menu, "name_410359960271086");
menu.setLayout(null);
JButton btnBrowse = new JButton("Browse breeds");
btnBrowse.setBounds(100, 300, 400, 200);
btnBrowse.setFont(new Font("Verdana", Font.PLAIN, 40));
btnBrowse.setBorder(new LineBorder(Color.DARK_GRAY));
btnBrowse.setBorder(BorderFactory.createStrokeBorder(new BasicStroke(5.0f)));
btnBrowse.setBackground(Color.WHITE);
btnBrowse.setRequestFocusEnabled(false);
btnBrowse.setVisible(true);
btnBrowse.setFocusPainted(false);
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
layeredPane.removeAll();
layeredPane.add(viewBreed);
layeredPane.repaint();
layeredPane.revalidate();
setText();
setBreed();
}
});
btnBrowse.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
btnBrowse.setBackground(new Color(237, 237, 237));
}
#Override
public void mouseExited(MouseEvent e) {
btnBrowse.setBackground(Color.WHITE);
}
});
menu.add(btnBrowse);
addBreed = new JPanel();
layeredPane.add(addBreed, "name_410359942089403");
addBreed.setVisible(false);
addBreed.setBackground(Color.WHITE);
addBreed.setLayout(null);
//view breed window
viewBreed = new JPanel();
layeredPane.add(viewBreed, "name_410359924014670");
viewBreed.setLayout(null);
viewBreed.setVisible(false);
viewBreed.setBackground(Color.WHITE);
ImageIcon previous = new ImageIcon("src/images/previous.png");
ImageIcon previousHover = new ImageIcon("src/images/previousHover.png");
JButton prevBreed = new JButton(previous);
prevBreed.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
prevBreed.setIcon(previousHover);
}
#Override
public void mouseExited(MouseEvent e) {
prevBreed.setIcon(previous);
}
});
prevBreed.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
View.changeBreed(false);
}
});
prevBreed.setBounds(30, 300, previous.getIconHeight(), previous.getIconWidth());
viewBreed.add(prevBreed);
prevBreed.setRequestFocusEnabled(false);
prevBreed.setOpaque(false);
prevBreed.setContentAreaFilled(false);
prevBreed.setBorderPainted(false);
prevBreed.setFocusPainted(false);
ImageIcon next = new ImageIcon("src/images/next.png");
ImageIcon nextHover = new ImageIcon("src/images/nextHover.png");
JButton nextBreed = new JButton(next);
nextBreed.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
nextBreed.setIcon(nextHover);
}
#Override
public void mouseExited(MouseEvent e) {
nextBreed.setIcon(next);
}
});
nextBreed.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
View.changeBreed(true);
}
});
nextBreed.setBounds(1140, 300, previous.getIconHeight(), previous.getIconWidth());
viewBreed.add(nextBreed);
nextBreed.setRequestFocusEnabled(false);
nextBreed.setVisible(true);
nextBreed.setOpaque(false);
nextBreed.setContentAreaFilled(false);
nextBreed.setBorderPainted(false);
nextBreed.setFocusPainted(false);
//add breed window
JButton btnAdd = new JButton("Add new breed");
btnAdd.setBounds(780, 300, 400, 200);
btnAdd.setFont(new Font("Verdana", Font.PLAIN, 40));
btnAdd.setBorder(new LineBorder(Color.DARK_GRAY));
btnAdd.setBorder(BorderFactory.createStrokeBorder(new BasicStroke(5.0f)));
btnAdd.setBackground(Color.WHITE);
btnAdd.setRequestFocusEnabled(false);
btnAdd.setFocusPainted(false);
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
layeredPane.removeAll();
layeredPane.add(addBreed);
layeredPane.repaint();
layeredPane.revalidate();
}
});
btnAdd.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
btnAdd.setBackground(new Color(237, 237, 237));
}
#Override
public void mouseExited(MouseEvent e) {
btnAdd.setBackground(Color.WHITE);
}
});
menu.add(btnAdd);
breedLabels = new JLabel[breedInfo.length];
for(int i=0; i<breedInfo.length; i++) {
breedLabels[i] = new JLabel(breedInfo[i]);
}
textLabels = new JLabel[breedInfo.length];
for(int i=0; i<breedInfo.length; i++) {
textLabels[i] = new JLabel(breedInfo[i]);
}
}
}
Is it possible to initialize for example JPanel outside Window class?"
Yes. A different class might contain a method that creates & returns a JPanel.
Other tips:
Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or combinations of them along with layout padding and borders for white space.
Application resources will become embedded resources by the time of deployment, so it is wise to start accessing them as if they were, right now. An embedded-resource must be accessed by URL rather than file. See the info. page for embedded resource for how to form the URL.
new Font("Verdana", Font.PLAIN, 20) Use defaults or logical fonts (E.G. Font.SERIF) unless the font is supplied with your app. as an embedded resource.
The loop and array of labels that are added to viewBreed suggest it should be a JList rather than a JPanel
layeredPane.removeAll(); .. Ugh.. Use a CardLayout as shown in this answer.
What is the purpose of the JLayeredPane? I expect it's unnecessary purely on the basis that there is so little use for them.
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 ^-^.
I am trying to stop my JDialog from closing when the Enter key is pushed. I have already tried using getRootPane().setDefaultButton(null); but it is still not working. I am calling this constructor for my JDialog from the main JFrame. Here is my code:
public class CustomSaleDialog extends JDialog {
private final JPanel contentPanel = new JPanel();
private JTextField txtScanBarcode;
private JTextField txtNumSold;
private String barcode;
private int numTickets;
public void setNumTickets(int num) {
numTickets = num;
}
public void setBarCode(String code) {
barcode = code;
}
public int getNumTickets() {
return numTickets;
}
public String getBarCode() {
return barcode;
}
public CustomSaleDialog(JFrame f) {
getRootPane().setDefaultButton(null); //This is what I tried
setTitle("Custom Sale");
setBounds(100, 100, 450, 300);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setModalityType(ModalityType.APPLICATION_MODAL);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
{
JLabel lblMakeACustom = new JLabel("Make a Custom Sale");
lblMakeACustom.setFont(new Font("Tahoma", Font.PLAIN, 25));
lblMakeACustom.setHorizontalAlignment(SwingConstants.CENTER);
lblMakeACustom.setBounds(10, 11, 414, 44);
contentPanel.add(lblMakeACustom);
}
{
JLabel lblScanTicket = new JLabel("Scan Ticket");
lblScanTicket.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblScanTicket.setBounds(20, 73, 102, 20);
contentPanel.add(lblScanTicket);
}
{
JLabel lblNumberOfTickets = new JLabel("Number of Tickets Being Sold");
lblNumberOfTickets.setFont(new Font("Tahoma", Font.PLAIN, 20));
lblNumberOfTickets.setBounds(20, 136, 262, 25);
contentPanel.add(lblNumberOfTickets);
}
{
txtScanBarcode = new JTextField();
txtScanBarcode.setBounds(132, 73, 284, 20);
contentPanel.add(txtScanBarcode);
txtScanBarcode.setColumns(10);
}
{
txtNumSold = new JTextField();
txtNumSold.setBounds(292, 141, 124, 20);
contentPanel.add(txtNumSold);
txtNumSold.setColumns(10);
}
{
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
barcode = txtScanBarcode.getText();
String numTickets = txtNumSold.getText();
int numTicketsInt = 0;
if (barcode.length() > 0
&& numTickets.matches("[0-9]+")
&& numTickets.length() >= 1) {
numTicketsInt = Integer.parseInt(numTickets);
setBarCode(barcode);
setNumTickets(numTicketsInt);
}
setVisible(false);
dispose();
}
});
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
dispose();
}
});
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
}
setLocationRelativeTo(f);
setVisible(true);
}
}
And you forget to remove...
getRootPane().setDefaultButton(okButton);
This...
is why you don't use null layouts
Set focusable method or something like this that focuses to false.
remove this line getRootPane().setDefaultButton(okButton); it should work :)
Something strange happened to me. For some reason, it takes a long time(1.60900 seconds) till it runs the following line:
textArea = new JTextArea();
I declared textArea variable as globally.
This only happens in one window (Jframe). In others it does not happen.
public class FAQ extends JFrame
{
/*--------attributes--------*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JPanel panel;
private JScrollPane scrollPaneInput;
private JScrollPane scrollPaneQuestions;
private JPanel paneQuestions;
private JPanel paneSelectOrNewFAQ;
private JButton btnEditSelection;
private JButton btnNewFAQ;
public JTextArea textArea;
private JLabel lblQuestions;
public JList list;
private User user;
private FAQ currentWindow;
private int selectedFaq = 0;
private DatabaseManager DManager;
private Vector<FAQ_class> Faqs = new Vector<FAQ_class>();
private JButton btnNewButton;
/*--------methods--------*/
public FAQ(User _user,DatabaseManager DM)
{
setResizable(false);
DManager = DM;
addWindowStateListener(new WindowStateListener() {
public void windowStateChanged(WindowEvent arg0) {
}
});
addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent arg0) {
Menu menu = new Menu(user,DManager);
menu.setVisible(true);
}
});
currentWindow = this;
user = _user;
addGui();
if(!user.rule.equals("patient"))
{
btnEditSelection.setEnabled(true);
btnNewFAQ.setEnabled(true);
}
loadFaqs();
}//end of FAQ
public void loadFaqs()
{
Faqs = DManager.getQuestionsList();
Vector<String> temp = new Vector<String>();
for(int i = 0 ; i < Faqs.size();i++)
{
temp.addElement(Faqs.get(i).question);
}
list.setListData(temp);
}
public void addGui()
{
setTitle("FAQ - Online medical help");
setIconImage(Toolkit.getDefaultToolkit().getImage(FAQ.class.getResource("/Images/question.png")));
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 708, 438);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new GridLayout(1, 0, 0, 0));
addPanel();
addPanes();
addButtons();
addGroupLayout();
addJTextArea();
}//end of addGui
public void addPanel()
{
panel = new JPanel();
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.add(panel);
}//end of addPanel
public void addPanes()
{
scrollPaneInput = new JScrollPane();
scrollPaneInput.setBounds(327, 0, 365, 398);
paneQuestions = new JPanel();
paneQuestions.setBounds(0, 0, 317, 38);
paneQuestions.setBackground(new Color(154, 205, 50));
}//end of addScrollPanes
public void addButtons()
{
}//end of addButtons
public void addJTextArea()
{
textArea = new JTextArea();
textArea.setEditable(false);
textArea.setFont(new Font("Courier New", Font.PLAIN, 14));
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setAlignmentX(Component.RIGHT_ALIGNMENT);
scrollPaneInput.setViewportView(textArea);
}//end of addJTextArea
public void addGroupLayout()
{
lblQuestions = new JLabel("Questions");
lblQuestions.setHorizontalAlignment(SwingConstants.CENTER);
lblQuestions.setBounds(0, 0, 317, 38);
lblQuestions.setForeground(new Color(255, 255, 255));
lblQuestions.setFont(new Font("Tahoma", Font.BOLD, 22));
panel.setLayout(null);
scrollPaneQuestions = new JScrollPane();
scrollPaneQuestions.setBounds(0, 37, 317, 318);
list = new JList();
list.setSelectionBackground(new Color(154, 205, 50));
list.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent arg0) {
try
{
for(int i = 0; i<Faqs.size();i++)
{
if(!list.isSelectionEmpty())
if(Faqs.get(i).question.equals(list.getSelectedValue().toString()))
{
textArea.setText(Faqs.get(i).answer);
selectedFaq = i;
break;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
scrollPaneQuestions.setViewportView(list);
panel.add(scrollPaneQuestions);
panel.add(paneQuestions);
paneQuestions.setLayout(null);
paneQuestions.add(lblQuestions);
panel.add(scrollPaneInput);
paneSelectOrNewFAQ = new JPanel();
paneSelectOrNewFAQ.setBounds(0, 348, 317, 50);
btnEditSelection = new JButton("Edit Selected");
btnEditSelection.setBounds(68, 11, 131, 40);
btnEditSelection.setEnabled(false);
btnEditSelection.addActionListener(new ActionListener() {
//open EditFAQ to edit FAQ
public void actionPerformed(ActionEvent e) {
if(!list.isSelectionEmpty())
{
EditFAQ faq = new EditFAQ(user,Faqs.get(selectedFaq),currentWindow,DManager);
faq.setVisible(true);
currentWindow.setEnabled(false);
}
else
{
JOptionPane.showMessageDialog(null,"You must select for the list first.");
}
}
});
btnEditSelection.setIcon(new ImageIcon(FAQ.class.getResource("/Images/tool.png")));
btnNewFAQ = new JButton("New FAQ");
btnNewFAQ.setBounds(203, 11, 114, 40);
btnNewFAQ.setEnabled(false);
btnNewFAQ.addActionListener(new ActionListener() {
//open EditFAQ to make new FAQ
public void actionPerformed(ActionEvent e) {
EditFAQ faq = new EditFAQ(user,null,currentWindow,DManager);
faq.setVisible(true);
currentWindow.setEnabled(false);
}
});
btnNewFAQ.setMinimumSize(new Dimension(95, 23));
btnNewFAQ.setMaximumSize(new Dimension(95, 23));
btnNewFAQ.setPreferredSize(new Dimension(95, 23));
btnNewFAQ.setIcon(new ImageIcon(FAQ.class.getResource("/Images/add.png")));
btnNewButton = new JButton("");
btnNewButton.setBounds(0, 10, 42, 41);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
btnNewButton.setIcon(new ImageIcon(FAQ.class.getResource("/Images/left.png")));
panel.add(paneSelectOrNewFAQ);
paneSelectOrNewFAQ.setLayout(null);
paneSelectOrNewFAQ.add(btnNewButton);
paneSelectOrNewFAQ.add(btnEditSelection);
paneSelectOrNewFAQ.add(btnNewFAQ);
}//end of addGroupLayout
}//end of class
Something strange happened to me. For some reason, it takes a long time(5 second~) till it runs the following line: Run this class and give me the result:
import java.text.DecimalFormat;
import java.text.NumberFormat;
import javax.swing.JTextArea;
public class JTextAreaRunningTime {
JTextArea textArea;
public JTextAreaRunningTime(){
long startTime = System.currentTimeMillis();
textArea = new JTextArea();
long endTime = System.currentTimeMillis();
NumberFormat nf = new DecimalFormat("#0.00000");
String totalTime = nf.format((endTime-startTime)/1000d);
System.out.println("Execution time is " + totalTime + " seconds");
}
public static void main (String...argW){
new JTextAreaRunningTime();
}
}