Can someone help me understand how ImageIcon works for java? - java

So I have about a year a 5/12 months experience playing around with java but I have never been able to make anything outside of skeletons. I would really appreciate it if someone could help me understand how I can make an image from my computer visible using swing.
I have gone between different websites trying to find answers but none of the example codes I've tried have worked out. Stackoverflow has helped in the past to learn java through various questions other people asked so I have made an account to ask a question myself. I'm probably being very dumb but my image never appears despite what I've tried. I come back to trying to understand swing every few months after giving up on it previously and while I feel I have a grasp on some basic concepts such as something should be set as visible, how to make/add a JFrame, etc, it's always this that messes me up.
import javax.swing.*;
import java.awt.*;
public class Main extends JFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("main");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
ImageIcon ii = new ImageIcon("C:\\Users\\plasm\\IdeaProjects\\Shdo\\src\\mario.jpg");
JLabel lable = new JLabel(ii);
JScrollPane jsp = new JScrollPane(lable);
frame.getContentPane().add(jsp);
frame. setSize(1000, 700);
JButton button = new JButton();
button.setSize(new Dimension(300, 300));
button.setLocation(500, 350);
frame.getContentPane().add(button);
frame.setVisible(true);
}
}
The code above is copy-pasted from https://www.daniweb.com/programming/software-development/threads/379864/add-image-and-button-to-jframe aside from the pathway, however, it only shows a basic white JFrame at the set dimensions.

frame.getContentPane().add(jsp); // problem
frame. setSize(1000, 700);
JButton button = new JButton();
button.setSize(new Dimension(300, 300)); // does nothing
button.setLocation(500, 350); // does nothing
frame.getContentPane().add(button); //problem
The problem is that the default layout manager for the content pane of the JFrame is a BorderLayout. You are attempting to add two compnents to the CENTER of the BorderLayout which won't work. The button replaces the scroll pane.
Instead you should be using:
frame.getContentPane().add(jsp, BorderLayout.CENTER);
frame. setSize(1000, 700);
JButton button = new JButton("Testing");
frame.getContentPane().add(button, BorderLayout.PAGE_END);
Read the section from the Swing tutorial on Layout Manager for more information and working example of a BorderLayout.
As mentioned in the first comment. There is no need for the getContentPane(). The frame will automatically add the component to the content pane.
Also, when doing testing it is better to do something like:
JLabel label = new JLabel("Icon label");
label.setIcon(ii);
This way if you specify the wrong path for the image, you will at least see the text of the label and you will know the problem is in the path, not with the layout code.

Related

JCheckBox centereing

I have been searching for a while now, but couldnt find a solution so I have decided to ask here.
I am using Java Swing for my gui implementation of calculator. I have custom made layout(which works correctly 100%). I have added all buttons and all buttons are positioned correctly, always. Last component I have inserted is "Inv" and it is checkbox which I cant find a way to center it inside its area. I have tried putting it in panel,in panel with borderlayout.center, setting the horizontal and vertical text alignment, but nothing works.
invert = new JCheckBox("Inv");
invert.setBackground(Color.decode("#8DA336"));
invert.addActionListener(new CommandListener(this,"invert"));
container.add(invert, new RCPosition(5, 7));
This RCPosition is nothing more than object which says in which row and column this component is (nothing wrong with that).
Checkbox is by default left-aligned. Try make it center-aligned:
invert = new JCheckBox("Inv");
invert.setHorizontalAlignment(SwingConstants.CENTER);
// styling and add to container
If it don't help, then you should publish your layout manager.
You could try putting it in a JPanel with BoxLayout, then add horizontal glue on the left and right.
final JFrame frame = new JFrame();
final JPanel jp = new JPanel();
jp.setLayout(new BoxLayout(jp, BoxLayout.X_AXIS));
jp.add(Box.createHorizontalGlue());
final JCheckBox jcb = new JCheckBox("inv");
jp.add(jcb);
jp.add(Box.createHorizontalGlue());
frame.getContentPane().add(jp);
frame.pack();
frame.setLocationRelativeTo(null);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
frame.setVisible(true);
}
});
This is just one way to do it, setHorizontalAlignment should work as well.

