Text and JLabel - java

I have a JLabel which contains a picture and I set a text to this JLabel using the setText method. My problem is that I want to choose the position of the text I have just set. Do you have any ideas to perform that ?
//This the code i have
this.label = new JLabel ();
this.label.setText("My text");
this.label.setForeground(Color.BLACK);
this.add(label);

Can you try
public class LabelTextPos extends JLabel {
public static void main(String args[]) {
LabelTextPos label = new LabelTextPos();
JFrame frame = new JFrame();
frame.add(label);
frame.pack();
frame.setVisible(true);
}
#Override
public void paint(Graphics g) {
g.setColor(Color.BLACK);
g.drawString("Sample", 100, 100);
}
}

Related

Issue when adding two JPanels

I'm trying to add two JPanels to a JFrame, one with a simple backround and another one with buttons etc. Either I get only buttons or only the background. I can't find a solution to my problem anywhere, so any help would be appreciated. I'm still new to Java, so please don't hate.
GuiMainMenu:
public class GuiMainMenu extends JFrame implements ActionListener, KeyListener {
private static final long serialVersionUID = -7936366600070922227L;
Color blue = new Color(114, 137, 218);
Color gray = new Color(44, 47, 51);
Color white = new Color(255, 255, 255);
ImagePanel panel = new ImagePanel(new ImageIcon("image.png").getImage());
public static int width;
public static int height;
JPanel p = new JPanel();
JPanel p1 = new JPanel();
JLabel l = new JLabel();
JLabel l1 = new JLabel();
JLabel l2 = new JLabel();
JButton b = new JButton();
JButton b1 = new JButton();
JButton b2 = new JButton();
String title = "-";
public GuiMainMenu() {
setSize(m.X, m.Y);
setTitle(title);
setResizable(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addKeyListener(this);
p.setLayout(null);
width = getWidth();
height = getHeight();
getRootPane().addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
width = getWidth();
height = getHeight();
addButtons();
addLabels();
}
});
addLabels();
addButtons();
add(p);
add(panel);
setVisible(true);
}
public void addLabels() {
l.setSize(width, height);
l.setLocation(5, -40);
l.setText("x");
l.setHorizontalAlignment(SwingConstants.LEFT);
l.setVerticalAlignment(SwingConstants.BOTTOM);
l.setForeground(blue);
l.setFont(new Font("Trebuchet MS", Font.PLAIN, 15));
l1.setSize(width, height);
l1.setLocation(-22, -40);
l1.setText("y");
l1.setHorizontalAlignment(SwingConstants.RIGHT);
l1.setVerticalAlignment(SwingConstants.BOTTOM);
l1.setForeground(blue);
l1.setFont(new Font("Trebuchet MS", Font.PLAIN, 15));
l2.setText("test label");
l2.setSize(width, height);
l2.setLocation(0, -75);
l2.setVerticalAlignment(SwingConstants.CENTER);
l2.setHorizontalAlignment(SwingConstants.CENTER);
l2.setForeground(blue);
l2.setFont(new Font("Trebuchet MS", Font.BOLD, 26));
p.add(l);
p.add(l1);
p.add(l2);
validate();
}
public void addButtons() {
b.setText("button0");
b.setFocusable(false);
b.setBorder(null);
b.setLocation(width / 2 - 200, height / 2 - 35);
b.setSize(400, 35);
b.setForeground(white);
b.setBackground(blue);
b.addActionListener(this);
b1.setText("button1");
b1.setFocusable(false);
b1.setBorder(null);
b1.setLocation(width / 2 - 200, height / 2 + 10);
b1.setSize(400, 35);
b1.setForeground(white);
b1.setBackground(blue);
b1.addActionListener(this);
p.add(b);
p.add(b1);
validate();
}
#Override
public void actionPerformed(ActionEvent arg0) {
}
#Override
public void keyPressed(KeyEvent arg0) {
}
#Override
public void keyReleased(KeyEvent arg0) {
}
#Override
public void keyTyped(KeyEvent arg0) {
}
}
ImagePanel Class:
class ImagePanel extends JPanel {
private static final long serialVersionUID = -7270956677693528549L;
private Image img;
public ImagePanel(String img) {
this(new ImageIcon(img).getImage());
}
public ImagePanel(Image img) {
this.img = img;
}
public void paintComponent(Graphics g) {
g.drawImage(img, 0, 0, GuiMainMenu.width, GuiMainMenu.height, null);
}
}
p.setLayout(null);
Don't use a null layout. Swing was designed to be used with layout managers.
Read the section from the Swing tutorial on Layout Managers for more information and working examples.
Either I get only buttons or only the background
add(p);
add(panel);
The default layout manager for a JFrame is the BorderLayout. If you don't specify a constraint both components get added to the CENTER. However only the last one added will be displayed.
Try the following to see the difference:
add(p, BorderLayout.PAGE_STRT);
add(panel, BorderLayout.CENTER);
one with a simple backround and another one with buttons etc.
However above is not what you want. Swing components have a parent/child relationship. So what you really need is:
backgroundPanel.add(buttonPanel);
add(backgroundPanel, BorderLayout.CENTER);
Note I used more meaningful names because "p" and "panel" and not descriptive. Use descriptive names for variable so people can understand what they mean.
I suppose you want to display a JFrame with a background image and various components. I think after reviewing your code that there is some misunderstanding on your part causing the problem.
I've created a short snippet of code that does the basics and maybe helps you to solve your problem. (Not tested!)
#SuppressWarnings("serial")
public class GuiMainMenu extends JFrame{
private BufferedImage imageBackground; // TODO: load your background image
public GuiMainMenu(){
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(1024, 768));
setMinimumSize(new Dimension(800, 600));
// TODO: setLayout if needed
JPanel panel = (JPanel)add(new JPanel(){
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(imageBackground, 0, 0, this);
}
});
addOtherComponents(panel);
pack();
setLocationRelativeTo(null);
setTitle("Your Title her");
setVisible(true);
}
private void addOtherComponents(JPanel panel){
//TODO: add the needed Stuff
//panel.add ...
}
}

