My image disappear when i run jar file - java

well here are the classes i made..
package testdnevnik;
import javax.swing.JFrame;
public class Diary {
StartWindow startWindow = new StartWindow();
static JFrame frame = new JFrame("Diary");
int n = 0;
public Diary() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setSize(800,600);
frame.setLocationRelativeTo(null);
//frame.add(new ImagePanel("Img//bg2.jpeg"));
frame.setVisible(true);
frame.add(startWindow);
startWindow.checkStudents(n);
startWindow.chooseOption();
}
public static void main(String[] args) {
new Diary();
}
}
that was the main class,and here is the panel for the start window..
package testdnevnik;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import static testdnevnik.Diary.frame;
public class StartWindow extends JPanel {
JPanel jp = new JPanel();
JLabel jl = new JLabel();
JLabel headline = new JLabel();
JButton viewStudents = new JButton();
JButton editStudents = new JButton();
JButton addStudents = new JButton();
JButton removeStudents = new JButton();
JLabel usernameLbl = new JLabel();
JLabel passwordLbl = new JLabel();
JTextField usernameFld = new JTextField();
JPasswordField passwordFld = new JPasswordField();
JButton logIn = new JButton("Log In");
JButton signUp = new JButton("Sign Up");
public StartWindow () {
jp.setLayout( new BorderLayout() );
// headline
headline.setText("Diary");
headline.setLocation(200, 30);
headline.setHorizontalAlignment(JLabel.CENTER);
headline.setFont(new Font("Serif", Font.BOLD, 60));
headline.setForeground(Color.ORANGE);
headline.setSize(300, 80);
headline.setVisible(true);
// Buttons
//View Students - Button
viewStudents.setText("View All Students");
viewStudents.setSize(200,40);
viewStudents.setLocation(70 , 200);
viewStudents.setVisible(true);
// Edit Students - Button
editStudents.setText("Edit Students");
editStudents.setSize(200,40);
editStudents.setLocation(70 , 300);
editStudents.setVisible(true);
// Add Students - Button
addStudents.setText("Add New Students");
addStudents.setSize(200,40);
addStudents.setLocation(70 ,400);
addStudents.setVisible(true);
// Remove Students - Button
removeStudents.setText("Remove Students");
removeStudents.setSize(200,40);
removeStudents.setLocation(70 , 500);
removeStudents.setVisible(true);
// username and password labels and input field
usernameLbl.setText("Username: ");
usernameLbl.setBounds(320, 200, 108, 40);
usernameLbl.setFont(new Font(null,Font.BOLD, 20));
usernameLbl.setVisible(true);
usernameFld.setBounds(450, 205, 200, 30); // username field input
usernameFld.setVisible(true);
passwordLbl.setText("Password: ");
passwordLbl.setBounds(320, 300, 108, 40);
passwordLbl.setFont(new Font(null,Font.BOLD, 20));
passwordLbl.setVisible(true);
passwordFld.setBounds(450, 305, 200, 30); // password field input
passwordFld.setVisible(true);
// button for log in and sign up
logIn.setBounds(580, 400, 70, 40);
logIn.setVisible(true);
signUp.setBounds(480, 400, 90, 40);
signUp.setVisible(true);
// panel
jp.setSize(new Dimension(800,600));
jp.add(viewStudents); // add ViewStudents button to the panel
jp.add(editStudents); // add EditStudents button to the panel
jp.add(addStudents); // add AddStudents button to the panel
jp.add(removeStudents); // add RemoveStudents button to the panel
jp.add(usernameLbl); // username label
jp.add(passwordLbl); // password label
jp.add(usernameFld); // username input field
jp.add(passwordFld); // password input field
jp.add(logIn); //add log in button to the panel
jp.add(signUp); //add sign up button to the panel
jp.add(headline); // add headline label to the panel
jp.add(new ImagePanel("Img//bg2.jpg")); // add background image to the panel
// adding panel to the frame
frame.add(jp);
validate();
}
public void checkStudents(int n) {
int numberOfStudents = n;
if (numberOfStudents == 0) {
removeStudents.setEnabled(false);
}
}
public void chooseOption() {
viewStudents.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JOptionPane.showMessageDialog(null, "view students", "alert", JOptionPane.INFORMATION_MESSAGE);
}
});
editStudents.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JOptionPane.showMessageDialog(null, "edit students", "alert", JOptionPane.INFORMATION_MESSAGE);
}
});
addStudents.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JOptionPane.showMessageDialog(null, "add students", "alert", JOptionPane.INFORMATION_MESSAGE);
}
});
removeStudents.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JOptionPane.showMessageDialog(null, "remove students", "alert", JOptionPane.INFORMATION_MESSAGE);
}
});
logIn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JOptionPane.showMessageDialog(null, "succesful log in", "alert", JOptionPane.INFORMATION_MESSAGE);
}
});
signUp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JOptionPane.showMessageDialog(null, "sign up form", "alert", JOptionPane.INFORMATION_MESSAGE);
}
});
}
}
and here is the class for the image background
package testdnevnik;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class ImagePanel extends JPanel {
private Image img;
public ImagePanel(String img) {
this(new ImageIcon(img).getImage());
}
public ImagePanel(Image img) {
this.img = img;
Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
setPreferredSize(size);
}
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, null);
}
}
when i run the program from the NetBeans everything is ok,running perfectly,but when i click "Clean and Build Project" in NetBeans and run from the jar file in the folder,the background is white but the components added to the panel are fine,just the image for the background disappearing,why??

