I am working on a project for class where a piece of code is displayed as an image and buttons are hidden where the errors are in the code. The idea being that the user can then click on the area of code where they think the error is and the button becomes visible- I have set it to be translucent red so the user can still the error underneath. What is happening in the code is the buttons are working, but when I hit another button the button takes on the view through the last button. For example the first button is over error 'j k' and when clicked it becomes red and can still see the error. However when hit the next button where the error is 'i+j' the first button then changes to display 'i+j' taking on the second buttons error. As the error is embedded in an image I am not quite sure how this is happening. Any help would be very welcome.
package gui;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Tutorial1Test extends JFrame {
private JPanel contentPane;
/**
*
*/
private static final long serialVersionUID = 1L;
JButton one = new JButton();
JButton two = new JButton();
JButton three = new JButton();
JButton four = new JButton();
JButton five = new JButton();
JButton six = new JButton();
JButton seven = new JButton();
JButton eight = new JButton();
JButton nine = new JButton();
int clickCount = 0;
/**
* Launch the application.
*
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Tutorial1Test frame = new Tutorial1Test();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Tutorial1Test() throws IOException {
//create, format and locate jframe
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//exit program when framed closed
setBounds(300, 75, 800, 600);
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel background = new JLabel(new ImageIcon("src/gui/Tutorial1TestImage.png"));
background.setBounds(0, 0, 800, 600);
contentPane.add(background);
JLabel count1 = new JLabel("count");
count1.setBounds(100,110,45,20);
//count1.setText(Integer.toString(clickCount));
contentPane.add(count1);
one = new JButton();
one.setBounds(100,110, 45, 20);
hideButton(one);
contentPane.add(one);
one.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
showButton(one);
} catch (Exception e) {
e.printStackTrace();
}
}
});
two = new JButton();
two.setBounds(100, 215, 45, 20);
hideButton(two);
contentPane.add(two);
two.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
showButton(two);
} catch (Exception e) {
e.printStackTrace();
}
}
});
three = new JButton();
three.setBounds(95, 240, 150, 20);
hideButton(three);
contentPane.add(three);
three.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
showButton(three);
} catch (Exception e) {
e.printStackTrace();
}
}
});
four = new JButton();
four.setBounds(275, 265, 45, 20);
hideButton(four);
contentPane.add(four);
four.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
showButton(four);
} catch (Exception e) {
e.printStackTrace();
}
}
});
five = new JButton();
five.setBounds(320, 365, 45, 20);
hideButton(five);
contentPane.add(five);
five.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
showButton(five);
} catch (Exception e) {
e.printStackTrace();
}
}
});
six = new JButton();
six.setBounds(35, 395, 45, 20);
hideButton(six);
contentPane.add(six);
six.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
showButton(six);
} catch (Exception e) {
e.printStackTrace();
}
}
});
seven = new JButton();
seven.setBounds(100, 440, 45, 20);
hideButton(seven);
contentPane.add(seven);
seven.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
showButton(seven);
} catch (Exception e) {
e.printStackTrace();
}
}
});
eight = new JButton("");
eight.setBounds(100, 520, 45, 20);
hideButton(eight);
contentPane.add(eight);
eight.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
showButton(eight);
} catch (Exception e) {
e.printStackTrace();
}
}
});
nine = new JButton("");
nine.setBounds(550, 545, 45, 20);
hideButton(nine);
contentPane.add(nine);
nine.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
showButton(nine);
} catch (Exception e) {
e.printStackTrace();
}
}
});
//after you create your panel
contentPane.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (evt.getClickCount() >=12) {
//close window
}
else {
//display number of clicks
clickCount = evt.getClickCount();
}
}
});
}
public static void hideButton(JButton button){
//change button settings so not visible on opening
button.setFocusPainted(false);
button.setContentAreaFilled(false);
button.setBorderPainted(false);
button.setOpaque(false);
}
public static void showButton(JButton button){
//change button back to visible but transparent with colour to highlight error
button.setOpaque(true);
button.setContentAreaFilled(true);
button.setBackground(new Color(255,0,0,25));
}
}
I would do things differently:
I would give my program an array of Rectangles or ArrayList<Rectangle> and fill the collection with a list of the "active" rectangles on the image.
I would give my program a Rectangle variable, say called pressedRect that is initially set to null.
I would have my gui class extend JPanel and give it a MouseListener.
In this listener's mousePressed(...) method, I would iterate through the Rectangles in the array or collection to see if any of them have been pressed.
If pressed, I would set the pressedRect variable to the Rectangle identified in the Mouselistener.
I would draw the image in the paintComponent(...) method of a JPanel.
In the same paintComponent(...) method, I'd check if pressedRect is null and if not, I'd fill it in using Graphics2D#fill(...) method. You could use a translucent color for this such as new Color(0, 80, 0, 80).
Related
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.");
}
}
}
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!
The GUI on the calculator is finished however it does not do any math.
I heard about this command called "parse Int". With this I am trying to receive a string from the user and convert it into an integer. When I click an operator button I want it to receive input again and when i press the equals button I want java to register that string as the second number.
Does anyone know how I could approach this?
I am new in Java and I am doing this for experience with no time limit so I am open to different ways to make the calculator. Below I provide the code...
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JButton;
import java.awt.GridLayout;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Scanner;
import javax.swing.JSplitPane;
public class CalcGUI {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
CalcGUI window = new CalcGUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
// parse (int)
/**
* Create the application.
*/
public CalcGUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.getContentPane().add(panel, BorderLayout.NORTH);
panel.setLayout(new BorderLayout(0, 0));
JSplitPane splitPane = new JSplitPane();
panel.add(splitPane);
textField = new JTextField();
splitPane.setLeftComponent(textField);
textField.setColumns(10);
//a = int.parse(int);
textField_1 = new JTextField();
splitPane.setRightComponent(textField_1);
textField_1.setColumns(10);
JPanel panel_1 = new JPanel();
frame.getContentPane().add(panel_1, BorderLayout.CENTER);
panel_1.setLayout(new GridLayout(0, 3, 0, 0));
JPanel panel_2 = new JPanel();
panel_1.add(panel_2);
JButton btnNewButton_01 = new JButton("1");
panel_2.add(btnNewButton_01);
btnNewButton_01.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() + "1");
}});
JButton btnNewButton_04 = new JButton("4");
panel_2.add(btnNewButton_04);
btnNewButton_04.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() + "4");
}});
JButton btnNewButton_07 = new JButton("7");
panel_2.add(btnNewButton_07);
btnNewButton_07.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() + "7");
}});
JButton btnNewButton_squared = new JButton("x^2");
panel_2.add(btnNewButton_squared);
btnNewButton_squared.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() + "^2");// NOT SURE YET
}});
JButton btnNewButton_root = new JButton("Sqr");
panel_2.add(btnNewButton_root);
btnNewButton_root.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//do whatever should happen when the button is clicked...
}
});
JButton btnNewButton_clear = new JButton("clear");
btnNewButton_clear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
panel_2.add(btnNewButton_clear);
JPanel panel_3 = new JPanel();
panel_1.add(panel_3);
JButton btnNewButton_02 = new JButton("2");
panel_3.add(btnNewButton_02);
btnNewButton_02.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() + "2");
}});
JButton btnNewButton_05 = new JButton("5");
panel_3.add(btnNewButton_05);
btnNewButton_05.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() + "5");
}});
JButton btnNewButton_08 = new JButton("8");
panel_3.add(btnNewButton_08);
btnNewButton_08.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() + "8");
}});
JButton btnNewButton_09 = new JButton("9");
panel_3.add(btnNewButton_09);
btnNewButton_09.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() + "9");
}});
JButton btnNewButton_times = new JButton("x");
panel_3.add(btnNewButton_times);
btnNewButton_times.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() + "x");
}});
JButton btnNewButton_divide = new JButton("/");
panel_3.add(btnNewButton_divide);
btnNewButton_divide.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() + "/");
}});
JButton btnNewButton_delete = new JButton("delete");
panel_3.add(btnNewButton_delete);
btnNewButton_delete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
//do whatever should happen when the button is clicked...
}
});
JPanel panel_4 = new JPanel();
panel_1.add(panel_4);
JButton btnNewButton_03 = new JButton("3");
btnNewButton_03.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() + "3");
}
});
panel_4.add(btnNewButton_03);
JButton btnNewButton_06 = new JButton("6");
btnNewButton_06.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
panel_4.add(btnNewButton_06);
btnNewButton_06.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() + "6");
}});
JButton btnNewButton_00 = new JButton("0");
panel_4.add(btnNewButton_00);
btnNewButton_00.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() + "0");
}});
JButton btnNewButton_plus = new JButton("+");
panel_4.add(btnNewButton_plus);
btnNewButton_plus.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() + "+");
}});
JButton btnNewButton_minus = new JButton("-");
panel_4.add(btnNewButton_minus);
btnNewButton_minus.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
textField.setText(textField.getText() + "-");
}});
JButton btnNewButton_equals = new JButton("=");
panel_4.add(btnNewButton_equals);
btnNewButton_equals.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
}
}
Copying the whole code into the question is a bit too much, but let me suggest you a hint as more or less pseudocode:
String numToConvert = textField.getText();
try {
int num = new Integer(numToConvert);
//sum up or ...
} catch (Exception e) { //numToConvertIsNotAnInteger
//-> must be an operator
}
Line 132 JPanel bookInventory = new Inventory(); of the attached code is reporting the error "Type mismatch: cannot convert from Inventory to JPanel" - any suggestions what's causing this please?
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JSeparator;
import javax.swing.SwingConstants;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.SystemColor;
import java.awt.Toolkit;
import javax.swing.JMenuBar;
import javax.swing.JScrollPane;
import java.awt.GridLayout;
import javax.swing.border.SoftBevelBorder;
import javax.swing.border.BevelBorder;
public class LibSys extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
//private JPanel panelContent;
private static LibSys frame;
private JPanel panelTools;
private JScrollPane scrollPane;
public static int level = 0;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
frame = new LibSys(0);
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public LibSys(int n) {
level = n;
setTitle("Library Management System");
setIconImage(Toolkit.getDefaultToolkit().getImage(LibSys.class.getResource("/resources/Books-2-icon64.png")));
setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 744);
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu menu = new JMenu("File");
JMenuItem exit = new JMenuItem("Exit");
exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dispose();
}
});
JSeparator sep = new JSeparator();
JMenuItem logout = new JMenuItem("Logout");
logout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Login login = new Login();
login.setVisible(true);
dispose();
}
});
menu.add(exit);
menu.add(sep);
menu.add(logout);
menuBar.add(menu);
contentPane = new JPanel();
contentPane.setBackground(SystemColor.text);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
panelTools = new JPanel();
contentPane.add(panelTools, BorderLayout.WEST);
JButton btnToolBookLending = new JButton("Book Lending");
btnToolBookLending.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
JPanel bookLend = new BookLending();
//scrollPane.repaint();
scrollPane.getViewport().removeAll();
scrollPane.setViewportView(bookLend);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
panelTools.setLayout(new GridLayout(8, 1, 0, 20));
btnToolBookLending.setHorizontalAlignment(SwingConstants.LEFT);
btnToolBookLending.setIcon(new ImageIcon(LibSys.class.getResource("/resources/book-48.png")));
panelTools.add(btnToolBookLending);
//panelContent = new JPanel();
//contentPane.add(panelContent, BorderLayout.CENTER);
//panelContent.setLayout(new FlowLayout(BorderLayout.CENTER, 5, 5));
JButton btnToolInventory = new JButton("Inventory");
btnToolInventory.setHorizontalAlignment(SwingConstants.LEFT);
btnToolInventory.setIcon(new ImageIcon(LibSys.class.getResource("/resources/Inventory-icon-32.png")));
btnToolInventory.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
JPanel bookInventory = new Inventory();
scrollPane.getViewport().removeAll();
//System.out.println(bookInventory);
scrollPane.setViewportView(bookInventory);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
panelTools.add(btnToolInventory);
//panelTools.add(btnNewButton_1, "2, 2, left, center");
JButton btnBooksReg = new JButton("Book Registration");
btnBooksReg.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
JPanel bookReg = new BookRegistration();
scrollPane.getViewport().removeAll();
scrollPane.setViewportView(bookReg);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnBooksReg.setHorizontalAlignment(SwingConstants.LEFT);
btnBooksReg.setIcon(new ImageIcon(LibSys.class.getResource("/resources/book-add-icon-32.png")));
panelTools.add(btnBooksReg);
JButton btnToolMemberProfile = new JButton("Member Profile");
btnToolMemberProfile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
JPanel bookMemberProfile = new MemberProfile();
scrollPane.getViewport().removeAll();
scrollPane.setViewportView(bookMemberProfile);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnToolMemberProfile.setIcon(new ImageIcon(LibSys.class.getResource("/resources/App-login-manager-icon32.png")));
btnToolMemberProfile.setHorizontalAlignment(SwingConstants.LEFT);
panelTools.add(btnToolMemberProfile);
JButton btnToolMemberReg = new JButton("Member Registration");
btnToolMemberReg.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
JPanel MemberReg = new Registration();
scrollPane.getViewport().removeAll();
scrollPane.setViewportView(MemberReg);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnToolMemberReg.setIcon(new ImageIcon(LibSys.class.getResource("/resources/user_male_2_add.png")));
btnToolMemberReg.setHorizontalAlignment(SwingConstants.LEFT);
panelTools.add(btnToolMemberReg);
JButton btnToolConfig = new JButton("Configuration");
btnToolConfig.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
JPanel adminPanel = new AdminPanel();
scrollPane.getViewport().removeAll();
scrollPane.setViewportView(adminPanel);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
btnToolConfig.setIcon(new ImageIcon(LibSys.class.getResource("/resources/settings.png")));
btnToolConfig.setHorizontalAlignment(SwingConstants.LEFT);
panelTools.add(btnToolConfig);
JButton btnLogout = new JButton("Logout");
btnLogout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Login login = new Login();
login.setVisible(true);
dispose();
}
});
btnLogout.setIcon(new ImageIcon(LibSys.class.getResource("/resources/12345678.png")));
btnLogout.setHorizontalAlignment(SwingConstants.LEFT);
panelTools.add(btnLogout);
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setBackground(SystemColor.window);
lblNewLabel.setIcon(new ImageIcon(LibSys.class.getResource("/resources/top-banner.png")));
lblNewLabel.setHorizontalAlignment(SwingConstants.RIGHT);
contentPane.add(lblNewLabel, BorderLayout.NORTH);
scrollPane = new JScrollPane();
contentPane.add(scrollPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
scrollPane.setColumnHeaderView(panel);
panel.setLayout(new BorderLayout(0, 0));
JButton btnClose = new JButton("");
btnClose.setPreferredSize(new Dimension(33, 33));
btnClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if(scrollPane.getViewport().getComponentCount()>0){
scrollPane.getViewport().remove(scrollPane.getViewport().getComponent(0));
scrollPane.getViewport().repaint();
}
}
});
btnClose.setIcon(new ImageIcon(LibSys.class.getResource("/resources/2015.png")));
panel.add(btnClose, BorderLayout.EAST);
}
}
make sure that Inventory extends JPanel
this makes Inventory to behave as a subclass of a JPanel, and thus you can use it in the same way.
Is it possible to change the look of JButton to a custom picture? I want to use this picture as the button: http://i.stack.imgur.com/JMQMX.png instead of: http://i.stack.imgur.com/MXKUF.png
I have tried myself without succeed. Please help me! :)
Here is my code:
package launcher;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.event.MouseAdapter;
public class Launcher extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
static Point mouseDownCompCoords;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
mouseDownCompCoords = null;
final Launcher frame = new Launcher();
frame.setResizable(false);
frame.setUndecorated(true);
frame.setBackground(new Color(0, 255, 0, 0));
frame.setVisible(true);
frame.addMouseListener(new MouseListener() {
public void mouseReleased(MouseEvent e) {
mouseDownCompCoords = null;
}
public void mousePressed(MouseEvent e) {
mouseDownCompCoords = e.getPoint();
}
public void mouseExited(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {
}
});
frame.addMouseMotionListener(new MouseMotionListener() {
public void mouseMoved(MouseEvent e) {
}
public void mouseDragged(MouseEvent e) {
Point currCoords = e.getLocationOnScreen();
frame.setLocation(currCoords.x - mouseDownCompCoords.x,
currCoords.y - mouseDownCompCoords.y);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Launcher() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 841, 593);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel Design = new JLabel("New label");
Design.setIcon(new ImageIcon("C:\\Users\\Daniel\\Pictures\\Launcher2.png"));
Design.setBounds(-158, -22, 1047, 592);
contentPane.add(Design);
JButton Playnow = new JButton("");
Playnow.setOpaque(false);
Playnow.setIcon(new ImageIcon("C:\\Users\\Daniel\\Pictures\\Playnow.png"));
Playnow.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
//Playnow.setIcon(new ImageIcon("C:\\Users\\Daniel\\Pictures\\PlaynowHover.png"));
}
#Override
public void mouseClicked(MouseEvent e) {
//Playnow.setIcon(new ImageIcon("C:\\Users\\Daniel\\Pictures\\PlaynowHover.png"));
}
});
Playnow.setBounds(258, 442, 301, 46);
contentPane.add(Playnow);
JButton Exit = new JButton("");
Exit.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
final Launcher frame = new Launcher();
frame.dispose();
System.exit(0);
}
});
Exit.setBounds(766, 60, 19, 17);
contentPane.add(Exit);
}
}
I fixed it. There was something wrong with the picture thats why I couldnt see it...
try {
Playnow.setIcon(new ImageIcon(new URL("http://i.stack.imgur.com/JMQMX.png")));
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
this worked for me at the moment when i tried using ur code. however, if you wanna load it locally, you should try:
Playnow.setIcon(new ImageIcon(getClass().getResource("test.png")));
and test.png is in the same directory as the class file this code is in.
hope this helps :)
(I can't write comments yet so i write it as am awnser) I am not sure if this applies here, too but when i tried to change the icon of a Jlabel in my project, i had to set it invisible and after changing the icon visible again. Maybe it works if you try it like that.
Try this:
ImageIcon ic=new ImageIcon("C:/Users/Daniel/Pictures/Playnow.png")
JButton Playnow = new JButton(ic);
Playnow.setOpaque(false);