how can I make an undecorated window containing a button with java?

I've created a round window with java , It's undecorated ..the problem is when I tried to add a button or a label in the frame ,nothing is shown inside.
could someone Please help me ?
edited
this is the code I made :
public class main {
static public JPanel p;
public static JLabel label1 ;
public static JLabel label2 ;
public static void main(String[] args) {
label1 = new JLabel("Name : ");
label2= new JLabel("surname : ");
p=new JPanel();
p.add(label1);
p.add(label2);
JFrame frame = new JFrame();
frame.add(p);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setUndecorated(true);
frame.setShape(new RoundRectangle2D.Double(200, 200, 200, 200, 200, 200));
frame.setSize(500, 500);
frame.setContentPane(p);
frame.setVisible(true);
}
}

Why is my JPanel messing with other components on my JFrame?

So I have a JFrame which contains a JPanel that holds a JList component.
Then I have another JPanel for my paintComponent() which also returns a dimension.
But when I set the size for the dimension, it tries to relocate my other JPanel.
Here is my code for the paintComponent():
class drawOnPanel extends JPanel {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.BLUE);
}
#Override
public Dimension getPreferredSize(){
return new Dimension(250, 250);
}
}
Then I have my JFrame which calls the drawOnPanel class:
public static void mainFrame() {
JFrame f = new MTGSAMPServerReference();
f.setTitle("MTG SAMP Server Reference Guide");
f.pack();
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new drawOnPanel());
f.setSize(330, 300);
f.setLocationRelativeTo(null);
}
And then I have my JList which is on my JPanel:
public void MainMenu() {
JPanel controls = new JPanel(new BorderLayout(5,5));
final CardLayout cl = new CardLayout();
final JPanel panel = new JPanel(cl);
controls.add(panel);
this.getContentPane().setLayout(new FlowLayout(FlowLayout.LEADING));
list = new JList<Object>(mainMenu);
list.setVisibleRowCount(7);
select = new JButton("Select");
exit = new JButton("Exit");
select.addActionListener(this);
exit.addActionListener(this);
controls.add(new JScrollPane(list));
JPanel basePanel = new JPanel(new GridLayout(0, 1));
basePanel.add(select);
basePanel.add(exit);
controls.add(basePanel, BorderLayout.PAGE_END);
add(controls);
refreshFrame();
}
When I try to draw on my paintComponent() JPanel, it draws, but the coordinates that I indicate are not correctly drawn.
Does anyone know why this is happening?
Thanks in advance!
EDIT: Here are some screenshots of my program.
This one is what my program looks like when I don't include drawOnPanel:
And this one is what my program looks like when I include drawOnPanel:
I just want it to draw on the right side of the JList, without moving the JList. As you can see, it adjusts the other JPanel.
Any and all help is appreciated!
EDIT: Here is my SSCCE.
EDIT: Here is my SSCCE code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public final class SSCCE1 extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
JList list;
JButton select;
JButton exit;
Object[]mainMenu = {"Value 1", "Value 2", "Value 3", "Value 4"};
public SSCCE1() {
MainMenu();
}
public void MainMenu() {
JPanel controls = new JPanel(new BorderLayout(5,5));
final CardLayout cl = new CardLayout();
final JPanel panel = new JPanel(cl);
controls.add(panel);
this.getContentPane().setLayout(new FlowLayout(FlowLayout.LEADING));
list = new JList<Object>(mainMenu);
list.setVisibleRowCount(7);
select = new JButton("Select");
exit = new JButton("Exit");
controls.add(new JScrollPane(list));
JPanel basePanel = new JPanel(new GridLayout(0, 1));
basePanel.add(select);
basePanel.add(exit);
controls.add(basePanel, BorderLayout.PAGE_END);
add(controls);
revalidate();
repaint();
SSCCE1.this.repaint();
}
public void createAndShowGUI() {
mainFrame();
SSCCE1.this.repaint();
}
public static void mainFrame() {
JFrame f = new SSCCE1();
f.setTitle("My SSCCE");
f.pack();
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new drawOnPanel()); // When this is uncommented, it messes with the other JPanel, but when commented, it works fine, but does not allow drawing on the other JFrame.
f.setExtendedState(JFrame.MAXIMIZED_BOTH);
f.setLocationRelativeTo(null);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
SSCCE1 gui = new SSCCE1();
gui.createAndShowGUI();
}
});
}
#Override
public void actionPerformed(ActionEvent ae) {
}
}
class drawOnPanel extends JPanel {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.BLUE);
}
#Override
public Dimension getPreferredSize(){
return new Dimension(250, 250);
}
}
Make setVisible() last, after a adding, packing and locating. Complete examples are seen here and here.
f.add(…);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
Addendum: Here's a variation on your example, without the invisible panel. Absent a compelling reason to extend JFrame, just create one and add your components.
import java.awt.*;
import javax.swing.*;
/** #see https://stackoverflow.com/a/18038765/230513 */
public class SSCCE2 {
private JList list;
private JButton select;
private JButton exit;
private Object[] mainMenu = {"Value 1", "Value 2", "Value 3", "Value 4"};
public JPanel mainMenu() {
JPanel controls = new JPanel(new BorderLayout(5, 5));
list = new JList(mainMenu);
list.setVisibleRowCount(7);
select = new JButton("Select");
exit = new JButton("Exit");
controls.add(new JScrollPane(list));
JPanel basePanel = new JPanel(new GridLayout(0, 1));
basePanel.add(select);
basePanel.add(exit);
controls.add(basePanel, BorderLayout.PAGE_END);
return controls;
}
public void createAndShowGUI() {
JFrame f = new JFrame("My SSCCE");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new DrawOnPanel());
f.add(mainMenu(), BorderLayout.WEST);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
SSCCE2 gui = new SSCCE2();
gui.createAndShowGUI();
}
});
}
private static class DrawOnPanel extends JPanel {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillRect(0, 0, getWidth(), getHeight());
}
#Override
public Dimension getPreferredSize() {
return new Dimension(250, 250);
}
}
}