Related

PaintComponent not showing up

i'm currently adding functionality and completing a Hang-Man game my programing teacher made.
I added a frame to enable the user to write their own word to play the game however i stumbled on the following problem.
The PaintComponent that is supposed to draw when the user guesses the wrong word does not work. it does not draw when i guess the wrong word. (right now the word to guess is set to "hello" but i am going to change it after PaintComponent works).
i have tried to put all the components including the object to a JPanel but after i tried to do that the JFrame did not show upp after i pressed the button (b).
should i try with JPanel again or can i do anything to solve it as it currently is. i would like to point out that my teachers original code does not have the components put into a JPanel, he only has a frame. However his class extends with JPanel.
Anny suggestions ?
package hangtest2;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class HangTest2 {
public static void main(String[] args) {
// frame intro skärm
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("HangMan");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(3,1));
//label till orden
JLabel intro = new JLabel();
String ord = "Valfri";
intro.setText(ord);
Font font = new Font("Verdana", Font.BOLD, 25);
intro.setFont(font);
//till att välja ord
JTextField field = new JTextField(10);
field.setFont(font);
JButton b = new JButton("ok");
b.setBounds(370, 300, 100, 30);
frame.add(intro);
frame.add(field);
frame.add(b);
frame.setBackground(Color.white);
frame.setSize(600, 400);
frame.setVisible(true);
// frame hang
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame2 = new JFrame("HangMan");
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setLayout(null);
JPanel p2 = new JPanel();
p2.setLayout(null);
JLabel hang = new JLabel();
String firstinstruct = "Gissa genom att Mata in en bokstav ";
hang.setText(firstinstruct);
Font font2 = new Font("Verdana", Font.BOLD, 10);
hang.setFont(font2);
hang.setBounds(70, 100, 600,150 );
JTextField field2 = new JTextField();
field2.setVisible(true);
field2.setSize(300, 30);
field2.setLocation(60, 300);
field2.setVisible(true);
JButton b2 = new JButton("ok");
b2.setBounds(370, 300, 100, 30);
frame2.add(b2);
frame2.add(field2);
frame2.add(hang);
frame2.setBackground(Color.white);
frame2.setSize(600, 400);
DynamicHangTest2 object = new DynamicHangTest2(field, field2, b, b2, frame, frame2);
b.addActionListener(object);
field.addActionListener(object);
b2.addActionListener(object);
field2.addActionListener(object);
frame2.add(object);
frame2.setVisible(false);
}
}
The Dynamic Class
package hangtest2;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class DynamicHangTest2 extends JPanel implements ActionListener, MouseListener {
private int error;
public static String a = "hello";
JFrame frame, frame2;
JButton b,b2;
JTextField field, field2;
public DynamicHangTest2(JTextField field, JTextField field2, JButton b, JButton b2, JFrame frame, JFrame frame2) {
this.frame = frame;
this.frame2 = frame2;
this.b = b;
this.b2 = b2;
this.field = field;
this.field2 = field2;
}
#Override
public void mouseClicked(MouseEvent e) {
System.out.println(e.getX() + " " + e.getY());
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if(source.equals(b)) {
frame.setVisible(false);
frame2.setVisible(true);
}
if (source.equals(b2)) {
if (!a.contains(field2.getText())) {
error++;
frame2.repaint();
}
field2.setText("");
}
}
public void paintComponent(Graphics g) {
if (error == 1)
g.drawLine(10, 270, 500, 270);
if (error == 2) {
g.drawLine(10, 270, 500, 270);
g.drawLine(200, 30, 200, 270);
}
if (error == 3) {
g.drawLine(10, 270, 500, 270);
g.drawLine(200, 30, 200, 270);
g.drawLine(200, 30, 350, 30);
}
if (error > 3) {
Font font = new Font("Verdana", Font.BOLD, 25);
g.setFont(font);
g.drawString("GAME OVER", 270, 170);
}
}
}

