I'm completely new to Layout Managers, but i want to create a table. I have a window that is set.Resizable(false) and doesn't have a layout manager, with 1 image and two text items placed using coordinates. I would like to keep these items using absolute layout, while creating my table underneath (using GridLayout I assume)
If it helps, here is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Canvas;
import javax.swing.JFrame;
import java.awt.Dimension;
class DisplayItems extends JFrame implements ActionListener
{
//text
private static JLabel TechforTeachingTitle;
private static JLabel TechforTeachingSubTitle;
//images
private static JLabel Logo;
//buttons
private static final int BUTTON_WIDTH = 100;
private static final int BUTTON_HEIGHT = 30;
public static void main(String[] args)
{
DisplayItems ProjectFrame = new DisplayItems();
ProjectFrame.setVisible(true); // Display the frame
}
public DisplayItems( )
{
//font properties
Font TitleFont = new Font("Serif", Font.BOLD, 80);
Font subFont = new Font("Serif", Font.BOLD, 40);
// set the frame properties
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Inventory system");
setSize(900, 700);
setLocationRelativeTo(null);
setResizable(false);
// set the content pane properties
Container contentPane = getContentPane();
contentPane.setLayout(null);
contentPane.setBackground(Color.decode("#FDF3E7"));
//set text properties
TechforTeachingTitle = new JLabel();
TechforTeachingTitle.setText("Tech For Teaching");
TechforTeachingTitle.setBounds(200, 30, 900, 95);
TechforTeachingTitle.setForeground(Color.decode("#8f8f8f"));
TechforTeachingTitle.setFont(TitleFont);
contentPane.add(TechforTeachingTitle);
TechforTeachingSubTitle = new JLabel();
TechforTeachingSubTitle.setText("View items");
TechforTeachingSubTitle.setBounds(400, 90, 900, 95); //left, top, length, height
TechforTeachingSubTitle.setForeground(Color.decode("#799177")); //7E8F7C (slightly less green)
TechforTeachingSubTitle.setFont(subFont);
contentPane.add(TechforTeachingSubTitle);
//set image properties
Logo = new JLabel(new ImageIcon("SmallLogo.png"));
Logo.setBounds(10,20,179,178); // //left, top, width, height
contentPane.add(Logo);
Logo.setVisible(true);
// Logo.addMouseListener(new MouseAdapter()
// {
// public void mouseClicked(MouseEvent e) {
// setVisible(false);
//
// FinalProject FP = new FinalProject();
// FP.setVisible(true);
// }
// });
//set button properties
}
public void actionPerformed(ActionEvent event) // Actions
{
}
}
Related
I am having some issues with my Swing GUI.
It currently looks like this:
But I would like to move a couple things around.
Firstly I want the buttons underneath the keyboard
I want to add a text field on top of the keyboard with the submit button on the right hand side.
How can I accomplish this? I've tried to create a GridLayout and slot things by row,column coordinate but it doesn't seem to work.
private class Display extends JPanel {
Display() {
setPreferredSize(new Dimension(620, 420));
setBackground(new Color(250, 230, 180));
setFont(new Font("Serif", Font.BOLD, 20));
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
((Graphics2D) g).setStroke(new BasicStroke(3));
if (message != null) {
g.setColor(Color.RED);
g.drawString(message, 30, 40);
g.drawString("00:00", 30, 410);
}
}
}
private void createWindow() {
setJMenuBar(menuBarCreator());
// The ActionListener that will respond to button clicks.
ButtonHandler buttonHandler = new ButtonHandler();
// Create the subpanels and add them to the main panel.
display = new Display();
setLayout(new BorderLayout(3, 3));
add(display, BorderLayout.CENTER);
JPanel bottom = new JPanel();
bottom.setLayout(new GridLayout(1,1));
add(bottom, BorderLayout.NORTH);
// Add keyboard
JPanel keyboard = new JPanel();
JPanel keyboardHolder = new JPanel();
keyboard.setLayout(new GridLayout(2, 13));
keyboardHolder.setLayout(new GridLayout(1, 2));
for (char alphabet = 'a'; alphabet <= 'z'; alphabet++) {
JButton button = new JButton(String.valueOf(alphabet));
button.addActionListener(buttonHandler);
keyboard.add(button);
alphabetButtons.add(button);
}
keyboardHolder.add(keyboard, 0,0);
add(keyboardHolder, BorderLayout.SOUTH);
// Create three buttons, register the ActionListener to respond to clicks on the
// buttons, and add them to the bottom panel.
JButton submitButton = new JButton("Submit");
submitButton.addActionListener(buttonHandler);
keyboard.add(submitButton);
JButton startButton = new JButton(GuiText.START.toString());
startButton.addActionListener(buttonHandler);
bottom.add(startButton);
JButton nextButton = new JButton(GuiText.NEXT.toString());
nextButton.addActionListener(buttonHandler);
bottom.add(nextButton);
JButton skipButton = new JButton(GuiText.SKIP.toString());
skipButton.addActionListener(buttonHandler);
bottom.add(skipButton);
JButton quit = new JButton(GuiText.QUIT.toString());
quit.addActionListener(buttonHandler);
bottom.add(quit);
setBackground(new Color(100, 0, 0));
nextButton.setEnabled(false);
skipButton.setEnabled(false);
}
Below is a concrete example of what camickr wrote in his comment to the original question. Note that this is not the only possibility. There are many layout managers. I recommend visiting Laying Out Components Within a Container
The purpose of the code is only to show you how to achieve your desired layout.
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
public class GuesGame implements Runnable {
private JFrame frame;
public void run() {
showGui();
}
private JPanel createBottomPanel() {
JPanel bottomPanel = new JPanel(new GridLayout(3, 1));
bottomPanel.add(createSubmitPanel());
bottomPanel.add(createKeyboardPanel());
bottomPanel.add(createButtonsPanel());
return bottomPanel;
}
private JPanel createButtonsPanel() {
JPanel buttonsPanel = new JPanel();
JButton startButton = new JButton("Start");
buttonsPanel.add(startButton);
JButton nextButton = new JButton("Next");
buttonsPanel.add(nextButton);
JButton skipButton = new JButton("Skip");
buttonsPanel.add(skipButton);
JButton quitButton = new JButton("Quit");
buttonsPanel.add(quitButton);
return buttonsPanel;
}
private JPanel createKeyboardPanel() {
JPanel keyboardPanel = new JPanel(new GridLayout(2, 13));
for (char c = 'a'; c <= 'z'; c++) {
JButton button = new JButton(String.valueOf(c));
keyboardPanel.add(button);
}
return keyboardPanel;
}
private JPanel createSubmitPanel() {
JPanel submitPanel = new JPanel();
JTextField txtFld = new JTextField(20);
submitPanel.add(txtFld);
JButton submitButton = new JButton("Submit");
submitPanel.add(submitButton);
return submitPanel;
}
private void showGui() {
frame = new JFrame("Guess Game");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(new Display(), BorderLayout.CENTER);
frame.add(createBottomPanel(), BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new GuesGame());
}
}
class Display extends JPanel {
private String message;
Display() {
message = "Starting game";
setPreferredSize(new Dimension(620, 420));
setBackground(new Color(250, 230, 180));
setFont(new Font("Serif", Font.BOLD, 20));
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
((Graphics2D) g).setStroke(new BasicStroke(3));
if (message != null) {
g.setColor(Color.RED);
g.drawString(message, 30, 40);
g.drawString("00:00", 30, 410);
}
}
}
You want three "rows" below the Display panel as follows
Text field and "submit" button.
Keyboard
Other buttons.
Hence the "bottom" panel contains three panels laid out one above the other.
The first panel is the text field and "submit" panel.
Underneath that is the "keyboard".
And underneath the keyboard are the other buttons.
Note that the default layout manager for JPanel is java.awt.FlowLayout and this layout manager is suitable for the panel containing the "submit" button and also suitable for the panel containing the other buttons.
Here is a screen capture of the running app.
My code is currently working fine, but whenever i compile, i get the Warning
C:\Users\etc\etc\FinalProject\AddItem.java uses unchecked or unsafe operations. Recompile with -Xlint:unchecked for details.
Should I do something about it, and if so, what? if my debugging is right, it appears to be caused by the content pane properties.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Canvas;
import javax.swing.JFrame;
import java.awt.Dimension;
import java.io.*;
class AddItem extends JFrame implements ActionListener
{
//text
private static JLabel TechforTeachingTitle;
private static JLabel TechforTeachingSubTitle;
//images
private static JLabel Logo;
//buttons
private JButton submitButton;
private static final int BUTTON_WIDTH = 100;
private static final int BUTTON_HEIGHT = 30;
//variables
public static void main(String[] args)
{
AddItem ProjectFrame = new AddItem();
ProjectFrame.setVisible(true); // Display the frame
//for combobox
//new AddItem().setVisible(true);
}
public AddItem ( )
{
//font properties
Font TitleFont = new Font("Serif", Font.BOLD, 80);
Font subFont = new Font("Serif", Font.BOLD, 40);
// set the frame properties
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Inventory system");
setSize(900, 700);
setLocationRelativeTo(null);
setResizable(true);
// set the content pane properties
Container contentPane = getContentPane();
contentPane.setLayout(null);
contentPane.setBackground(Color.decode("#FDF3E7"));
//set text properties
TechforTeachingTitle = new JLabel();
TechforTeachingTitle.setText("Tech For Teaching");
TechforTeachingTitle.setBounds(200, 30, 900, 95);
TechforTeachingTitle.setForeground(Color.decode("#8f8f8f"));
TechforTeachingTitle.setFont(TitleFont);
contentPane.add(TechforTeachingTitle);
TechforTeachingSubTitle = new JLabel();
TechforTeachingSubTitle.setText("Add an item");
TechforTeachingSubTitle.setBounds(400, 90, 900, 95); //left, top, length, height
TechforTeachingSubTitle.setForeground(Color.decode("#799177")); //7E8F7C (slightly less green)
TechforTeachingSubTitle.setFont(subFont);
contentPane.add(TechforTeachingSubTitle);
//set image properties
Logo = new JLabel(new ImageIcon("SmallLogo.png"));
Logo.setBounds(10,20,179,178); // //left, top, width, height
contentPane.add(Logo);
Logo.setVisible(true);
Logo.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e) {
setVisible(false);
FinalProject FP = new FinalProject();
FP.setVisible(true);
}
});
//set button properties
//for combobox
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//setLayout(null); //ONLY PROBLEM WITH THIS IS GETTING THE SCREEN TO APPEAR AT CORRECT SIZE
String[] values = {"Computer", "Monitor", "Keyboard"};
final JComboBox b = new JComboBox(values);
b.setEditable(true);
add(b);
b.setBounds(300, 300, 100, 50); //this works
add(b);
submitButton = new JButton("Submit");
submitButton.setBounds(700,600, BUTTON_WIDTH, BUTTON_HEIGHT);
submitButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String item=b.getSelectedItem().toString();
}
});
contentPane.add(submitButton);
//pack(); //not quite sure what this is for, but it makes the window tiny, so i commented it out
setLocationRelativeTo(null); //positions window center on screen
}
public void actionPerformed(ActionEvent event) // Actions
{
JButton clickedButton = (JButton) event.getSource();
String buttonText = clickedButton.getText();
}
}
you get the warning here I think:
final JComboBox b = new JComboBox(values);
to avoid this you have the following possibilities:
add SupressWarning above the JComboBox
#SuppressWarnings("unchecked")
final JComboBox b = new JComboBox(values);
or add SupressWarning above your method
#SuppressWarnings("rawtypes")
public AddItem ( )
or my favourite add the generic:
final JComboBox<Object> b = new JComboBox<Object>(values);
When I compile and run my program I would like to be able to re-size it and keep the components with the same scale factor. This would mean that when the frame is expanded the components will also expand, keeping the size and the spacing scale as the original was.
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.lang.*;
public class ResizeTst
{
JFrame myMainWindow = new JFrame("This is my title");
JPanel firstPanel = new JPanel();
//Components
JButton CompAth = new JButton();
JButton ViewAth = new JButton();
JButton UpdateRD = new JButton();
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String []fontFamilies = ge.getAvailableFontFamilyNames();
Font FontT5 = new Font("SansSerif", Font.BOLD, 50);
///////////
public void runGUI()
{
myMainWindow.setBounds(10, 10, 1296, 756);
myMainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myMainWindow.setLayout(new GridLayout(1,1));
createFirstPanel();
myMainWindow.getContentPane().add(firstPanel);
myMainWindow.setVisible(true);
}
public void createFirstPanel()
{
firstPanel.setLayout(null);
CompAth.setLocation(500,250);
CompAth.setSize(320,300);
CompAth.setText("<html><CENTER>Compare<br>Athletes</CENTER></html>");
CompAth.setFont(FontT5);
firstPanel.add(CompAth);
ViewAth.setLocation(100,250);
ViewAth.setSize(320,300);
ViewAth.setText("<html><CENTER>View<br>Athletes</CENTER></html>");
ViewAth.setFont(FontT5);
firstPanel.add(ViewAth);
UpdateRD.setLocation(900,250);
UpdateRD.setSize(320,300);
UpdateRD.setText("<html><CENTER>Update<br>Running<br>Details</CENTER></html>");
UpdateRD.setFont(FontT5);
firstPanel.add(UpdateRD);
}
public static void main(String[] args)
{
ResizeTst rt = new ResizeTst();
rt.runGUI();
}
}
So that if I implemented this code it would allow me to run it on any system in full size automatically, without the size of the components changing in scale factor to what they were originally. Allowing for my program to run without it looking bad on larger or smaller screens in full screen.
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.lang.*;
public class ResizeTst
{
JFrame myMainWindow = new JFrame("This is my title");
JPanel firstPanel = new JPanel();
//Components
JButton CompAth = new JButton();
JButton ViewAth = new JButton();
JButton UpdateRD = new JButton();
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String []fontFamilies = ge.getAvailableFontFamilyNames();
Font FontT5 = new Font("SansSerif", Font.BOLD, 50);
///////////
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
public void runGUI()
{
myMainWindow.setExtendedState(JFrame.MAXIMIZED_BOTH);
myMainWindow.setSize(screenSize);
myMainWindow.setVisible(true);
myMainWindow.setResizable(true);
myMainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myMainWindow.setLayout(new GridLayout(1,1));
createFirstPanel();
myMainWindow.getContentPane().add(firstPanel);
myMainWindow.setVisible(true);
}
I have been told I should use a layout on the panel which would allow me to do this, but I am unaware of which layout to use and how to apply it to this program correctly. Any solutions or suggestions on how to do this would be greatly appreciated.
Start with something along these lines. It uses a GridLayout that will stretch components to size. The buttons are made a little larger using setMargin(Insets). The font size is reduced for the screenshot, adjust all numbers to need.
import javax.swing.*;
import java.awt.*;
import javax.swing.border.EmptyBorder;
public class ResizeTst {
JFrame myMainWindow = new JFrame("This is my title");
JPanel firstPanel = new JPanel();
//Components
JButton compAth = new JButton();
JButton viewAth = new JButton();
JButton updateRD = new JButton();
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fontFamilies = ge.getAvailableFontFamilyNames();
Font fontT5 = new Font(Font.SANS_SERIF, Font.BOLD, 25);
///////////
public void runGUI() {
myMainWindow.setBounds(10, 10, 1296, 756); // don't guess the size (1)
myMainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myMainWindow.setLayout(new GridLayout(1, 1));
createFirstPanel();
myMainWindow.getContentPane().add(firstPanel);
myMainWindow.pack(); // 1) Make it mininum size needed
myMainWindow.setMinimumSize(myMainWindow.getSize());
myMainWindow.setVisible(true);
}
public void createFirstPanel() {
//firstPanel.setLayout(null);
firstPanel.setLayout(new GridLayout(1,0,50,50));
firstPanel.setBorder(new EmptyBorder(50,50,50,50));
Insets buttonMargin = new Insets(20, 20, 20, 20);
compAth.setText("<html><CENTER>Compare<br>Athletes</CENTER></html>");
compAth.setMargin(buttonMargin);
compAth.setFont(fontT5);
firstPanel.add(compAth);
viewAth.setMargin(buttonMargin);
viewAth.setText("<html><CENTER>View<br>Athletes</CENTER></html>");
viewAth.setFont(fontT5);
firstPanel.add(viewAth);
updateRD.setMargin(buttonMargin);
updateRD.setText("<html><CENTER>Update<br>Running<br>Details</CENTER></html>");
updateRD.setFont(fontT5);
firstPanel.add(updateRD);
}
public static void main(String[] args) {
// should be on the EDT!
ResizeTst rt = new ResizeTst();
rt.runGUI();
}
}
I am trying to access JTextField text namely 'searchBox' from outer action listener created in outer class.
GUI:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class MyFrame extends JFrame
{
public int stat1_var;
public int stat2_var;
public int stat3_var;
public String stat4_var;
private int statX_bound = 50;
private int statY_bound = 280;
public String url;
/*
* #param width The width of the frame.
* #param height The height of the frame.
* #param title The title of the frame.
*/
public MyFrame(int width, int height, String title, int stat1_var, int stat2_var, int stat3_var, String stat4_var)
{
this.stat1_var = stat1_var; //threading var
this.stat2_var = stat2_var; //spiders var
this.stat3_var = stat3_var; //results var
this.stat4_var = stat4_var; //other var
initUI(width, height, stat1_var, stat2_var, stat3_var, stat4_var);
this.setSize(width,height); //set frame size
this.setTitle(title); //set frame title
this.setVisible(true); //set visible
this.setResizable(false); //disable resizable frame
}
private void initUI(int width, int height, int stat1_var, int stat2_var, int stat3_var, String stat4_var)
{
ImageIcon ic = new ImageIcon("background.jpg");//background image source
JDesktopPane dp = new JDesktopPane(); //create desktop pane
JLabel lbl = new JLabel(ic); //create label
JPanel transparentPanel = new JPanel(); //create a JPanel
lbl.setBounds(0, 0, width, height); //bounds for the background
transparentPanel.setOpaque(false);
transparentPanel.setBounds(0, 0, width, height);//bounds for the panel
transparentPanel.setLayout(null);//default layout
setLayeredPane(dp);
JTextField searchBox = new JTextField("http://", 40); //keyword search box
searchBox.setEditable(true);
searchBox.setBounds(250, 130, 300, 25);
searchBox.setToolTipText("Enter domain to be crawled");
transparentPanel.add(searchBox);
searchBox.setActionCommand("url");
searchBox.addActionListener(new listeners(this));
JButton crawlBtn = new JButton("Crawl"); // search button
crawlBtn.addActionListener(new listeners(this));
crawlBtn.setBounds(555, 130, 80, 25);
crawlBtn.setActionCommand("crawl");
crawlBtn.setToolTipText("crawl domain");
transparentPanel.add(crawlBtn);//end
JTextField searchBox2 = new JTextField("", 40); //crawl url search box
searchBox2.setEditable(true);
searchBox2.setBounds(250, 160, 300, 25);
searchBox2.setToolTipText("enter your keywords");
transparentPanel.add(searchBox2); //end
JButton jumpBtn = new JButton("Jump!"); // search button
jumpBtn.addActionListener(new listeners(this));
jumpBtn.setBounds(555, 160, 80, 25);
jumpBtn.setActionCommand("crawl");
jumpBtn.setToolTipText("crawl domain");
transparentPanel.add(jumpBtn);//end
JLabel stat1 = new JLabel("Threads: " + stat1_var); //stat labels
stat1.setToolTipText("Threads");
stat1.setBounds(statX_bound, statY_bound, 300, 25);
statY_bound += 25; //place the label one place below
transparentPanel.add(stat1);
JLabel stat2 = new JLabel("Spiders: " + stat2_var); //stat labels
stat2.setToolTipText("Spiders");
stat2.setBounds(statX_bound, statY_bound, 300, 25);
statY_bound += 25; //place the label one place below
transparentPanel.add(stat2);
JLabel stat3 = new JLabel("Results found: " + stat3_var);
stat3.setToolTipText("Results found");
stat3.setBounds(statX_bound, statY_bound, 300, 25);
statY_bound += 25; //place the label one place below
transparentPanel.add(stat3);
JLabel stat4 = new JLabel("Status: " + stat4_var);
stat4.setToolTipText("Status");
stat4.setBounds(statX_bound, statY_bound, 300, 25);
statY_bound += 25; //place the label one place below
transparentPanel.add(stat4);
dp.add(lbl,new Integer(50));
dp.add(transparentPanel,new Integer(350));
setDefaultCloseOperation(EXIT_ON_CLOSE); //close the app if close button clicked
} //end constructor
public void paint(Graphics g)
{
super.paint(g); //call superclass' paint method
g.setColor(Color.BLACK);
} //end method paint
} //end class MyFrame
And this is the outer class listener:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.PrintWriter;
import java.io.File;
public class listeners implements ActionListener
{
private MyFrame myframe;
public listeners(MyFrame myframe){
this.myframe = myframe;
//String source = e.getSource();
}
public void actionPerformed(ActionEvent event) {
String action = event.getActionCommand();
if (action == "url")
{
myframe.url = searchBox.getText(); //<----- I am trying to obtain this from the gui
}
}
}
I am trying to obtain the searchBox text value(arrows above) to the url variable from GUI class. Can anyone please help me with this? I have been looking for the solution for 3 hours now...
Use getSource to obtain a reference to the JTextField
JTextField searchBox = (JTextField) e.getSource();
Declare your JTextField variable as instance var. (outside of initUI method) and create getter method. Then call it in your listeners class:
myframe.url = myframe.getSearchBox().getText();;
Other sidenotes:
Name your classes properly. Names of classes begin with upper cases.
Do not extend your class with JFrame if you are not going to override some methods or to define new methods.
DON'T use absolute positioning for swing components! Use proper layout manager.
How would I go upon adding JLabel hovering? Like when you move your mouse over top a JLabel a and new image will overlap it. I know how to make it work with buttons, but the same technique will not work for JLabels. Will anyone guide me towards adding JLabel hovering? Please and thanks.
package src;
import java.awt.Dimension;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
/*
* #Author - 0x29A
*
*
*/
public class Jframe {
public static void main(final String args[]) {
/*
* #Images
*/
final ImageIcon icon = new ImageIcon("Data/button.png");
final JLabel label = new JLabel(icon);
final ImageIcon icon1 = new ImageIcon("Data/button1.png");
final JLabel label1 = new JLabel(icon1);
final ImageIcon icon2 = new ImageIcon("Data/button2.png");
final JLabel label2 = new JLabel(icon2);
final ImageIcon icon3 = new ImageIcon("Data/button3.png");
final JLabel label3 = new JLabel(icon3);
final ImageIcon icon4 = new ImageIcon("Data/button4.png");
final JLabel label4 = new JLabel(icon4);
final ImageIcon icon5 = new ImageIcon("Data/button5.png");
final JLabel label5 = new JLabel(icon5);
final ImageIcon icon6 = new ImageIcon("Data/background.png");
final JLabel label6 = new JLabel(icon6);
/*
* #Image Location
*/
label.setBounds(282, 255, 96, 96);
label1.setBounds(384, 255, 96, 96);
label2.setBounds(282, 153, 96, 96);
label3.setBounds(384, 153, 198, 96);
label4.setBounds(181, 152, 96, 96);
label5.setBounds(181, 255, 96, 96);
label6.setBounds(0, 0, 765, 503);
/*
* #Frame
*/
final JFrame frame = new JFrame("test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(765, 503));
frame.setLayout(null);
frame.add(label);
frame.add(label1);
frame.add(label2);
frame.add(label3);
frame.add(label4);
frame.add(label5);
frame.add(label6);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Made a quick example, it uses a MouseListener and MosueAdapter to monitor mouseExited() and mouseEntered() events on the JLabel, and when either of these methods are called (i.e when the mouse is over the label or not) the picture is changed:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.MouseAdapter;
import javax.swing.*;
public class LabelHoverTest extends JFrame {
Icon pic1;
Icon pic2;
JLabel label;
public LabelHoverTest(String title) {
super(title);
pic1 = UIManager.getIcon("OptionPane.informationIcon");
pic2 = UIManager.getIcon("OptionPane.questionIcon");
createAndShowUI();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new LabelHoverTest("Label Hover Test").setVisible(true);
}
});
}
private void createAndShowUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
addComponentsToPane(getContentPane());
setSize(300, 300);
setLocationRelativeTo(null);
setVisible(true);
}
private void addComponentsToPane(Container contentPane) {
label = new JLabel(pic1);
contentPane.add(label, BorderLayout.CENTER);
label.addMouseListener(new MouseAdapter() {
#Override
public void mouseEntered(java.awt.event.MouseEvent evt) {
label.setIcon(pic2);
}
#Override
public void mouseExited(java.awt.event.MouseEvent evt) {
label.setIcon(pic1);
}
});
}
}
you can use the MouseEntered mouse event for that and write this code
JLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("image location")));