Components won't show on Frame Java

I want to make a message box with a label and a button. At first I tried witohout "BorderLayout.." there and I set bounds for every component. But my JLabel appeared on the screen "Puzzle....", and the width dimension was enough big.
Now I tried with this method but I have nothing in my JFrame. It looks like this:
I resolved this with JOptionPaneMessage, but I just want to know what was wrong at my code. I use this just for learning purpose.
Here is the code:
JFrame a = new JFrame("Message");
JLabel mesaj = new JLabel("Puzzle cannot be solved!");
JButton ok = new JButton("Ok");
a.add(mesaj, BorderLayout.CENTER);
a.add(ok, BorderLayout.SOUTH);
a.setSize(450, 200);
a.isFocusableWindow();
a.setLayout(null);
a.setVisible(true);
a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Multiple JPanels in one JFrame not showing top panel

So I'm writing a program in which I wish to have a single JFrame containing a JPanel header in a separate colour and directly underneath have a grid of buttons in a separate JPanel. So far my program works perfectly except for the fact that the header String isn't showing up in the NORTH panel. Instead I'm getting a box containing the set background colour with a small grey box in the centre. I'm wondering if I didn't set the size of the panel correctly?
I have heard this can be accomplished using JLabel, but when I tried to do this, it would not show the background colour that I had set.
So, could anyone please show me how to achieve the following either with the JPanel (preferably because I would like to know how it works and what I'm missing) or with JLabel: filling that little grey box in the middle of the header with a String.
Here is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Example {
public static void main(String[] args) {
// Initialize a panel for the header, and mainGrid which will contain buttons
JPanel panel = new JPanel();
JPanel header = new JPanel();
JPanel mainGrid = new JPanel();
// Initialize the header
DisplayPanel message = new DisplayPanel();
header.setBackground(Color.ORANGE);
header.add(message);
// Initialize the mainGrid panel
mainGrid.setLayout(new GridLayout(2,2,2,2));
mainGrid.add(new JButton("1"));
mainGrid.add(new JButton("2"));
mainGrid.add(new JButton("3"));
mainGrid.add(new JButton("4"));
// Add the two subpanels to the main panel
panel.setLayout(new BorderLayout());
panel.add(header, BorderLayout.NORTH); // The issue is this panel isn't displaying the String created in DisplayPanel
panel.add(mainGrid, BorderLayout.CENTER);
// Add main panel to JFrame
JFrame display = new JFrame("Test");
display.setContentPane(panel);
display.setSize(200,100);
display.setLocation(500,200);
display.setVisible(true);
display.setResizable(false);
display.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private static class DisplayPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("header" , 20, 20); // The string I want to be displayed
}
}
}
I would very much appreciate anyone's help or input as I have only been studying Java for a few months and this is my first post. Thank you in advance.
Also, any general tips on writing that you may have would be greatly appreciated.
I'm wondering if your problem is that you're nesting your message JPanel inside of the header JPanel, and the container header JPanel uses the JPanel default FlowLayout. Thus the component it holds won't expand on its own and will remain trivially small.
Consider either giving the header JPanel a BorderLayout so that message expands inside of it, or
use a JLabel to show your text, not a JPanel's paintComponent method. The JLabel should size itself to be big enough to show its text. If you do this and want it to show a background color, all you have to do is call setOpaque(true) on your JLabel, and you're set.
Actually, if you nest the JLabel, then there's no need to make it opaque. Just do this:
JPanel header = new JPanel();
JPanel mainGrid = new JPanel();
JLabel message = new JLabel("Header", SwingConstants.CENTER);
header.setBackground(Color.ORANGE);
header.setLayout(new BorderLayout());
header.add(message);
I would highly recommend using a GUI builder WYSIWYG IDE, like NetBeans, where you can easily drag and drop components to where they need to be. If you're doing any sort of complex GUI layout, it can be madness (and in my opinion, nonsensical) trying to write and maintain the code.
The layout your trying to implement would be trivial in NetBeans.