How to remove the blank JFrame from appearing?

When I run my java program, two JFrames are showing, the JFrame that I created and another one that is blank that I cannot close. I think this error also has something to do with my JFrame that I created with components in it, not show when I run the program, instead the one showing is the blank JFrame. How do I fix this?
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import java.awt.Font;
public class trial extends Frame implements ActionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
private JFrame frame;
JButton newButton1, newButton2, newButton3,newButton4,newButton5,newButton6,newButton7,newButton8,newButton9;
Icon ic1=new ImageIcon("C:\\Users\\DB\\Desktop\\eclipse\\JAVA\\Final Project\\img\\INSTRUMENTS\\A1.png");
Icon ic2=new ImageIcon("C:\\Users\\DB\\Desktop\\eclipse\\JAVA\\Final Project\\img\\INSTRUMENTS\\A2.png");
Icon ic3=new ImageIcon("C:\\Users\\DB\\Desktop\\eclipse\\JAVA\\Final Project\\img\\INSTRUMENTS\\A3.png");
Icon ic4=new ImageIcon("C:\\Users\\DB\\Desktop\\eclipse\\JAVA\\Final Project\\img\\INSTRUMENTS\\A4.png");
Icon ic5=new ImageIcon("C:\\Users\\DB\\Desktop\\eclipse\\JAVA\\Final Project\\img\\INSTRUMENTS\\A5.png");
Icon ic6=new ImageIcon("C:\\Users\\DB\\Desktop\\eclipse\\JAVA\\Final Project\\img\\INSTRUMENTS\\A6.png");
Icon ic7=new ImageIcon("C:\\Users\\DB\\Desktop\\eclipse\\JAVA\\Final Project\\img\\INSTRUMENTS\\A7.png");
Icon ic8=new ImageIcon("C:\\Users\\DB\\Desktop\\eclipse\\JAVA\\Final Project\\img\\INSTRUMENTS\\A8.png");
Icon pink=new ImageIcon("C:\\Users\\DB\\Desktop\\eclipse\\JAVA\\Final Project\\img\\INSTRUMENTS\\c9.png");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
trial window = new trial();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public trial() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 986, 677);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
newButton1 = new JButton(new ImageIcon("C:\\Users\\jaxma\\Documents\\JAVA\\Final Project\\img\\INSTRUMENTS\\A1.png"));
newButton1.setBounds(43, 37, 150, 150);
newButton2 = new JButton(new ImageIcon("C:\\Users\\jaxma\\Documents\\JAVA\\Final Project\\img\\INSTRUMENTS\\A2.png"));
newButton2.setBounds(191,37, 150, 150);
newButton3 = new JButton(new ImageIcon("C:\\Users\\jaxma\\Documents\\JAVA\\Final Project\\img\\INSTRUMENTS\\A3.png"));
newButton3.setBounds(340,37, 150, 150);
newButton4 = new JButton(new ImageIcon("C:\\Users\\jaxma\\Documents\\JAVA\\Final Project\\img\\INSTRUMENTS\\A4.png"));
newButton4.setBounds(43,186, 150, 150);
newButton5 = new JButton(new ImageIcon("C:\\Users\\jaxma\\Documents\\JAVA\\Final Project\\img\\INSTRUMENTS\\A5.png"));
newButton5.setBounds(191,186, 150, 150);
newButton6 = new JButton(new ImageIcon("C:\\Users\\jaxma\\Documents\\JAVA\\Final Project\\img\\INSTRUMENTS\\A6.png"));
newButton6.setBounds(340,186, 150, 150);
newButton7 = new JButton(new ImageIcon("C:\\Users\\jaxma\\Documents\\JAVA\\Final Project\\img\\INSTRUMENTS\\A7.png"));
newButton7.setBounds(43,335, 150, 150);
newButton8 = new JButton(new ImageIcon("C:\\Users\\jaxma\\Documents\\JAVA\\Final Project\\img\\INSTRUMENTS\\A8.png"));
newButton8.setBounds(191,335,150, 150);
newButton9 = new JButton(pink);
newButton9.setBounds(340,335,150, 150);
newButton1.addActionListener(this);
newButton2.addActionListener(this);
newButton3.addActionListener(this);
newButton4.addActionListener(this);
newButton5.addActionListener(this);
newButton6.addActionListener(this);
newButton7.addActionListener(this);
newButton8.addActionListener(this);
newButton9.addActionListener(this);
frame.getContentPane().add(newButton1);frame.getContentPane().add(newButton2);frame.getContentPane().add(newButton3);frame.getContentPane().add(newButton4);frame.getContentPane().add(newButton5);frame.getContentPane().add(newButton6);
frame.getContentPane().add(newButton7);frame.getContentPane().add(newButton8);frame.getContentPane().add(newButton9);
JButton btnNewButton = new JButton("");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dispose();
DrumInfo a = new DrumInfo();
a.setLocationRelativeTo(null);
a.setVisible(true);
}
});
btnNewButton.setIcon(new ImageIcon("C:\\Users\\jaxma\\Documents\\JAVA\\Final Project\\img\\INSTRUMENTS\\drums.png"));
btnNewButton.setBounds(597, 37, 300, 277);
frame.getContentPane().add(btnNewButton);
JLabel lblNewLabel = new JLabel("Click the picture to find out what's the picture about!");
lblNewLabel.setFont(new Font("Berlin Sans FB Demi", Font.PLAIN, 15));
lblNewLabel.setBounds(563, 315, 382, 45);
frame.getContentPane().add(lblNewLabel);
JButton btnNewButton_1 = new JButton("BACK");
btnNewButton_1.setBounds(412, 563, 156, 63);
frame.getContentPane().add(btnNewButton_1);
JButton btnCategories = new JButton("CATEGORIES");
btnCategories.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
Puzzle2 a = new Puzzle2();
a.setLocationRelativeTo(null);
a.setVisible(true);
}
});
btnCategories.setBounds(604, 563, 156, 63);
frame.getContentPane().add(btnCategories);
JButton btnNext = new JButton("NEXT");
btnNext.setBounds(789, 563, 156, 63);
frame.getContentPane().add(btnNext);
setSize(600,500);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==newButton1){
Icon s1 = newButton1.getIcon();
if(newButton2.getIcon().equals(pink)) {
newButton2.setIcon(s1);
newButton1.setIcon(pink);
}
if(newButton4.getIcon().equals(pink)) {
newButton4.setIcon(s1);
newButton1.setIcon(pink);
}
}
if(e.getSource()==newButton2){
Icon s1 = newButton2.getIcon();
if(newButton1.getIcon().equals(pink)) {
newButton1.setIcon(s1);
newButton2.setIcon(pink);
}
if(newButton3.getIcon().equals(pink)) {
newButton3.setIcon(s1);
newButton2.setIcon(pink);
}
if(newButton5.getIcon().equals(pink)) {
newButton5.setIcon(s1);
newButton2.setIcon(pink);
}
}
if(e.getSource()==newButton3){
Icon s1 = newButton3.getIcon();
if(newButton2.getIcon().equals(pink)) {
newButton2.setIcon(s1);
newButton3.setIcon(pink);
}
if(newButton6.getIcon().equals(pink)) {
newButton6.setIcon(s1);
newButton3.setIcon(pink);
}
}
if(e.getSource()==newButton4){
Icon s1 = newButton4.getIcon();
if(newButton1.getIcon().equals(pink)) {
newButton1.setIcon(s1);
newButton4.setIcon(pink);
}
if(newButton7.getIcon().equals(pink)) {
newButton7.setIcon(s1);
newButton4.setIcon(pink);
}
if(newButton5.getIcon().equals(pink)) {
newButton5.setIcon(s1);
newButton4.setIcon(pink);
}
}
if(e.getSource()==newButton5){
Icon s1 = newButton5.getIcon();
if(newButton2.getIcon().equals(pink)) {
newButton2.setIcon(s1);
newButton5.setIcon(pink);
}
if(newButton6.getIcon().equals(pink)) {
newButton6.setIcon(s1);
newButton5.setIcon(pink);
}
if(newButton4.getIcon().equals(pink)) {
newButton4.setIcon(s1);
newButton5.setIcon(pink);
}
if(newButton8.getIcon().equals(pink)) {
newButton8.setIcon(s1);
newButton5.setIcon(pink);
}
}
if(e.getSource()==newButton6){
Icon s1 = newButton6.getIcon();
if(newButton9.getIcon().equals(pink)) {
newButton9.setIcon(s1);
newButton6.setIcon(pink);
}
if(newButton3.getIcon().equals(pink)) {
newButton3.setIcon(s1);
newButton6.setIcon(pink);
}
if(newButton5.getIcon().equals(pink)) {
newButton5.setIcon(s1);
newButton6.setIcon(pink);
}
}
if(e.getSource()==newButton7){
Icon s1 = newButton7.getIcon();
if(newButton4.getIcon().equals(pink)) {
newButton4.setIcon(s1);
newButton7.setIcon(pink);
}
if(newButton8.getIcon().equals(pink)) {
newButton8.setIcon(s1);
newButton7.setIcon(pink);
}
}
if(e.getSource()==newButton8){
Icon s1 = newButton8.getIcon();
if(newButton9.getIcon().equals(pink)) {
newButton9.setIcon(s1);
newButton8.setIcon(pink);
}
if(newButton7.getIcon().equals(pink)) {
newButton7.setIcon(s1);
newButton8.setIcon(pink);
}
if(newButton5.getIcon().equals(pink)) {
newButton5.setIcon(s1);
newButton8.setIcon(pink);
}
}
if(e.getSource()==newButton9){
Icon s1 = newButton9.getIcon();
if(newButton6.getIcon().equals(pink)) {
newButton6.setIcon(s1);
newButton9.setIcon(pink);
}
if(newButton8.getIcon().equals(pink)) {
newButton8.setIcon(s1);
newButton9.setIcon(pink);
}
}
if(newButton1.getIcon().equals(ic1)&&newButton2.getIcon().equals(ic2)&&newButton3.getIcon().equals(ic3)&&newButton4.getIcon().equals(ic4)&&newButton5.getIcon().equals(ic5)&&newButton6.getIcon().equals(ic6)&&newButton7.getIcon().equals(ic7)&&newButton8.getIcon().equals(ic8)&&newButton9.getIcon().equals(pink)) {
JOptionPane.showMessageDialog(this,"Congratulations! You won.");
}
}
}

