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")));
Related
I cant seem to get the line to appear. I have a Background color and a few pictures. If I have frame.setSize(x, y); and frame.setVisible(true);
then the outcome is as expected but without the line there. If I change the code and remove frame. from these two lines, leaving setSize(x,y); and setVisible(true);. I have tried using extends JPanel and extends JFrame but neither work. I have tried adding and removing #Override, paintComponent and g2d.drawLine.
It either one or the other, how do I get both to work?
import javax.swing.*;
import java.awt.*;
import javax.imageio.*;
import java.io.*;
public class CodeBreaker extends JPanel
{
JFrame frame = new JFrame("Code Breaker!");
Picture picture = new Picture("Empty.png");
JLabel label = new JLabel(picture);
JLabel label2 = new JLabel(picture);
JLabel label3 = new JLabel(picture);
JLabel label4 = new JLabel(picture);
JLabel label5 = new JLabel(picture);
JLabel label6 = new JLabel(picture);
JLabel label7 = new JLabel(picture);
JLabel label8 = new JLabel(picture);
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
public CodeBreaker()
{
frame.setSize(600, 900);
frame.setContentPane(panel);
frame.add(panel2);
frame.setResizable(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(new Color(141, 100, 21));
panel.add(label);
panel.add(label2);
panel.add(label3);
panel.add(label4);
panel2.add(label5);
panel2.add(label6);
panel2.add(label7);
panel2.add(label8);
panel2.setOpaque(false);
frame.setVisible(true);
}
/*
void drawLines(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
g2d.drawLine(120, 50, 360, 50);
}
*/
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.white);
g.drawLine(120, 50, 360, 50);
}
}
And this is my main:
public class CodeBreakerDriver
{
public static void main(String[] args)
{
CodeBreaker cb = new CodeBreaker();
}
}
Introduction
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section.
Since the code you posted isn't executable, I went ahead and created the following GUI.
You can see a black line in the lower right of the GUI.
Explanation
All Swing applications must start with a call to the SwingUtilities invokeLater method. This method ensures that the Swing components are created and executed on the Event Dispatch Thread.
Create the JFrame and JPanels in separate methods. This makes the code much easier to read and understand.
Use Swing layout managers. The JFrame has a default BorderLayout. I used a FlowLayout for both JPanels.
Code
Here's the complete runnable code. I made the Picture class an inner class so I could post the code as one block.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class CodeBreakerGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new CodeBreakerGUI());
}
private final Picture picture;
public CodeBreakerGUI() {
this.picture = new Picture();
}
#Override
public void run() {
JFrame frame = new JFrame("Code Breaker!");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTopPanel(), BorderLayout.NORTH);
frame.add(createBottomPanel(), BorderLayout.SOUTH);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public JPanel createTopPanel() {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 25, 25));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JLabel label = new JLabel(new ImageIcon(picture.getEmptyImage()));
panel.add(label);
JLabel label2 = new JLabel(new ImageIcon(picture.getEmptyImage()));
panel.add(label2);
JLabel label3 = new JLabel(new ImageIcon(picture.getEmptyImage()));
panel.add(label3);
JLabel label4 = new JLabel(new ImageIcon(picture.getEmptyImage()));
panel.add(label4);
return panel;
}
public JPanel createBottomPanel() {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 25, 25)) {
private static final long serialVersionUID = 1L;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.black);
g.drawLine(120, 50, 360, 50);
}
};
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JLabel label5 = new JLabel(new ImageIcon(picture.getEmptyImage()));
panel.add(label5);
JLabel label6 = new JLabel(new ImageIcon(picture.getEmptyImage()));
panel.add(label6);
JLabel label7 = new JLabel(new ImageIcon(picture.getEmptyImage()));
panel.add(label7);
JLabel label8 = new JLabel(new ImageIcon(picture.getEmptyImage()));
panel.add(label8);
return panel;
}
public class Picture {
private final BufferedImage emptyImage;
public Picture() {
this.emptyImage = new BufferedImage(64, 64, BufferedImage.TYPE_INT_RGB);
}
public BufferedImage getEmptyImage() {
return emptyImage;
}
}
}
I've been making an app with java swing and JavaFX and didn't run into a problem until now. Whenever I set the guis visibility to true, the GUI becomes very small, when it should be 1150 px wide, 900 px tall. Does anyone get any ideas?
Main Gui code:
import javax.swing.*;
import java.awt.*;
public class mainGui extends JFrame{
public static JFrame mainScreen = new JFrame("Tamo");
public mainGui() {
JPanel topPanel = new JPanel();
mainScreen.setSize(1150, 900);
mainScreen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainScreen.setResizable(false);
mainScreen.setLayout(new BorderLayout());
topPanel.setBackground(new Color(226, 230, 204));
topPanel.setPreferredSize(new Dimension(1150, 100));
mainScreen.add(topPanel, BorderLayout.NORTH);
ImageIcon icon = new ImageIcon("C:\\Users\\uname\\Desktop\\TamoDienynas\\pngs\\tamo.png");
mainScreen.setIconImage(icon.getImage());
mainScreen.setVisible(false);
}
public static void main(String[] args) {
new mainGui();
}
}
Class which make's the gui visible:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import static me.rockorbonk.tamodienynas.GUI.mainGui.mainScreen;
public class loginGui extends JFrame implements ActionListener {
private static JFrame frame;
private static JLabel userLabel;
private static JLabel passwordLabel;
private static JLabel success;
private static JButton login;
private static JTextField userText;
private static JPasswordField passwordText;
loginGui() {
frame = new JFrame();
JPanel panel = new JPanel();
frame.setSize(350, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(panel);
panel.setLayout(null);
userLabel = new JLabel("User");
userLabel.setBounds(10, 20, 80, 25);
panel.add(userLabel);
userText = new JTextField();
userText.setBounds(100, 20, 165, 25);
panel.add(userText);
passwordLabel = new JLabel("Password");
passwordLabel.setBounds(10, 50, 80, 25);
panel.add(passwordLabel);
passwordText = new JPasswordField();
passwordText.setBounds(100, 50, 165, 25);
panel.add(passwordText);
login = new JButton("Login");
login.setBounds(10, 80, 80, 25);
login.addActionListener(this);
panel.add(login);
success = new JLabel("");
success.setBounds(10, 110, 300, 25);
panel.add(success);
ImageIcon icon = new ImageIcon("C:\\Users\\uname\\Desktop\\TamoDienynas\\pngs\\tamo.png");
frame.setIconImage(icon.getImage());
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent ae) {
String uname = userText.getText();
String pwd = passwordText.getText();
if(uname.equals("rokasbruz") && pwd.equals("Rokas123")) {
success.setText("Sekmingai prisijungėte!");
ActionListener l = evt -> {
userLabel.setVisible(false);
passwordLabel.setVisible(false);
userText.setVisible(false);
passwordText.setVisible(false);
login.setVisible(false);
success.setVisible(false);
frame.setVisible(false);
mainScreen.setVisible(true);
mainScreen.pack();
};
Timer timer = new Timer(2000, l);
timer.setRepeats(false);
timer.start();
}
else{
success.setText("Slapyvardis arba slaptažodis nesutampa!");
}
}
public static void main(String[] args) {
new loginGui();
}
}
Any help would be appreciated!
P.S. I'm using IntelliJ ultimate as the IDE
-Rock
mainScreen is just a JFrame that does not contain anything. Hence when you make it visible, all you see is the title bar. In order to initialize mainScreen you need to call mainGui constructor. Nonetheless, as Andrew Thompson wrote in his comment, your style of coding a Swing application is very unusual. Consider using a dialog as your login window.
Here is your code that displays mainScreen as I believe you intended. I only changed the ActionListener, in class loginGui, that displays mainGui. I added one line which is indicated with the comment ADDED THIS LINE
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.Timer;
import static me.rockorbonk.tamodienynas.GUI.mainGui.mainScreen;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class loginGui extends JFrame implements ActionListener {
private static JFrame frame;
private static JLabel userLabel;
private static JLabel passwordLabel;
private static JLabel success;
private static JButton login;
private static JTextField userText;
private static JPasswordField passwordText;
loginGui() {
frame = new JFrame();
JPanel panel = new JPanel();
frame.setSize(350, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.add(panel);
panel.setLayout(null);
userLabel = new JLabel("User");
userLabel.setBounds(10, 20, 80, 25);
panel.add(userLabel);
userText = new JTextField();
userText.setBounds(100, 20, 165, 25);
panel.add(userText);
passwordLabel = new JLabel("Password");
passwordLabel.setBounds(10, 50, 80, 25);
panel.add(passwordLabel);
passwordText = new JPasswordField();
passwordText.setBounds(100, 50, 165, 25);
panel.add(passwordText);
login = new JButton("Login");
login.setBounds(10, 80, 80, 25);
login.addActionListener(this);
panel.add(login);
success = new JLabel("");
success.setBounds(10, 110, 300, 25);
panel.add(success);
ImageIcon icon = new ImageIcon("C:\\Users\\uname\\Desktop\\TamoDienynas\\pngs\\tamo.png");
frame.setIconImage(icon.getImage());
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent ae) {
String uname = userText.getText();
String pwd = passwordText.getText();
if (uname.equals("rokasbruz") && pwd.equals("Rokas123")) {
success.setText("Sekmingai prisijungėte!");
ActionListener l = evt -> {
userLabel.setVisible(false);
passwordLabel.setVisible(false);
userText.setVisible(false);
passwordText.setVisible(false);
login.setVisible(false);
success.setVisible(false);
frame.setVisible(false);
new mainGui(); // ADDED THIS LINE
mainScreen.setVisible(true);
mainScreen.pack();
};
Timer timer = new Timer(2000, l);
timer.setRepeats(false);
timer.start();
}
else {
success.setText("Slapyvardis arba slaptažodis nesutampa!");
}
}
public static void main(String[] args) {
new loginGui();
}
}
Here is how it appears (after logging in).
I am trying to implement an image appearing when a button is pressed. For this purpose I thought I could just copy the concept of button 4 (which works) and exchange the System.exit(0) with code to add an image, but while I've been able to use that code elsewhere successfully, here it does not seem to work.
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JSpinner;
import java.awt.Color;
import java.util.ArrayList;
public class Mainframe {
private JFrame frmOceanlife;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Mainframe window = new Mainframe();
window.frmOceanlife.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Mainframe() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmOceanlife = new JFrame();
frmOceanlife.setTitle("OceanLife");
frmOceanlife.setBounds(100, 100, 750, 600);
frmOceanlife.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmOceanlife.getContentPane().setLayout(null);
JButton btnNewButton_4 = new JButton("Quit");
btnNewButton_4.setBounds(640, 6, 81, 29);
frmOceanlife.getContentPane().add(btnNewButton_4);
btnNewButton_4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
JButton btnNewButton_5 = new JButton("Einfügen");
btnNewButton_5.setBounds(410, 34, 103, 29);
frmOceanlife.getContentPane().add(btnNewButton_5);
btnNewButton_5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ImageIcon icon = new ImageIcon("Stone.png");
JLabel label = new JLabel(icon);
// label.setBounds(25,25,50,50);
frmOceanlife.getContentPane().add(label);
}
});
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
panel.setBounds(70, 75, 600, 450);
panel.setLayout(new FlowLayout());
JLabel piclabel = new JLabel(new ImageIcon("underwater-600x450.png"));
panel.add(piclabel);
frmOceanlife.getContentPane().add(panel);
JLabel lblNewLabel_2 = new JLabel("Welcome to Oceanlife - Your Ocean size is 600x450!");
lblNewLabel_2.setBounds(6, 539, 334, 16);
frmOceanlife.getContentPane().add(lblNewLabel_2);
}
}
The problem is that you are creating a new JLabel and trying to add it to the frame, once the button is pressed. Instead, you should just change the Icon of the label that is already added to the frame (i.e., piclabel), using piclabel.setIcon(icon);. So, you should declare picLabel at the start of your code, so that it can be accessible in the actionPerformed method of your button.
public class Mainframe {
private JFrame frmOceanlife;
JLabel piclabel;
...
Then, instantiate the label in the initialize() method as below:
...
panel.setBounds(70, 75, 600, 450);
panel.setLayout(new FlowLayout());
piclabel = new JLabel(new ImageIcon("underwater-600x450.png"));
...
Finally, your actionPerformed method for btnNewButton_5 (please consider using descriptive names instead) should look like this:
btnNewButton_5.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ImageIcon icon = new ImageIcon("Stone.png");
piclabel.setIcon(icon);
}
});
Update
If, however, what you want is to add a new JLabel each time, and not change the icon of the existing one, you could use Box object with BoxLayout added to a ScrollPane. Then add the ScrollPane to your JFrame. Working example is shown below, based on the code you provided (again, please consider using descriptive names and removing unecessary code):
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.*;
import javax.swing.*;
public class Mainframe {
private JFrame frmOceanlife;
Box box;
JScrollPane scrollPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Mainframe mf = new Mainframe();
mf.initialize();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
JButton insertBtn = new JButton("Einfügen");
insertBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ImageIcon icon = new ImageIcon("Stone.png");
JLabel label = new JLabel(icon);
box.add(Box.createRigidArea(new Dimension(0, 5)));// creates space between the JLabels
box.add(label);
frmOceanlife.repaint();
frmOceanlife.revalidate();
Rectangle bounds = label.getBounds();
scrollPane.getViewport().scrollRectToVisible(bounds);// scroll to the new image
}
});
JButton quitBtn = new JButton("Quit");
quitBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
box = new Box(BoxLayout.Y_AXIS);
JLabel piclabel = new JLabel(new ImageIcon("underwater-600x450.png"));
box.add(piclabel);
scrollPane = new JScrollPane(box);
Dimension dim = new Dimension(box.getComponent(0).getPreferredSize());
scrollPane.getViewport().setPreferredSize(dim);
scrollPane.getVerticalScrollBar().setUnitIncrement(dim.height);
scrollPane.getViewport().setBackground(Color.WHITE);
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
controlPanel.add(insertBtn);
controlPanel.add(quitBtn);
JLabel titleLbl = new JLabel("Welcome to Oceanlife - Your Ocean size is 600x450!", SwingConstants.CENTER);
frmOceanlife = new JFrame();
frmOceanlife.getContentPane().add(titleLbl, BorderLayout.NORTH);
frmOceanlife.getContentPane().add(scrollPane, BorderLayout.CENTER);
frmOceanlife.getContentPane().add(controlPanel, BorderLayout.SOUTH);
frmOceanlife.setTitle("OceanLife");
frmOceanlife.pack();
frmOceanlife.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmOceanlife.setLocationRelativeTo(null);
frmOceanlife.setVisible(true);
}
}
Here is a sample application demonstrating the use of CardLayout. Note that I used [Eclipse] WindowBuilder. All the below code was generated by WindowBuilder apart from the ActionListener implementations. Also note that the ActionListener implementation for quitButton uses a lambda expression while the insertButton implementation uses a method reference.
More notes after the code.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import javax.swing.JLabel;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import javax.swing.ImageIcon;
import javax.swing.JButton;
public class MainFram {
private JFrame frame;
private JPanel cardsPanel;
private JPanel firstPanel;
private JLabel firstLabel;
private JPanel secondPanel;
private JLabel secondLabel;
private JPanel buttonsPanel;
private JButton insertButton;
private JButton quitButton;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFram window = new MainFram();
window.frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainFram() {
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);
frame.getContentPane().add(getCardsPanel(), BorderLayout.CENTER);
frame.getContentPane().add(getButtonsPanel(), BorderLayout.SOUTH);
}
private JPanel getCardsPanel() {
if (cardsPanel == null) {
cardsPanel = new JPanel();
cardsPanel.setLayout(new CardLayout(0, 0));
cardsPanel.add(getFirstPanel(), "first");
cardsPanel.add(getSecondPanel(), "second");
}
return cardsPanel;
}
private JPanel getFirstPanel() {
if (firstPanel == null) {
firstPanel = new JPanel();
firstPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
firstPanel.add(getFirstLabel());
}
return firstPanel;
}
private JLabel getFirstLabel() {
if (firstLabel == null) {
firstLabel = new JLabel("");
firstLabel.setIcon(new ImageIcon(getClass().getResource("underwater-600x450.png")));
}
return firstLabel;
}
private JPanel getSecondPanel() {
if (secondPanel == null) {
secondPanel = new JPanel();
secondPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
secondPanel.add(getLabel_1());
}
return secondPanel;
}
private JLabel getLabel_1() {
if (secondLabel == null) {
secondLabel = new JLabel("");
secondLabel.setIcon(new ImageIcon(getClass().getResource("Stone.png")));
}
return secondLabel;
}
private JPanel getButtonsPanel() {
if (buttonsPanel == null) {
buttonsPanel = new JPanel();
buttonsPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
buttonsPanel.add(getInsertButton());
buttonsPanel.add(getQuitButton());
}
return buttonsPanel;
}
private JButton getInsertButton() {
if (insertButton == null) {
insertButton = new JButton("Einfügen");
insertButton.addActionListener(this::insertAction);
}
return insertButton;
}
private JButton getQuitButton() {
if (quitButton == null) {
quitButton = new JButton("Quit");
quitButton.addActionListener(e -> System.exit(0));
}
return quitButton;
}
private void insertAction(ActionEvent event) {
CardLayout cardLayout = (CardLayout) cardsPanel.getLayout();
cardLayout.next(cardsPanel);
}
}
The above code requires that the image files, i.e. underwater-600x450.png and Stone.png, be located in the same directory as file MainFram.class. Refer to How to Use Icons.
When you click on the insertButton, the panel containing the underwater-600x450.png image is hidden and the panel containing the Stone.png image is displayed. Clicking the insertButton a second time will hide Stone.png and display underwater-600x450.png. In other words, clicking the insertButton toggles the images.
The first thing to do is using layout managers instead of setting bounds manually:
import java.awt.*;
import javax.swing.*;
public class Mainframe {
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
try {
new Mainframe();
} catch (Exception e) {
e.printStackTrace();
}
});
}
/**
* Create the application.
*/
public Mainframe() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
JFrame frmOceanlife = new JFrame();
frmOceanlife.setTitle("OceanLife");
//frmOceanlife.setBounds(100, 100, 750, 600);
frmOceanlife.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frmOceanlife.getContentPane().setLayout(null);
frmOceanlife.setLayout(new BoxLayout(frmOceanlife.getContentPane(), BoxLayout.PAGE_AXIS));
JButton btnNewButton_4 = new JButton("Quit");
btnNewButton_4.addActionListener(e -> System.exit(0));
//btnNewButton_4.setBounds(640, 6, 81, 29);
JPanel quitPanel = new JPanel();
quitPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
quitPanel.add(btnNewButton_4);
frmOceanlife.getContentPane().add(quitPanel);
JPanel stonesPanel = new JPanel();
frmOceanlife.getContentPane().add(stonesPanel);
JButton btnNewButton_5 = new JButton("Insert");
//btnNewButton_5.setBounds(410, 34, 103, 29);
btnNewButton_5.addActionListener(e -> {
ImageIcon icon = new ImageIcon("Stone.png");
JLabel label = new JLabel(icon);
//label.setBounds(25,25,50,50);
stonesPanel.add(label);
frmOceanlife.revalidate();
});
JPanel insertPanel = new JPanel();
insertPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
insertPanel.add(btnNewButton_5);
frmOceanlife.getContentPane().add(insertPanel);
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
//panel.setBounds(70, 75, 600, 450);
panel.setLayout(new FlowLayout());
panel.setPreferredSize(new Dimension(700,550));
JLabel piclabel = new JLabel(new ImageIcon("underwater-600x450.png"));
panel.add(piclabel);
frmOceanlife.getContentPane().add(panel);
JLabel lblNewLabel_2 = new JLabel("Welcome to Oceanlife - Your Ocean size is 600x450!");
//lblNewLabel_2.setBounds(6, 539, 334, 16);
JPanel infoPanel = new JPanel();
infoPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
infoPanel.add(lblNewLabel_2);
frmOceanlife.getContentPane().add(infoPanel);
frmOceanlife.pack();
frmOceanlife.setVisible(true);
}
}
Next, let's introduce better names and use publicly available images to make the code more readable and more of an mre:
import java.awt.*;
import java.net.*;
import javax.swing.*;
public class Mainframe {
private static final String STONE = "https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/32x32/Circle_Red.png",
OCEAN ="https://media-gadventures.global.ssl.fastly.net/media-server/dynamic/blogs/posts/robin-wu/2014/12/PB110075.jpg";
public Mainframe() {
initialize();
}
private void initialize() {
JFrame frmOceanlife = new JFrame();
frmOceanlife.setTitle("OceanLife");
frmOceanlife.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmOceanlife.setLayout(new BoxLayout(frmOceanlife.getContentPane(), BoxLayout.PAGE_AXIS));
JButton quitBtn = new JButton("Quit");
quitBtn.addActionListener(e -> System.exit(0));
JPanel quitPanel = new JPanel();
quitPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
quitPanel.add(quitBtn);
frmOceanlife.getContentPane().add(quitPanel);
JPanel stonesPanel = new JPanel();
frmOceanlife.getContentPane().add(stonesPanel);
JButton insertBtn = new JButton("Insert");
insertBtn.addActionListener(e -> {
try {
ImageIcon icon = new ImageIcon(new URL(STONE));
JLabel stoneLbl = new JLabel(icon);
stonesPanel.add(stoneLbl);
frmOceanlife.revalidate();
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
});
JPanel insertPanel = new JPanel();
insertPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
insertPanel.add(insertBtn);
frmOceanlife.getContentPane().add(insertPanel);
JPanel oceanPanel = new JPanel();
oceanPanel.setBackground(Color.WHITE);
oceanPanel.setLayout(new FlowLayout());
oceanPanel.setPreferredSize(new Dimension(700,550));
try {
JLabel oceanLbl = new JLabel(new ImageIcon(new URL(OCEAN)));
oceanPanel.add(oceanLbl);
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
frmOceanlife.getContentPane().add(oceanPanel);
JLabel infoLabel = new JLabel("Welcome to Oceanlife - Your Ocean size is 600x450!");
JPanel infoPanel = new JPanel();
infoPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
infoPanel.add(infoLabel);
frmOceanlife.getContentPane().add(infoPanel);
frmOceanlife.pack();
frmOceanlife.setVisible(true);
}
public static void main(String[] args) {
//no change in main
}
}
And add some final touchups :
public class Mainframe {
private static final String STONE = "https://cdn3.iconfinder.com/data/icons/softwaredemo/PNG/32x32/Circle_Red.png",
OCEAN ="https://media-gadventures.global.ssl.fastly.net/media-server/dynamic/blogs/posts/robin-wu/2014/12/PB110075.jpg";
private ImageIcon oceanIcon;
public Mainframe() {
initialize();
}
private void initialize() {
JFrame frmOceanlife = new JFrame();
frmOceanlife.setTitle("OceanLife");
frmOceanlife.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmOceanlife.setLayout(new BoxLayout(frmOceanlife.getContentPane(), BoxLayout.PAGE_AXIS));
JButton quitBtn = new JButton("Quit");
quitBtn.addActionListener(e -> System.exit(0));
JPanel quitPanel = new JPanel();
quitPanel.setLayout(new FlowLayout(FlowLayout.RIGHT));
quitPanel.add(quitBtn);
frmOceanlife.getContentPane().add(quitPanel);
JPanel stonesPanel = new JPanel();
JLabel stoneLbl = new JLabel();
stonesPanel.add(stoneLbl);
frmOceanlife.getContentPane().add(stonesPanel);
JButton insertBtn = new JButton("Insert");
insertBtn.addActionListener(e -> {
try {
ImageIcon icon = new ImageIcon(new URL(STONE));
stoneLbl.setIcon(icon);
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
});
JPanel insertPanel = new JPanel();
insertPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
insertPanel.add(insertBtn);
frmOceanlife.getContentPane().add(insertPanel);
try {
oceanIcon = new ImageIcon(new URL(OCEAN));
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
JLabel oceanLbl = new JLabel();
oceanLbl.setIcon(oceanIcon);
JPanel oceanPanel = new JPanel(){
#Override
public Dimension getPreferredSize() {
return new Dimension(oceanIcon.getIconWidth()+100, oceanIcon.getIconHeight());
};
};
oceanPanel.add(oceanLbl);
oceanPanel.setBackground(Color.WHITE);
oceanPanel.setLayout(new GridBagLayout()); //center image in panel
frmOceanlife.getContentPane().add(oceanPanel);
JLabel infoLabel = new JLabel("Welcome to Oceanlife - Your Ocean size is "+oceanIcon+oceanIcon.getIconWidth()+
"x"+oceanIcon.getIconHeight()+"!");
JPanel infoPanel = new JPanel();
infoPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
infoPanel.add(infoLabel);
frmOceanlife.getContentPane().add(infoPanel);
frmOceanlife.pack();
frmOceanlife.setVisible(true);
}
public static void main(String[] args) {
//no change in main
}
}
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
{
}
}
As you can see from the image above some of the text is being cut off :(
Code:
package malgm.school.clockui.ui;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.*;
import malgm.school.clockui.ClockUI;
import malgm.school.clockui.ResourceLoader;
public class ClockFrame extends JFrame {
private static final long serialVersionUID = 1L;
public final static int FRAME_WIDTH = 600;
public final static int FRAME_HEIGHT = 200;
public ClockFrame() {
setTitle("Clock");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
relocalize();
}
public void relocalize() {
//Wipe controls
this.getContentPane().removeAll();
this.setLayout(null);
initComponents();
}
#SuppressWarnings("unused")
private void initComponents() {
setLayout(new BorderLayout());
JPanel header = new JPanel();
header.setLayout(new BoxLayout(header, BoxLayout.LINE_AXIS));
JPanel section = new JPanel();
section.setLayout(new BoxLayout(section, BoxLayout.LINE_AXIS));
JLabel label = new JLabel("The time is...");
JButton speakButton = new JButton("Speak");
speakButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Runtime rt = Runtime.getRuntime();
try {
Process pr = rt.exec(ClockUI.dir + "/SpeakingClock.exe");
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
JLabel time = new JLabel("test");
ResourceLoader resLoader = new ResourceLoader();
time.setFont(resLoader.getFont(ResourceLoader.FONT_DIGITAL, 72));
section.add(Box.createHorizontalGlue());
section.add(time);
section.add(Box.createHorizontalGlue());
header.add(label);
header.add(Box.createHorizontalGlue());
header.add(speakButton);
add(header, BorderLayout.PAGE_START);
add(section, BorderLayout.CENTER);
}
}
FONT: http://www.dafont.com/digital-7.font
Any help will be greatly appreciated
A key to success with Swing layouts is to avoid setLayout(null) and to pack() the enclosing Window. This lets the contained components adopt their preferred sizes, as shown below. To avoid this pitfall, don't invoke setResizable(false).
import java.awt.*;
import javax.swing.*;
/** #see https://stackoverflow.com/a/23551260/230513 */
public class ClockFrame extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
ClockFrame cf = new ClockFrame();
}
});
}
public ClockFrame() {
setTitle("Clock");
setDefaultCloseOperation(EXIT_ON_CLOSE);
initComponents();
pack();
setLocationRelativeTo(null);
setVisible(true);
}
#SuppressWarnings("unused")
private void initComponents() {
JPanel header = new JPanel();
header.setLayout(new BoxLayout(header, BoxLayout.LINE_AXIS));
JPanel section = new JPanel();
section.setLayout(new BoxLayout(section, BoxLayout.LINE_AXIS));
JLabel label = new JLabel("The time is...");
JButton speakButton = new JButton("Speak");
JLabel time = new JLabel("00:00");
time.setFont(time.getFont().deriveFont(72f));
section.add(Box.createHorizontalGlue());
section.add(time);
section.add(Box.createHorizontalGlue());
header.add(label);
header.add(Box.createHorizontalGlue());
header.add(speakButton);
add(header, BorderLayout.PAGE_START);
add(section, BorderLayout.CENTER);
}
}
After
JLabel time = new JLabel("test");
ResourceLoader resLoader = new ResourceLoader();
time.setFont(resLoader.getFont(ResourceLoader.FONT_DIGITAL, 72));
Add time.setBorder(BorderFactory.createEmptyBorder(0, 20, 20, 20));
After it will look like:
JLabel time = new JLabel("test");
ResourceLoader resLoader = new ResourceLoader();
time.setFont(resLoader.getFont(ResourceLoader.FONT_DIGITAL, 72));
time.setBorder(BorderFactory.createEmptyBorder(0, 20, 20, 20));
change your constructor definition to (EDITED)
public Frame() {
setTitle("Clock");
setSize(FRAME_WIDTH, FRAME_HEIGHT);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
relocalize();
setSize(850, 650);
setLocationRelativeTo(null);
setVisible(true);
}