Center a button or image - java

I'm using Eclipse to create an app for Android. I know you set attributes such as centering a button or image in the XML file but How would you do this in Java?

Its hard to say without knowing what you have. However, if you look through the docs, every xml attribute has a related method in Java. For example, Look at the View Docs and you can see a list of attributes with its corresponding Java method and a description of what it actually does. You should be able to use this to get you started then you can ask a question with code you have tried, precise problem you are having, and any error messages you might be getting. Good luck!

Use code to center your stuff, not attributes in an XML file.
Center a button:
Use a FlowLayout. This will keep the button centered horizontally in the container, but not vertically.
JButton button = new JButton("Click Me!");
panel.setLayout(new FlowLayout(FlowLayout.CENTER));
panel.add(button);
If you want it centered in both directions, you could use BoxLayout.
JButton button = new JButton("Click Me!");
button.setAlignmentX(Component.CENTER_ALIGNMENT);
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(Box.createVerticalGlue());
panel.add(button);
panel.add(Box.createVerticalGlue());
Center image:
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
int xCenter = (this.getWidth() - image.getWidth()) / 2;
int yCenter = (this.getHeight() - image.getHeight()) / 2;
g2d.drawImage(image, xCenter, yCenter, null);
}

Have you tried :
Button button = new Button(getApplicationContext());
button.setLayoutParams(newLayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
button.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);

Related

Is there any standard Java Component with a notification count

I am wondering if there is a Standard Java Component (Icon or JLabel) that offers the abillity to show a notification count like the example below. I am not doing Android Development. I just want to show something similar in a Java desktop client application
The following code in a JLabel subclass would get the same result, but I am more interested in a standard solution. Which automatically derives the correct font size and automatically adjust to the visible space.
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
int w = getWidth();
Font orgFont = g.getFont();
Font deriveFont = orgFont.deriveFont(8.5f);
g2d.setPaint(Color.RED);
g2d.fillOval(w - 12, 0, 12, 12);
g2d.setPaint(Color.BLACK);
g2d.setFont(deriveFont);
g2d.drawString("99", w-10, 10);
g2d.setFont(orgFont);
}
if there is a Standard Java Component (Icon or JLabel)
No there is no standard component.
You might be able to:
Use the Compound Icon. It allows you to combine multiple icons into one.
Add a second JLabel with the notification Icon to the first JLabel. By default a JLabel doesn't have a layout manager but there is no reason you can't use one.
So for example to add the label in the top/right corner you could do:
JLabel main = new JLabel(…);
main.setLayout( new FlowLayout(FlowLayout.FlowLayout.RIGHT, 5, 5) );
JLabel notify = new JLabel(…);
main.add( notify );

How to make rounded corners of JTabbedPane in Java Swing