How can I add a functional Java key listener to a panel under the card layout?

I was designing a program which has multiple layers(panels), and I want these panels to be keyboard sensitive so that I can press ESC to exit to the main menu (First panel) at any time.
Here is the switch panel code that I've written:
public void switchPane(JPanel jp) {
frmDavidsAppstore.getContentPane().removeAll();
frmDavidsAppstore.getContentPane().add(jp);
frmDavidsAppstore.getContentPane().repaint();
frmDavidsAppstore.getContentPane().revalidate();
jp.requestFocusInWindow();
}
I know that in order for the panel to be keyboard sensitive, it needs to be focusable.
Here's the code I have written for the initialisation of one of the panels:
panel2 = new JPanel();
panel2.setFocusable(true);
frmDavidsAppstore.getContentPane().add(panel2, "name_83147693736131");
panel2.setLayout(null);
panel2.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("panel2: " + KeyEvent.getKeyText(e.getKeyCode()));
if(e.getKeyCode()==KeyEvent.VK_ESCAPE) {
switchPane(panel1);
}
}
});
JButton btnReturnToMain = new JButton("Return to main page");
btnReturnToMain.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
switchPane(panel1);
}
});
btnReturnToMain.setBounds(279, 431, 236, 50);
panel2.add(btnReturnToMain);
I have deleted most of the unrelated functions and codes.
What I wish to accomplish is that when the switch page button is clicked, the switchPane method is executed, and the new panel automatically gets the focus with the requestFocusInWindow(); command, so that user can type ESC to return to the main menu.
When I tried to run the program, it turns out that for the first time I entered a sub-panel, it can not get the focus and does not respond to the keyboard. However, if I return to the main panel using the return button and re-enter the same sub-panel, this time it automatically gets the focus and is responding to the keyboard.
I have no idea why the program shows such behaviour. The following is the full program. Please notice that in the full program I also added a click to get focus function which works. However, I wish the newly opened panel can automatically get the focus and responding to the keys without the user actually clicking the panel.
import java.awt.*;
import javax.swing.JFrame;
import java.awt.CardLayout;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import java.awt.Font;
import javax.swing.JList;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class mainFrame {
private JFrame frmDavidsAppstore;
private JPanel panel1;
private JPanel panel2;
private JPanel panel3;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mainFrame window = new mainFrame();
window.frmDavidsAppstore.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public mainFrame() {
initialize();
}
public void switchPane(JPanel jp) {
frmDavidsAppstore.getContentPane().removeAll();
frmDavidsAppstore.getContentPane().add(jp);
frmDavidsAppstore.getContentPane().repaint();
frmDavidsAppstore.getContentPane().revalidate();
jp.requestFocusInWindow();
System.out.println(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner());
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmDavidsAppstore = new JFrame();
frmDavidsAppstore.setResizable(false);
frmDavidsAppstore.setTitle("David's appstore");
frmDavidsAppstore.setBounds(100, 100, 800, 600);
frmDavidsAppstore.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmDavidsAppstore.getContentPane().setLayout(new CardLayout(0, 0));
panel1 = new JPanel();
panel1.setFocusable(true);
frmDavidsAppstore.getContentPane().add(panel1, "name_83127645466169");
panel1.setLayout(null);
panel1.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("panel1: " + KeyEvent.getKeyText(e.getKeyCode()));
}
});
JButton button2 = new JButton("Open page 2");
button2.setFont(new Font("Tahoma", Font.PLAIN, 18));
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
switchPane(panel2);
}
});
button2.setBounds(279, 344, 236, 50);
panel1.add(button2);
JButton button3 = new JButton("Open page 3");
button3.setFont(new Font("Tahoma", Font.PLAIN, 18));
button3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
switchPane(panel3);
}
});
button3.setBounds(279, 432, 236, 50);
panel1.add(button3);
JLabel background = new JLabel("");
background.setIcon(new ImageIcon(mainFrame.class.getResource("/images/background_main.jpg")));
background.setBounds(0, 0, 794, 565);
panel1.add(background);
panel2 = new JPanel();
panel2.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
panel2.requestFocusInWindow();
System.out.println(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner());
}
});
panel2.setFocusable(true);
frmDavidsAppstore.getContentPane().add(panel2, "name_83147693736131");
panel2.setLayout(null);
panel2.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("panel2: " + KeyEvent.getKeyText(e.getKeyCode()));
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
switchPane(panel1);
}
}
});
JScrollPane scrollPane_1 = new JScrollPane();
scrollPane_1.setBounds(130, 104, 533, 270);
panel2.add(scrollPane_1);
JTextArea txtrIAmPage = new JTextArea();
txtrIAmPage.setEditable(false);
scrollPane_1.setViewportView(txtrIAmPage);
txtrIAmPage.setText("I am page2");
JButton btnReturnToMain = new JButton("Return to main page");
btnReturnToMain.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
switchPane(panel1);
}
});
btnReturnToMain.setBounds(279, 431, 236, 50);
panel2.add(btnReturnToMain);
panel3 = new JPanel();
panel3.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
panel3.requestFocusInWindow();
System.out.println(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner());
}
});
panel3.setFocusable(true);
frmDavidsAppstore.getContentPane().add(panel3, "name_83334788966651");
panel3.setLayout(null);
panel3.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
System.out.println("panel3: " + KeyEvent.getKeyText(e.getKeyCode()));
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
switchPane(panel1);
}
}
});
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(130, 104, 533, 270);
panel3.add(scrollPane);
JTextArea txtrIAmPage_1 = new JTextArea();
scrollPane.setViewportView(txtrIAmPage_1);
txtrIAmPage_1.setText("I am page3");
JButton button = new JButton("Return to main page");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
switchPane(panel1);
}
});
button.setBounds(279, 431, 236, 50);
panel3.add(button);
}
}
I have been working on it for a day now and couldn't figure out why. Thank you guys so much for any help or advices.
Apreciated!
Problem solved!!! You need to add .setVisible(true); before .requestFocusInWindow(); in order for it to work!