How to dynamically add JLabels to JPanel?

I'm having a problem with this. I have a JPanel and normally I would create a JLabel like this:
JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setBounds(0, 0, 135, 14);
panel.add(lblNewLabel);
but I want each time I click a button, in that panel to be created a new JLabel with the same size, but with a different height possition. I tried:
panel.add(new JLabel(stringName));
but this way I don't get to set it's bounds. stringName I get from a JTextField.
First off, use a layout. Done correctly the layout will place the components like you want. Secondly, when dynamically adding a component to a layout you need to tell the layout to update. Here is an example, it adds a label each time a button is pressed:
public static void main(String[] args) {
final JFrame frame = new JFrame("Test");
frame.setLayout(new GridLayout(0, 1));
frame.add(new JButton(new AbstractAction("Click to add") {
#Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
frame.add(new JLabel("Bla"));
frame.validate();
frame.repaint();
}
});
}
}));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
SwingUtilities.invokeLater(new Runnable() {
#Override public void run() {
frame.setVisible(true);
}
});
}
As said by #AndrewThompson use a correct LayoutManager, you should not be messing with setBounds etc.
Here is an example I made (Simply adds a JLabel to the JPanel each time the JButton is clicked):
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Test {
public Test() {
createAndShowUI();
}
private void createAndShowUI() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initComponents(frame);
frame.setResizable(false);
frame.pack();
frame.setVisible(true);
}
private void initComponents(final JFrame frame) {
final JPanel panel = new JPanel();
JButton button = new JButton("Add label");
button.addActionListener(new ActionListener() {
int count = 1;
#Override
public void actionPerformed(ActionEvent e) {
JLabel _lbl = new JLabel("Label " + count);//make label and assign text in 1 line
panel.add(_lbl);//add label we made
panel.revalidate();
panel.repaint();
frame.pack();//so our frame resizes to compensate for new components
count++;
}
});
frame.add(panel, BorderLayout.CENTER);
frame.add(button, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test();
}
});
}
}
Try swapping the order of of your commands, add the panel first then set the location.

