Is it possible to create a JLabel with a right-justified icon and text and the icon is on the right, like this:
I've seen this question, but is it really the best approach?
Perhaps this would be more what you're looking for? It should align everything on the right side of the panel (more so than the example you were looking at):
import java.awt.*;
import javax.swing.*;
public class TempProject
{
public static void main(String args[])
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
Box mainContent = Box.createVerticalBox();
mainContent.add(TempProject.getLabel("abc"));
mainContent.add(TempProject.getLabel("Longer"));
mainContent.add(TempProject.getLabel("Longerest"));
mainContent.add(TempProject.getLabel("Smaller"));
JFrame frame = new JFrame();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setContentPane(mainContent);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public static JLabel getLabel(String text){
JLabel c = new JLabel(text);
c.setHorizontalTextPosition(SwingConstants.LEADING);
c.setAlignmentX(SwingConstants.RIGHT);
c.setIcon(UIManager.getIcon("FileChooser.detailsViewIcon"));
return c;
}
}
The example cited uses layout and label properties for right/left justification.
Additionally, consider implementing the Icon interface in a JList renderer, where setHorizontalAlignment() and setVerticalAlignment() may be used to control the relative geometry. This related TableCellRenderer illustrates the principle.
Related
I need a program that displays many images and I need window that can be scrolled for that. I read the documentation and searched on the forum but I still didn't manage to do it. I tried with JScrollPane and JFrame as you can see below.
JScrollPane class:
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.*;
public class EmojiWindow extends JScrollPane {
private void newImg(String emojiLocation, String emojiName) {
JLabel emoji = new JLabel(new ImageIcon(emojiLocation));
Emoji.setToolTipText(emojiName);
add(emoji);
Emoji.addMouseListener(new MouseListener(){
public void mouseClicked(MouseEvent arg0) {}
public void mouseEntered(MouseEvent arg0) {}
public void mouseExited(MouseEvent arg0) {}
public void mouseReleased(MouseEvent arg0) {}
#Override
public void mousePressed(MouseEvent e) {
if(SwingUtilities.isLeftMouseButton(e))
{
JFrame frame = new JFrame("new frame");
frame.setSize(300, 10);
frame.setVisible(true);
}
}
});
}
public EmojiWindow(){
newImg("fbike.png", "Riding a bike");
newImg("fdizzy.png", "Dizzy");
newImg("fcubehead.png", "Cube head");
newImg("fhappy.png", "Happy");
}
}
Main:
import java.awt.*;
import javax.swing.*;
public class Main {
public static void main(String[] args)
{
EmojiWindow scrollPane = new EmojiWindow();
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JFrame window = new JFrame();
window.add(scrollPane, BorderLayout.SOUTH);
window.setSize(300, 400);
window.setVisible(true);
}
}
Edit:
Changed the variables' and methods' names to camel-case to stop triggering people.
First of all, learn and follow Java naming conventions. Variable names should NOT start with an upper case character. Any example you find in this forum or text book uses this convention. Learn by example!!!
Don't extend JScrollPane. There is no need to do this as you are not adding any new functionality to the class.
Also, never add components to a JScrollPane. A single component is added to the JViewPort of the scroll pane.
So in this case you would create a JPanel using an appropriate layout manager. Then you add the panel to the viewport of the scroll pane.
So the basic code might be something like:
JPanel imagePanel = new JPanel();
imagePanel.add( label1 );
imagePanel.add( label2 );
...
JScrollPane scrollPane = new JScrollPane( imagePanel );
window.add( scrollPane );
Read the Swing Tutorial for working examples of all the Swing basics.
Edit:
You can also try the Wrap Layout which will cause components to wrap to the next line when a horizontal row is full.
I have a JDialog with a title written at the top. I call this JDialog for two different cases and if it is not the default I change the text to something else. This works fine but the position is then too far to the right.
I have tried numerous methods such as:
TitleText.setText("Edit Fuse");
TitleText.setAlignmentY(JLabel.CENTER_ALIGNMENT);
//TitleText.setHorizontalAlignment(JDialog.);
//TitleText.setLayout(new FlowLayout(FlowLayout.LEFT));
None of them even move the text. I am using a Free Design Layout for the entire JDialog. If I must I'll just create another JLable and hide/unhide but I thought this would be simple. Anyone know how to do this?
I am using a Free Design Layout for the entire JDialog
Don't do this if you want the title JLabel's text to be at the top and be centered. Instead have the JDialog's main JPanel use BorderLayout, and add the JLabel to it BorderLayout.PAGE_START, also known as BorderLayout.North.
The main JPanel can then hold the rest of your GUI, likely in its own JPanel, using its own layout manager, and other JPanels, in its BorderLayout.CENTER position.
Also, don't use JLabel.CENTER_ALIGNMENT, a float, but rather use JLabel.CENTER, an int, which is the appropriate parameter for the setHorizontalAlignment(...) method.
Finally, I must give you an unsolicitated side recommendation to be sure that your variable names begin with a lower-case letters and not upper case letters so that they comply with Java naming rules. This is important if you want others, such as folks here who'd like to help you, to rapidly understand your code.
For example:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
#SuppressWarnings("serial")
public class LayoutExample extends JPanel {
private static final float SIZE = 32;
private static final int TIMER_DELAY = 2000;
private String[] TITLE_STRINGS = { "Title 1", "Title 2",
"Some Random Title", "Fubars Rule!", "Snafus Drool!" };
private int titleIndex = 0;
private JLabel titleLabel = new JLabel(TITLE_STRINGS[titleIndex],
JLabel.CENTER);
public LayoutExample() {
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, SIZE));
setLayout(new BorderLayout());
add(titleLabel, BorderLayout.PAGE_START);
// the rest of your GUI could be added below
add(Box.createRigidArea(new Dimension(500, 300)), BorderLayout.CENTER);
new Timer(TIMER_DELAY, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
titleIndex++;
titleIndex %= TITLE_STRINGS.length;
titleLabel.setText(TITLE_STRINGS[titleIndex]);
}
}).start();
}
private static void createAndShowGui() {
JFrame frame = new JFrame("LayoutExample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new LayoutExample());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
I'm following through a book called "The JFC Swing Tutorial (Second Edition)" and I'm pretty much at the start I have followed this code and it should be displaying the button and the label in the content pane, but All im getting is a blank screen. any ideas?
Thanks.
import java.awt.GridLayout;
import javax.swing.*;
public class m extends JFrame
{
void UserFrame()
{
//JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Hellow You");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel jp = new JPanel(new GridLayout(0,1));
//makes label
JLabel label = new JLabel("Sup ");
//adds to the frames content pane a label
frame.getContentPane().add(label);
JButton button = new JButton("Hai");
frame.getContentPane().add(button);
jp.add(button);
jp.add(label);
jp.setBorder(BorderFactory.createEmptyBorder(30,30,10,30));
//pack set the window to what it needs AKA to display all components
frame.pack();
//frame.setSize(250, 250);
//shows window
frame.setVisible(true);
}
public static void main(String[] args)
{
final m window = new m();
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
window.UserFrame();
}
});
}
}
Simply add
frame.add(jp);
just before
frame.pack();
What's happening here? You correctly add all your widgets to a JPane, but you basically threw that JPane away and didn't use it anywhere.
This will be sufficient just to get it to work properly.
If you want to do it correctly, you should also remove frame.getContentPane().add(label); and frame.getContentPane().add(button); (Thank you #dic19 for noting that!). These will not work the way you used it.
I'm using Container.getComponents() to get an array of Components stored inside the Container. I'm then modifying one of these Components (which happens to be a JLabel), but the changes are not showing on the GUI.
So I'm thinking maybe the method creates new instances of each Component which prevents me from making changes to the original component?
Here's my code:
Component[] components = source.getComponents();
if(components.length >= 2) {
if(components[1] instanceof JLabel) {
JLabel htmlArea = (JLabel) components[1];
htmlArea.setText("<html>new changes here</html>");
htmlArea.revalidate();
}
}
It is either another problem outside of the code, or you are doing this from the wrong thread.
Any changes on Swing components should be done in the event dispatch thread. Often is it most easy to surround the changing code with EventQueue.invokeLater(...) (or SwingUtilities.invokeLater, this is the same).
And make sure your component is actually visible on the screen.
There is no need to revalidate() or repaint() anything (unless you are doing something really strange)!
Where is your SSCCE that demonstrates your problem???
It works fine for me:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class TabbedPaneLabel extends JFrame
{
JTabbedPane tabbedPane;
public TabbedPaneLabel()
{
tabbedPane = new JTabbedPane();
add(tabbedPane);
tabbedPane.addTab("First", createPanel("<html>label with text</html>"));
tabbedPane.addTab("Second", createPanel("another label"));
JButton remove = new JButton("Change Label on first tab");
add(remove, BorderLayout.SOUTH);
remove.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Component[] components = tabbedPane.getComponents();
JPanel panel = (JPanel)components[0];
JLabel label = (JLabel)panel.getComponent(0);
String date = new Date().toString();
label.setText("<html>" + date + "</html>");
}
});
}
private JPanel createPanel(String text)
{
JPanel panel = new JPanel();
panel.add( new JLabel(text) );
return panel;
}
public static void main(String args[])
{
TabbedPaneLabel frame = new TabbedPaneLabel();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.setSize(300, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
i want to add icons in jframe which does some action while click like buttons.
You'll probably want to create a JLabel with an Icon and add a MouseListener to the JLabel, like so:
import javax.swing.*;
import java.awt.event.*;
public class Foo {
public static void main(String args[]) {
// Create a "clickable" image icon.
ImageIcon icon = new ImageIcon("path/to/image.jpg");
JLabel label = new JLabel(icon);
label.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
System.out.println("CLICKED");
}
});
// Add it to a frame.
JFrame frame = new JFrame("My Window");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(label);
frame.pack();
frame.setVisible(true);
}
}
You can create a JButton which takes an icon as a parameter and displays it.
JButton
I highly suggest trying that out first. Hopefully that will help