JPanel won't show up in JFrame

Why does my JPanel not show in JFrame after button is clicked.
There's my code:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.DefaultListModel;
import javax.swing.AbstractListModel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JPanel;
public class Main {
private JFrame frame;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Main window = new Main();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Main() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setResizable(false);
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
table = new JTable();
table.setModel(new DefaultTableModel(
new Object[][] {
{"1", "Marcin Zelek", "537573656"},
{"2", "Krzysztof Tomala", "324159103"},
{"3", "Zbigniew S", "324159104"},
},
new String[] {
"#", "Name", "Phone number"
}
));
table.getColumnModel().getColumn(1).setPreferredWidth(214);
table.getColumnModel().getColumn(2).setPreferredWidth(246);
table.setBounds(12, 103, 426, 185);
frame.getContentPane().add(table);
JButton btnDodajNowy = new JButton("Dodaj nowy");
btnDodajNowy.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent arg0) {
JPanel panel = new JPanel(null);// Creating the JPanel
panel.setBounds(0, 243, 286, 150);
panel.setVisible(true);
JButton button = new JButton("New button");
button.setBounds(12, 12, 117, 25);
panel.add(button);
frame.getContentPane().add(panel);
}
});
btnDodajNowy.setBounds(12, 30, 117, 25);
frame.getContentPane().add(btnDodajNowy);
JButton btnUsuZaznaczone = new JButton("Usuń zaznaczone");
btnUsuZaznaczone.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent arg0) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
int[] selection = table.getSelectedRows();
for (int i = 0; i < selection.length; i++)
{
model.removeRow(selection[i]-i);
}
}
});
btnUsuZaznaczone.setBounds(141, 30, 204, 25);
frame.getContentPane().add(btnUsuZaznaczone);
}
}
Thanks.
You should use actionListener instead:
btnDodajNowy.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JPanel panel = new JPanel();// Creating the JPanel
panel.setBounds(0, 243, 286, 150);
JButton button = new JButton("New button");
button.setBounds(12, 12, 117, 25);
panel.add(button);
frame.getContentPane().add(panel);
frame.repaint();
}
});
and also:
You don't need to pass null as a parameter to the JPanel constructor
You might want to add a frame.repaint()
You don't need to set the JPanel to visible via setVisible().
If you looking to present the panel in same jframe where you added the button you probably should use CardLayout here is the link http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html
It is being added, however, it is hiding below the JTable. The quickest fix is this:
public void mouseReleased(MouseEvent arg0) {
//...
panel.setBounds(0, 300, 286, 150); // 300 is on the y axis
//...
// then render the frame again:
frame.revalidate();
frame.repaint();
}
However, I suggest to rewrite it a little:
this.generalPanel = new JPanel();
frame.getContentPane().add(generalPanel);
...
generalPanel.add(table);
This way you'll get a good Layout for the topmost container.