I need make a JTabbedPane like this (I made the image in Photoshop):
But in my look and feel (based on TabbedPaneUI: javax.swing.plaf.basic.BasicTabbedPaneUI) looks like this:
How can I do it?
I’ve tried change LAF properties, but I didn't find a solution.
If I use setBorder method the swing make this:
jtabbedpane1.setBorder(BorderFactory.createLineBorder(Color.WHITE, 1, true));
Java changed only the upper left corner as outer border as image above shows.
I need a solution that might use the Paint method on an extended JTabbedPane class, but I really don't know if this is correct or how do this.
I read the tutorial above and tried override paintComponent method in my extended JTabbedPane class, see:
public class MyTabbedPane extends JTabbedPane {
[...]
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.YELLOW);
g.drawRoundRect(getX()-12, getY()-11, getWidth()-4, getHeight()-22, 6, 6);
}
}
The result:
https://i.imgur.com/YLXkVRS.jpg
Rounded corners are actually a boolean argument when instantiating a border, as can be seen here with BorderFactory.
So what we can do is something like this:
pane.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 2, true));
Where "true" refers to rounded corners.
If you are interested in customizing the border further, you will most likely have to paint it yourself, in which case I would look here for a further read.
Edit regarding your code:
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.YELLOW);
g.drawPolyLine(new int[]{getX(), getX() getX() + 12}, new int[]{getY() + 12, getY(), getY()});
g.drawPolyLine(.....); // next corner
g.drawPolyLine(.....); // next corner
}
etc. where you repeat for each corner that you want your L shape at.
Here is the start of an answer.
import javax.swing.*;
import java.awt.Dimension;
import javax.swing.plaf.TabbedPaneUI;
import javax.swing.plaf.metal.MetalTabbedPaneUI;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Insets;
public class Bordered{
public static void main(String[] args){
JFrame frame = new JFrame("border check");
JPanel content = new JPanel();
JTabbedPane tabs = new JTabbedPane();
JPanel one = new JPanel();
one.add(new JLabel("first tab"));
one.setOpaque(true);
one.setBackground(Color.WHITE);
JPanel two = new JPanel();
two.add(new JLabel("second tab"));
tabs.add("one", one);
tabs.add("two", two);
tabs.setUI( new MetalTabbedPaneUI(){
#Override
protected void paintContentBorder(Graphics g, int placement, int selectedIndex){
int width = tabPane.getWidth();
int height = tabPane.getHeight();
Insets insets = tabPane.getInsets();
Insets tabAreaInsets = getTabAreaInsets(placement);
int x = insets.left;
int y = insets.top;
int w = width - insets.right - insets.left;
int h = height - insets.top - insets.bottom;
y += calculateTabAreaHeight(placement, runCount, maxTabHeight);
h -= (y - insets.top);
//g.fillRoundRect(x, y, w, h, 5, 5);
}
});
tabs.setPreferredSize(new Dimension(400, 200));
content.add(tabs);
frame.setContentPane(content);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Somethings to note, The inner panel the ones holding the jlabel have square corners. I've shown this by making one white. I've taken some of the boundary code from BasicTabbedPaneUI source code.
They really did not make this easy to manage, but looking at the source for the MetalTabbedPaneUI you can see they draw each border as a line, and it would need to be modified to draw a curve at the ends.

Drawing in JLabel

i have a problem with drawing in my JFrame app. I have these two functions:
Im quite new to such graphics in Java, i was wondering if someone would be kind and help me. I need to add the line on the JLabel called areaImage. I tried using some done code i found here but none worked for me. Is my code usable with some bugs? Or is it completely bad?
Please dont just post a link with some code, Im not skilled enough to understand it and then change it so it fits my app...
This one just makes the window, adds the components:
public void game (int difficulty)
{
getContentPane().removeAll();
areaImage = new JLabel ();
areaImage.setBounds (50,100,650,500);
areaImage.setForeground(Color.WHITE);
areaImage.setBorder(BorderFactory.createMatteBorder(2,2,2,2,Color.BLACK));
add(areaImage);
paint (100,120,500,500, null);
info = new JLabel (" Write your answer into the text field");
info.setBounds(730,180,250,50);
info.setBorder(BorderFactory.createMatteBorder(2,2,2,2,Color.BLACK));
info.setFont(new Font ("Arial", Font.PLAIN, 15));
areaImage.setForeground(Color.red);
add(info);
inputField = new JTextField("");
inputField.setBounds(810, 240, 80, 50);
add(inputField);
checkAnswer = new JButton ("Check");
checkAnswer.setBounds(750, 330, 200, 50);
checkAnswer.setContentAreaFilled(false);
checkAnswer.setOpaque(false);
checkAnswer.addActionListener(this);
checkAnswer.setFont (new Font("Arial",Font.PLAIN, 30));
add(checkAnswer);
next = new JButton ("Next");
next.setBounds(750,440,200,50);
next.setContentAreaFilled(false);
next.setOpaque(false);
next.addActionListener(this);
next.setFont (new Font("Arial",Font.PLAIN, 30));
add(next);
end= new JButton ("Exit");
end.setBounds (750,550,200,50);
end.setFont(new Font("Arial", Font.PLAIN, 30));
end.addActionListener(this);
end.setOpaque(false);
end.setContentAreaFilled(false);
add(end);
revalidate();
repaint();
}
This one is the drawing function:
private void paint (int x, int xx, int y, int yy, Graphics g)
{
super.paint(g);
Graphics2D g2 = (Graphics2D) g;
g.drawLine(x,y,xx,yy);
Line2D lin = new Line2D.Float(100, 100, 250, 260);
g2.draw(lin);
}
Please dont just post a link with some code, Im not skilled enough to understand it
Well that is how you learn. You can't expect us to debug your code and rewrite it every time you have a little problem. If you are not willing to learn by playing with working examples, then I'm not sure how we can help you.
I need to add the line on the JLabel
Then you need to override the painting code for the JLabel. You should never invoke a painting method directly because the painting will be lost the next time Swing determines the component needs to be repainted.
So start by learning how to do painting properly. There is a working example in the Swing tutorial on Custom Painting. The first example just draws a string on a panel but it will be easy enough for you do just draw a line on the label. It is a single statement you add to the paintComponent() method.
The real question is why are you trying to draw this line on a label? I'm sure there is a better solution if we understand the real requirement. You should not be hardcoding the location/size of the line since you don't know how big the label will be.

graphics not showing on resized subpanel?

I am having issues with a small project im working on. I am trying to create a Moveable message panel when holding down the mouse button but i am stuck on one part.
I want to place the A small panel with a size of 50x30 pixels that contains the message "java" in it and have this small panel in a larger panel and place that panel into my JFrame.
However, when i do so the message "java" disappears and only the the small panel in the larger panel appears. I added borders to my panels to make sure that my panels were actually visible. Please help and here is my code:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class MovingPanel extends JFrame {
private String message;
private int x = 100;
private int y = 100;
public MovingPanel() {
JPanel panel = new JPanel();
MessagePanel p1 = new MessagePanel("Java");
panel.setBorder(new LineBorder(Color.RED, 2));
panel.setLayout(null);
p1.setLocation(x, y);
p1.setSize(50, 30);
p1.setBorder(new LineBorder(Color.BLACK, 2));
p1.setLayout(new BorderLayout());
panel.add(p1);
add(panel);
}
public static void main(String[] args) {
MovingPanel frame = new MovingPanel();
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Test Message Panel");
frame.setVisible(true);
}
class MessagePanel extends JPanel {
public MessagePanel(String s) {
message = s;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString(message, x + 20, y + 10);
}
}
}
Maybe you can try to use a simple JLabel component instead of your "MessagePanel".
First thing you need to understand is this.
The second and third arguments of this g.drawString(message, x + 20, y + 10); method are the x and y location of the panel.
With the above being said, you have to remember that it is the x and y location of the containing panel, which is MessagePanel.
You have the size of your MessagePanel object set at 50, 30, yet you are trying to access a point 120 (x + 20) and 110 (100 + 10), which does not exist since you size the size of the panel.
So now that's understood, let's say you want to paint the message at the very left corner of the MessagePanel, so you try and do this g.drawString(message, 0, 0);. This still would show anything as the point starts from the bottom left corner of the message, so the message would actually be riding just above the visible area.
When drawing strings, you need to consider the FontMetrics, which allows you to get the size of the string you are trying to draw, so you can position the message exactly on the screen where you want it.
A simple fix would be just set an x and y a little above 0, 0, like 15, 15. Though this might get your message to draw, it wouldn't be centered. You can keep on changing and getting different numbers to check if it is aligned in the middle, but the proper way is to use FontMetrics
As a said a simple (but maybe not desired) fix is to just change this
g.drawString(message, x + 20, y + 10);
To
g.drawString(message, 15, 15);
And you will see the message.
Instead of what you are doing though, this is how I would do it.
Instead of using two panels, I would just use one - the one that's doing the painting.
Don't set the size of it, instead override getPrefferedSize inside that class, to whatever size you want the main panel to me.
When you draw, just draw a rectangle the size you want at the specified coordinates.
Also draw the message in the same paintComponent method.
call pack() on the JFrame.
If you do the above, there's no need to try and move the location of the MessagePanel. Instead move the x and y coordinates when you call repaint, You can have offsets for the message. Like
int boxX = 100;
int boxY = 100;
int messageOffset = 15;
Then you can paint like this
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.drawRect(boxX, boxY, 50, 30);
g.drawString(message, boxX + messageOffset, boxY + messageOffset);
}
Now in your action methods, just alter the boxX and/or boxY and call repaint.
Also, if you want a thicker line, look into Graphics2D API, you can setStroke.

JPanel how to add a ToolTipText

I have a little problem, I need to add a ToolTipText to JPanel. How should I do this?
I want to have a tooltip when I have mouse over the circle.
This is part of my code.
JPanel component1 = new JPanel();
JPanel component11 = new JPanel();
okno.add(component1,"align left,cell 0 0, h 75!, grow,wrap");
component1.setLayout(new MigLayout("","[][grow][grow]", "[grow]"));
component1.add((okno.add(creLab("Kraj", i, czcionka, etykietki))),"left align, cell 0 0");
component1.add(t1,"cell 1 0,grow");
//component1.add(new circle1(),"right align, cell 2 0,h 50!, w 53!, gapleft 50, wrap");
component1.add(component11," right align, cell 2 0, h 30!, gapleft 300, wrap");
component11.setLayout(new MigLayout("","[]","[]"));
component11.add(new circle1(),"cell 0 0,h 50!, w 50!, dock north");
component11.setToolTipText("<html>W polu obok wpisz kraj pochodzenia towaru</html>");
I add also code of circle1:
class circle1 extends Applet{
public void paint(Graphics g){
setForeground(Color.yellow);
g.drawOval(0, 0, 50, 50);
g.fillOval(0, 0, 50, 50);
g.setColor(Color.black);
g.drawString("Jak", 14, 14);
g.drawString("wpisac", 3, 28);
g.setColor(Color.red);
g.drawString("kraj?", 14, 42);
//g.drawString(arg0, arg1, arg2)
}
}
Take a look at JComponent#getToolTipText(MouseEvent)
This will allow you to determine what text to return based on the location of the mouse.
It's difficult to determine for your code snippet, exactly where the circle is been drawen, but I would avoid drawing directly to the surface of the applet, but instead use a custom component (like a JPanel) instead (overriding its paintComponent method). This I would then either add to the applet or to the control panel.
This way your going to avoid issues with the mouse events been consumed
I would also take a look at Ellipse2D, which can be used to determine if the ellipse contains a given point
The first thing is to identify when the mouse is inside the circle. To do that you could verify the mouse position on a mouseMotionlister according to the circle area
http://www.java2s.com/Code/JavaAPI/javax.swing/JPaneladdMouseMotionListenerMouseMotionListenerlis.htm
Once you identify this situation you could proceed to change the tooltip
See Playing With Shapes. You can create a JLabel with a ShapeIcon. Then you just use the setToolTipText() method of the JLabel. You can then add the label to the panel like any other component.
Now that you can use a component to represent a Shape there is no need to do custom painting. Just create a panel add add components to the panel. You can also create JLabels for all your text strings.
Don't do custom painting, unless you have a good reason to do so.

Categories