so I would like to know if it's possible to put things like buttons, text boxes, words, progress bars, ect, ect, on top of an already existing, in this example, JLabel.
Here is the image of the undercoated frame I made, followed by the snippet of code that is associated with this undercoated frame.
(I dont have 10 reputation, so here is a link to a photo)
http://prntscr.com/15516f
Map.setTitle("Map");
Map.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Map.setUndecorated(true);
Map.setBackground(new Color(0,0,0,0));
Map.setLayout(new FlowLayout());
JLabel Background = new JLabel(new ImageIcon(getClass().getResource("Map.png")));
Background.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
initialClick = e.getPoint();
getComponentAt(initialClick);
}
});
Background.addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
// get location of Window
int thisX = Map.getLocation().x;
int thisY = Map.getLocation().y;
// Determine how much the mouse moved since the initial click
int xMoved = (thisX + e.getX()) - (thisX + initialClick.x);
int yMoved = (thisY + e.getY()) - (thisY + initialClick.y);
// Move window to this position
int X = thisX + xMoved;
int Y = thisY + yMoved;
Map.setLocation(X, Y);
}
});
Map.add(Background);
Map.setSize(507,512);
Map.setLocation(0, 100);
Map.setResizable(false);
Map.setVisible(false);
on a side note, and I KNOW this is FlowLayout(), but when I try to add something else, it'll just put itself above, or below my map.
I'd just like to know if I could put things on top of this Map.
Maybe I should put the image in in another way besides the JLabel?
Look into JLayeredPane and similar strategies. See How to Use Layered Panes for more details.
Related
Basically, I'm trying to make a button that has the text aligned to the left (so I'm using setHorizontalAlignment(SwingConstants.LEFT)) and the image on the right border of the button, far from the text.
I already tried setHorizontalTextAlignment(SwingConstants.LEFT), but that just makes the text go relativity to the left of the icon, which is not exactly what I want, since I needed the icon to be secluded from it.
Also, I can't make any fixed spacing because it's a series of buttons with different texts with different sizes.
I can't make any fixed spacing because it's a series of buttons with different texts with different sizes.
You can dynamically change the spacing with code like:
JButton button = new JButton("Text on left:")
{
#Override
public void doLayout()
{
super.doLayout();
int preferredWidth = getPreferredSize().width;
int actualWidth = getSize().width;
if (actualWidth != preferredWidth)
{
int gap = getIconTextGap() + actualWidth - preferredWidth;
gap = Math.max(gap, UIManager.getInt("Button.iconTextGap"));
setIconTextGap(gap);
}
}
};
button.setIcon( new ImageIcon("copy16.gif") );
button.setHorizontalTextPosition(SwingConstants.LEADING);
This is a derivative of camickr's answer to allow editing in a GUI builder as well as placing it in a dynamic layout. I also removed the UIManager.getInt("Button.iconTextGap") so the gap will shrink to 0 if necessary.
I called it a 'Justified' button in analogy with justified text alignment (stretches a paragraph to left & right by growing width of space characters).
public class JustifiedButton extends JButton {
#Override
public void doLayout() {
super.doLayout();
setIconTextGap(0);
if (getHorizontalTextPosition() != CENTER) {
int newGap = getSize().width - getMinimumSize().width;
if (newGap > 0)
setIconTextGap(newGap);
}
}
#Override
public Dimension getMinimumSize() {
Dimension minimumSize = super.getMinimumSize();
if (getHorizontalTextPosition() != CENTER)
minimumSize.width -= getIconTextGap();
return minimumSize;
}
#Override
public Dimension getPreferredSize() {
Dimension preferredSize = super.getPreferredSize();
if (getHorizontalTextPosition() != CENTER)
preferredSize.width -= getIconTextGap();
return preferredSize;
}
}
This is not exactly production-ready and needs some field-testing. If I find anything, I'll edit the code.
[edit] Now works for vertical text alignments. Also simplified a bit.
[edit2] Also manipulate getPreferredSize to play nice with scroll pane (otherwise it keeps growing and never shrinks again)
You can add a layout manager to your button.
JButton btn = new JButton();
btn.add(new JLabel(text));
btn.add(new JLabel(img));
btn.setLayout(/*best layout choice here*/);
btn.setPreferredSize(new Dimension(x,y));
btn.setMaximumSize(new Dimension(maxX, minY));
btn.setMinimumSize(new Dimension(minX, minY)); //this one is most important when it comes to layoutmanagers
Sorry I can't be much help when it comes to picking out a good layout - But this will eventually get you what you want. Maybe someone else can comment on which one to use.
I am using this code to get the X and Y coordinates of an image placed as icon of a jLable.
This method to get the coordinates was suggested by an answer to this question.
private void lblMapMouseClicked(java.awt.event.MouseEvent evt) {
lblMap.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
double X = e.getX();
double Y = e.getY();
System.out.println("X: " + X + "Y: " + Y );
}
});
}
When I run this public void mouseClicked(MouseEvent e) { } gets called multiple times.
Exactly the amount of times I click on the image.
Eg: If I'm clicking on it for the 3rd time ,
X and Y values from the System.out.println line , gets printed 3 times.
And it increases as the number of times I click increases.
Can any of you explain why this happens? And how can I fix it? :)
The problem is that you are adding a new listener again and again when click happens, here.
private void lblMapMouseClicked(MouseEvent evt)
{
lblMap.addMouseListener(new MouseAdapter()
{
...
Instead, change your code to this.
private void lblMapMouseClicked(MouseEvent e)
{
double X = e.getX();
double Y = e.getY();
System.out.println("X: " + X + "Y: " + Y);
}
And it should fix the problem.
Hope this helps.
it looks for me that every time image is clicked new mouse listener is added.. do also
System.out.println(this)
to check from which instance of mouse listener it is actually printed
The problem with above code was you are creating new Mouse event with every click on the image.
// Create a Mouse pressed Event
mouseLis = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
actionMenthod(e);
}
};
Here am attaching the my event to lblMap.
lblMap.addMouseListener(mouseLis);
After this event happens you have to remove this event from the lblmap.
lblMap.removeMouseListener(mouseLis);
After when I click again only one event will be there then it prints only once.
I am trying to make a player in java.
Have made a seekbar using jprogressbar as shown in this link in Andrew Thompson's answer,
I have been able to add a mouselistener and detect click on jprogressbar, but how do I get the selected value of jprogressbar to which I will seek my bar to?
I tried,
progressBar.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
int v = progressBar.getSelectedValue();
jlabel.setText("----"+v);
}
});
But didn't work as I expected, could not even find anything on internet.
Please help me. Thanks for your time and effort, really appreciated.
You would probably have to calculate the location on the JProgressBar based solely on the mouse click co-ordinates. You could essential do this:
progressBar.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
int v = progressBar.getValue();
jlabel.setText("----"+v);
//Retrieves the mouse position relative to the component origin.
int mouseX = e.getX();
//Computes how far along the mouse is relative to the component width then multiply it by the progress bar's maximum value.
int progressBarVal = (int)Math.round(((double)mouseX / (double)progressBar.getWidth()) * progressBar.getMaximum());
progressBar.setValue(progressBarVal);
}
});
So, I have a jFrame in which I'm building the main interface window of a chat. This window/jFrame has several buttons , each of which show a jDialog (Which I created previously in Netbeans dragging a jDialog onto the parent(?) jFrame).
My problem is that both windows are set to undecorated = true and so I wish to let the user drag and move all windows at will by clicking and dragging a portion of the windows (Which emulate the title bar when not undecorated)
In all the jFrames I have accomplished this by the following code just after initComponents():
final Point point = new Point(0,0); // Why 'final' and not simply Point point?
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if(!e.isMetaDown()){
point.x = e.getX();
point.y = e.getY();
System.out.println("Ratón pulsado: " + point.x + "," + point.y);
}
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
if(!e.isMetaDown() && point.y <= 17){ //Coordinates of title bar, any X and up to 17px from the top border
Point p = getLocation();
setLocation(p.x + e.getX() - point.x, p.y + e.getY() - point.y);
System.out.println("Ratón movido: " + (p.x + e.getX() - point.x) + "," + (p.y + e.getY() - point.y));
}
}
});
However, I don't know how to use this code in the jDialog. When I right click it in the Navigator, and select Customize code, then I can't paste it in there because the whole jFrame stops working. I'm new in this thing of jDialogs children of jFrames, so please help me with some guidelines :) Thanks
Well, as #mKorbel suggested, I headed to here where I found a nice class called ComponentMover which helped me to do this. I'll need 2 more reputation so I saved the link to get back and upvote when I'm able to do it.
I'll have to ensure it works perfect and exactly in the way I want, but looks great! Thanks!
I wish to place a small Jframe right above the Button, on ActionPerformed
I directly tried to get the X (getX()) and Y(getY()) co-ordinates of the JScrollPane in which the button is added, but it always seems to return wrong co-coordinates
values returned by jScrollPane1.getLocation()
java.awt.Point[x=10,y=170]
The above values are same independent on where I place the JScrollPane on the screen.
This works if I remove the JScrollPane and directly try to get the Jpanels co-ordinates!!
for example
private void showDialog() {
if (canShow) {
location = myButton.getLocationOnScreen();
int x = location.x;
int y = location.y;
dialog.setLocation(x - 466, y - 514);
if (!(dialog.isVisible())) {
Runnable doRun = new Runnable() {
#Override
public void run() {
dialog.setVisible(true);
//setFocusButton();
//another method that moving Focus to the desired JComponent
}
};
SwingUtilities.invokeLater(doRun);
}
}
}
This nice method will help you:
// Convert a coordinate relative to a component's bounds to screen coordinates
Point pt = new Point(component.getLocation());
SwingUtilities.convertPointToScreen(pt, component);
// pt is now the absolute screen coordinate of the component
Add: I didn't realise, but like mKorbel wrote, you can simply call
Point pt = component.getLocationOnScreen();
Since you want to spawn a new frame right above a given component, you want to get the screen coordinates of your component.
For this, you need to use the getLocationOnScreen() method of your component.
Here is a useful code snippet :
public void showFrameAboveCmp(Frame frame, Component cmp) {
Dimension size = cmp.getSize();
Point loc = cmp.getLocationOnScreen();
Dimension frameSize = frame.getSize();
loc.x += (size.width - frameSize.width)/2;
loc.y += (size.height - frameSize.height)/2;
frame.setBounds(loc.x, loc.y, frameSize.width, frameSize.height);
frame.setVisible(true);
}