how can i use a Jbutton in a class to trigger a panelSlider effect which is in a button actionPerformed in another class

how can i use a Jbutton in a class to trigger a panelSlider effect which is in a button actionPerformed in another class
Find the code here
public class programDisplay extends javax.swing.JPanel { /** * Creates new form programDisplay */
public programDisplay() {
initComponents();
}
here is an example for sliding effect of panel. you can take it as a reference and implement your requirement.
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class SlidingPanel {
JPanel panel;
public void makeUI() {
panel = new JPanel();
panel.setBackground(Color.RED);
panel.setBounds(0, 0, 400, 400);
JButton button = new JButton("Click");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
((JButton) e.getSource()).setEnabled(false);
new Timer(1, new ActionListener() {
public void actionPerformed(ActionEvent e) {
panel.setLocation(panel.getX() - 1, 0);
if (panel.getX() + panel.getWidth() == 0) {
((Timer) e.getSource()).stop();
System.out.println("Timer stopped");
}
}
}).start();
}
});
panel.add(button);
JFrame frame = new JFrame("Sliding Panel");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setLayout(null);
frame.add(panel);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new SlidingPanel().makeUI();
}
});
}
}
UPDATE :
in HomePane.java
rightPane rPane = new rightPane();
JPanel lPane = new leftPane(rPane);
in leftPane.java
private rightPane rPane;
public leftPane(final rightPane rPane)
{
pane = new JPanel();
this.rPane = rPane;
staffLogin = new JButton("STAFF LOGIN");
adminLogin = new JButton("ADMIN LOGIN");
guestLogin = new JButton("GUEST LOGIN");
staffLogin.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e)
{
rPane.trigerEvent();
}
});
this.setLayout(null);
this.add(staffLogin);
this.add(adminLogin);
this.add(guestLogin);
staffLogin.setFont(new Font("Serif", Font.BOLD, 20));
adminLogin.setFont(new Font("Serif", Font.BOLD, 20));
guestLogin.setFont(new Font("Serif", Font.BOLD, 20));
staffLogin.setBounds(20, 10, 200, 50);
adminLogin.setBounds(20, 75, 200, 50);
guestLogin.setBounds(20, 140, 200, 50);
this.setBorder(BorderFactory.createLineBorder(Color.BLUE));
pane.setBorder(BorderFactory.createLineBorder(Color.red));
}

Categories