Getting scrollbar to work with absolute positioning on

Hello I'm trying to make a game and a basic thing I want to do is add a JTextArea with a scrollbars. This is my code:
package TestStuff;
import javax.swing.*;
#SuppressWarnings("serial")
public class JTextAreaTest extends JFrame
{
public static void main(String[] args)
{
new JTextAreaTest();
}
public JTextAreaTest()
{
this.setSize(1500, 600);
setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
this.setLocation(450, 175);
this.setExtendedState(JFrame.
MAXIMIZED_BOTH);
this.setTitle("Game Display Test");
panel1 = new JPanel(null);
final JTextArea gameDisplay = new JTextArea(
500, 300);
gameDisplay.setBounds(424, 300, 500, 300);
gameDisplay.setBackground(Color.BLACK);
Font font = new Font ("Verdana", Font.BOLD,
14);
gameDisplay.setFont(font);
gameDisplay.setForeground(Color.WHITE);
final JScrollPane displayScroll = new JScrollPane(
gameDisplay);
displayScroll.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_AS_
NEEDED);
displayScroll.setVerticalScrollBarPolicy(
JScrollPane.
VERTICAL_SCROLLBAR_AS_NEEDED);
panel1.add(gameDisplay);
panel1.add(displayScroll);
setContentPane(panel1);
this.setVisible(true);
}
}
Everything workable fine when I run it, but when the text gets out of the bounds of the JTextArea, the scrollbars never appear! And yes, I know I'm using absolute positioning (no layout) and that's bad but I need it for other reasons in my game. Thanks in advance! (Also I can't connect to this site for some reason on my computer but I've used you guys before and you're awesome, so I have to type this on my phone. Sorry if the layout of the question gets screwed up, it the phone :P)
When you call...
panel1.add(gameDisplay);
panel1.add(displayScroll);
You are effectively removing the gameDisplay from displayScroll, as a component can only have one parent.
The fact that it works as it does comes down to the fact that you are playing around with the position and size of the gameDisplay panel instead of the displayScroll, which you should be...
Use
panel1.add(displayScroll);
Instead, but make sure you size and position ONLY the displayScroll, as displayScroll will take care of the gameDisplay
I had a similar problem and the solution was setPreferredSize on the component inside the scrollbar. I was trying to absolute position things inside the scrollbars. Luckily I knew exactly what the size should be. Maybe this is a special case.
final JFrame frame = new JFrame("HelloWorldSwing");
final JPanel panel = new JPanel();
panel.setPreferredSize(PUT SIZE HERE);
panel.setLayout(null);
final JScrollPane scrollPane = new JScrollPane(panel);
frame.getContentPane().add(scrollPane);

MigLayout - Need help on how to use the dock parameters (or need an alternative)

I just started using MigLayout for SWING in Java and I'm really liking it so far. The only thing, though, is that the dock parameters don't seem to work the way I thought they worked and I can't figure out what I'm doing wrong.
The problem is: I'm trying to add a JButton inside a JPanel and docking it to the right side using panel.add(button, "east");. While it actually makes it the rightmost component, it still only takes the same space as it would in a flowLayout. What I'd like it to do is stick to the right side of the panel.
Here's some compilable code that recreates the problem:
public class MigLayoutTest extends JFrame
{
public MigLayoutTest()
{
setSize(500,500);
JPanel panel = new JPanel(new MigLayout());
panel.setBackground(Color.YELLOW);
setContentPane(panel);
panel.setSize(500,500);
panel.add(new JButton("Dock east"), "east");
panel.add(new JButton("No dock"));
}
public static void main(String[] args)
{
JFrame frame = new MigLayoutTest();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Here's what the output looks like:
And here's where I'd want the "dock east" button:
If I'm using the parameters wrong, I'd like it if someone could tell me how I'm supposed to make my button dock to the right side of the panel.
Thanks!
You have to specify growth paarameters:
new MigLayout("", "[grow]", "[]")
Be careful though how you use it - it may not work the way you think it is. Here is a good read up on MigLayout features http://www.miglayout.com/QuickStart.pdf

Categories