how can i put a JButton on an image?

I am trying to fix a JFrame where there will be a background image and on the image JButtons which will do some commands. I try to do it without layout because i want to put small buttons in some specific locations on the JFrame but every time i do it, the background image comes to the front or the JFrame has size equal to the JFrame size. With the following code, the JButton has the same size to JFrame. I have tried to change the size and location of the JButton but nothing. Can you help me please?
here is the code
public final class Test extends JComponent
{
private Image background;
private JFrame frame;
private Dimension dimension;
public Test()
{
dimension = new Dimension(15, 15);
frame = new JFrame("Iphone");
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(this);
frame.setBounds(641, 0, 344, 655);
frame.setVisible(true);
test = displayButton("tigka");
frame.getContentPane().add(test);
}
public void update(Graphics g)
{
paint(g);
}
public void paintComponent(Graphics g)
{
super.paintComponents(g);
g.drawImage(background, 0, 25, null); // draw background
// label();
test = displayButton("test");
}
public JButton displayButton(String name)
{
JButton button = new JButton(name);
button.setSize(100, 100);
button.setPreferredSize(dimension);
return button;
}
You need to change the content pane to get a background for your Frame.
public static void main(String[] args) throws IOException {
JFrame frame = new JFrame("Test");
frame.setContentPane(new JPanel() {
BufferedImage image = ImageIO.read(new URL("http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png"));
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, 300, 300, this);
}
});
frame.add(new JButton("Test Button"));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
}
Output:
Have you tried using a JLabel with HTML in the label? Something like this:
import javax.swing.*;
public class SwingImage1
{
public static void main( String args[] )
{
JFrame frm = new JFrame( "Swing Image 1" );
JLabel lbl = new JLabel( "<html><body><img src=\"http://liv.liviutudor.com/images/liv.gif\"></body></html>" );
frm.getContentPane().add( lbl );
frm.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frm.pack();
frm.setVisible( true );
}
}
then on top of your label you can add your button?
You should swap those two lines:
super.paintComponents(g); //paints the children, like the button
g.drawImage(background, 0, 25, null); // draw background later possibly overwriting the button
Thus it should be this order:
g.drawImage(background, 0, 25, null);
super.paintComponents(g);
Additionally, note that the content pane's default layout is BorderLayout. Thus you'd set the layout of your content pane to null explicitly.
/*it is simple to put button on image first set image by making object then make button object & add the button object direct to image object rather then add to frame.*/
package frame;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class frame
{
public frame()
{
JFrame obj = new JFrame("Banking Software");
JButton b1 = new JButton("Opening Account");
JLabel image = new JLabel(new ImageIcon("money.jpg"));
image.setBounds(0,0, 1600, 1400);
obj.setExtendedState(JFrame.MAXIMIZED_BOTH);
obj.add(image);
b1.setBounds(500,400, 100, 40);
image.add(b1);
obj.setVisible(true);
}
public static void main(String args[])
{
new frame();
}
}

Categories

Resources