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);
Related
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!
I built a Java-Swing GUI using the WindowBuilder in Eclipse. But when I try to add new components using the .add() and .revalidate() nothing happens.
If someone could help to fix this issue I realy would apreciate it.
package Frame;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.BorderLayout;
public class TestFrame {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestFrame window = new TestFrame();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TestFrame() {
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);
JButton btnSampleButton = new JButton("Sample Button");
btnSampleButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frame.add(new JButton("BTN"));
frame.revalidate();
frame.repaint();
}
});
frame.getContentPane().setLayout(null);
btnSampleButton.setBounds(110, 126, 185, 112);
frame.getContentPane().add(btnSampleButton);
}
}
Try following:
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class TestFrame {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
TestFrame window = new TestFrame();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TestFrame() {
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);
JButton btnSampleButton = new JButton("Sample Button");
btnSampleButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
JButton btn = new JButton("BTN");
btn.setSize(btn.getPreferredSize());
btn.setLocation(new Point(1, 1));
frame.add(btn);
frame.revalidate();
frame.repaint();
}
});
frame.getContentPane().setLayout(null);
btnSampleButton.setBounds(110, 126, 185, 112);
frame.getContentPane().add(btnSampleButton);
}
}
Try to learn Layout Managers. When you use an appropriate layout manager you shouldn't set the component's size/location.
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.
Hey I am trying to make a basic launcher and for the design I got an image. I want to make the exit button to be shown over the launcher image so you can see it. I dont know how I do it so I need help with it. Here is my code:
package launcher;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
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;
/**
*
* #author Daniel <Skype: daniel.gusdal>
*
* Current Date: 2. feb. 2014 Current Time: 21:46:52
* Project: 742 client. File Name: Launcher.java
*
*/
public class Launcher extends JFrame {
/**
* Generated serialVersionUID
*/
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(true);
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(getClass().getResource("Launcher3.png")));
Design.setBounds(-158, -22, 1047, 592);
contentPane.add(Design);
ImageIcon img = new ImageIcon(getClass().getResource(
"Playnow.png"));
final JButton Playnow = new JButton(img);
Playnow.setBackground(null);
Playnow.setOpaque(false);
Playnow.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(MouseEvent e) {
Playnow.setIcon(new ImageIcon(getClass().getResource(
"PlaynowHover.png")));
}
#Override
public void mouseClicked(MouseEvent e) {
Playnow.setIcon(new ImageIcon(getClass().getResource(
"PlaynowHover.png")));
System.out.println(Playnow.getIcon());
}
#Override
public void mouseExited(MouseEvent e) {
Playnow.setIcon(new ImageIcon(getClass().getResource(
"Playnow.png")));
}
});
Playnow.setBounds(258, 442, 301, 46);
contentPane.add(Playnow);
final JButton Exit = new JButton();
Exit.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
System.out.println(Exit.getIcon());
System.exit(0);
}
});
Exit.setIcon(new ImageIcon(Launcher.class.getResource("Exit.png")));
Exit.setOpaque(false);
Exit.setBounds(766, 59, 21, 21);
contentPane.add(Exit);
}
}
Don't set bounds. Learn to use Layout Managers.
Paint the image on a JPanel instead of using a JLabel
Put the JButton on the JPanel. Give that JPanel a GridBadLayout
Override the getPreferredSize() of the JPanel.
To switch between images you can use a flag like boolean icon1, icon2, icon3;. and repaint the JPanel the mouseXxx. Something like this
public void mouseClicked(MouseEvent e) {
icon1 = true;
icon2 = false;
icon3 = false;
imagePanel.repaint();
}
....
protected void paintComponent(Graphics g) {
if (icon1) {
g.drawImage(image1, .....);
}
if (icon2) { ... }
if (icon3) { ... }
}
pack() your frame.
Use Java naming convention. variables start with lower case letters.
Here's an example
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.*;
import java.util.logging.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class TestButtonOverImage {
public TestButtonOverImage() {
JFrame frame = new JFrame("Test Card");
frame.add(new ImagePanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new TestButtonOverImage();
}
});
}
public class ImagePanel extends JPanel {
BufferedImage img;
public ImagePanel() {
setLayout(new GridBagLayout());
add(new JButton("StackOverflow Button"));
try {
img = ImageIO.read(new URL("http://d8u1nmttd4enu.cloudfront.net/designs/logo-stackoverflow-logo-design-99designs_447080~36d200d82d83d7b2e738cebd2a48de07180cef3a_largecrop"));
} catch (MalformedURLException ex) {
Logger.getLogger(TestButtonOverImage.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(TestButtonOverImage.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 100, 100, 300, 300, this);
}
public Dimension getPreferredSize() {
return new Dimension(500, 500);
}
}
}
I don't know why, but I can't call the method paint(Graphics g) from code. I have MouseListeners:
#Override
public void mouseReleased(MouseEvent e) {
pointstart = null;
}
#Override
public void mousePressed(MouseEvent e) {
pointstart = e.getPoint();
}
and MouseMotionListeners:
#Override
public void mouseMoved(MouseEvent e) {
pointend = e.getPoint();
}
#Override
public void mouseDragged(MouseEvent arg0) {
pointend = arg0.getPoint();
// ==========================================================================
// call repaint:
repaint();
// ==========================================================================
}
and my paint method:
public void paint(Graphics g){
super.paint(g); //here I have my breakpoint in debugger
g.translate(currentx, currenty);
if(pointstart!=null){
g.setClip(chartPanel.getBounds());
g.setColor(Color.BLACK);
g.drawLine(pointstart.x, pointstart.y, pointend.x, pointend.y);
}
}
in the initialize method:
currentx = chartPanel.getLocationOnScreen().x;
currenty = Math.abs(chartPanel.getLocationOnScreen().y - frame.getLocationOnScreen().y);
All in class, which is my work frame, it extends JFrame.
Problem is, that program doesn't call paint method. I checked that in debugger.
I tried do this by paintComponent , without super.paint(g).
And the best is that, that code I copied from my other project, where it works fine.
UPDATE:
This is code which I want to draw line on panel (no matter - panel/chartpanel/etc). And it doesn't paint. I tried do this by paint(Graphics g){super.paint(g) ..... } and it doesn't too. Painting should be aneble after clicking button "line".
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Point;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JToolBar;
import javax.swing.SwingConstants;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
public class Window extends JFrame {
private JFrame frame;
public JPanel panelbuttons;
public JPanel panelscrollpane;
public JButton btnLine;
public JToolBar toolBar;
public JScrollPane scrollPane;
public JPanel panel;
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();
}
}
});
}
public Window() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 644, 430);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panelbuttons = new JPanel();
frame.getContentPane().add(panelbuttons, BorderLayout.WEST);
panelbuttons.setLayout(new BorderLayout(0, 0));
toolBar = new JToolBar();
toolBar.setOrientation(SwingConstants.VERTICAL);
panelbuttons.add(toolBar, BorderLayout.WEST);
btnLine = new JButton("line");
btnLine.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
panel.addMouseListener(mouselistenerLine);
panel.addMouseMotionListener(mousemotionlistenerLine);
}
});
toolBar.add(btnLine);
panelscrollpane = new JPanel();
frame.getContentPane().add(panelscrollpane, BorderLayout.CENTER);
panelscrollpane.setLayout(new BorderLayout(0, 0));
scrollPane = new JScrollPane(panel);
panel.setLayout(new BorderLayout(0, 0));
scrollPane.setViewportBorder(null);
panelscrollpane.add(scrollPane);
panelscrollpane.revalidate();
}
Point pointstart = null;
Point pointend = null;
private MouseListener mouselistenerLine = new MouseListener() {
#Override
public void mouseReleased(MouseEvent e) {
System.out.println("I'm in first listener. - mouse Released");
pointstart = null;
}
#Override
public void mousePressed(MouseEvent e) {
System.out.println("I'm in first listener. - mousePressed");
pointstart = e.getPoint();
}
#Override
public void mouseExited(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseClicked(MouseEvent e) {
}
};
private MouseMotionListener mousemotionlistenerLine = new MouseMotionListener() {
#Override
public void mouseMoved(MouseEvent e) {
System.out.println("I'm in second listener. - mouseMoved");
pointend = e.getPoint();
}
#Override
public void mouseDragged(MouseEvent arg0) {
System.out.println("I'm in second listener. - mouseDragged");
pointend = arg0.getPoint();
repaint();
}
};
public void paintComponent(Graphics g){
System.out.println("I'm in paintComponent method.");
if(pointstart!=null){
System.out.println("I'm drawing.");
g.setClip(scrollPane.getBounds());
g.setColor(Color.BLACK);
g.drawLine(pointstart.x, pointstart.y, pointend.x, pointend.y);
}
}
}
You are creating two separate instances of JFrame and showing only one.
One instance is created because Window class extends JFrame, and the second is created inside initialize method.
To fix this without a lot of changes in code do this:
private void initialize() {
frame = this;
frame.setBounds(100, 100, 644, 430);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
BTW. change paintComponent(Graphic g) to paint(Graphic g) because JFrame is not a JComponent.
In a ChartPanel context, consider one of the org.jfree.chart.annotations such as XYLineAnnotation, illustrated here and here.
Calling repaint() will trigger your paint(Graphics g) method to be called. So, you don't have to explicitly call paint().