How to add an image to my GUI using an ImageIcon? - java

I'm very confused on how to add an image to my GUI in java. Below is my code and I am using ImageIcon to implement the image "map.png" but when I run this program the image does not appear. is this because it is not in the same folder as my .java file or is there some other problem?
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GUI implements ActionListener
{
private int count = 0;
private JLabel label;
private JFrame frame;
private JPanel panel;
public GUI()
{
frame = new JFrame();
frame.setResizable(false);
ImageIcon icon = new ImageIcon("map.png");
JLabel picture = new JLabel(icon);
JButton button = new JButton("Click me");
button.addActionListener(this);
label = new JLabel("Number of clicks: 0");
panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(400, 700, 10, 30));
panel.setLayout(new GridLayout(0, 1));
panel.add(button);
panel.add(label);
frame.add(picture);
frame.add(panel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Maynooth Thing");
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
new GUI();
}
#Override
public void actionPerformed(ActionEvent e)
{
count++;
label.setText("Number of clicks: " + count);
}
}

Java will search the image in the actual working directory, that is, the directory where java was started. This depends on how it is started - if command line, it is the same as the command line is using; IDEs normally have some settings (e.g. default for eclipse is the project main directory). Easy way to print it System.out.println(new java.io.File("").getAbsolutePath());
Unfortunately new ImageIcon does not throw an exception if the file is not found - the icon size (getIconHeight() or getIconWidth()) will be set to -1 if not found. ImageIO is better for reading images from file, given the image is not part of the application; otherwise, image is part of app, getResource() from class or class loader should be used.
The location of .java files is not relevant at all during execution. The location of .class files (classpath) would matter if using getResource methods from class loarder (recommended! specially if image/file should be read from JAR).

Related

How to receive input from textfield to textarea and a lot more...?

enter image description here
How can I make it like that?
1) If user opens that program, you don't have to click on textfield to receive focus, instead, if you switch to that program, it immediatetly gives you a focus to write instead of clicking for focus.
2) If user writes a ID number or item name to textfield, textarea responds to textfield and shows that ID or name to the user, like, pops up.
3) How to make textarea smaller in case, that even panel shows out in corners? I'd like to make a textarea a little bit smaller like a box and outside a box, its just a gray color.
In order to fully help me, I'll gladly give out the code.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
public abstract class Itemlist extends JFrame implements ActionListener, FocusListener {
/**
*
*/
private static final long serialVersionUID = 1L;
public static void main(String args[]) {
// create JFrame
JFrame frame = new JFrame("small project");
frame.setDefaultCloseOperation(2);
frame.setPreferredSize(new Dimension(400, 600));
frame.setLayout(new BorderLayout());
frame.setResizable(false);
JPanel panel = new JPanel(new FlowLayout(SwingConstants.LEADING, 10, 10));
frame.add(panel);
panel.setPreferredSize(new Dimension(100, 50));
JTextField tf = new JTextField(25);
tf.setPreferredSize(new Dimension(100, 35));
Font f = new Font("Times New Roman", Font.BOLD, 18);
tf.setFont(f);
panel.add(tf);
frame.add(tf, BorderLayout.PAGE_END);
tf.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e) {
tf.getText();
}
#Override
public void focusLost(FocusEvent e) {
tf.setText("");
}
});
JTextArea ta = new JTextArea();
frame.add(ta);
Font font = new Font("Times New Roman", Font.PLAIN, 16);
ta.setEditable(false);
ta.setFont(font);
JScrollPane scrollPane = new JScrollPane(ta);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
frame.add(scrollPane);
BufferedReader br;
String contents;
try {
br = new BufferedReader(new FileReader("C:/ItemList.txt"));
contents = br.readLine();
while ((contents = br.readLine()) != null) {
ta.read(br, null);
}
br.close();
} catch (IOException e) {
}
frame.pack();
// frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent arg0) {
}
}
*All help is appreciated. Have been stuck on it.
I suspect you want to consider using a WindowListener and monitor for the windowActivated event, at which time you can call requestFocusInWindow on the JTextField to transfer focus to it automatically. Focus management is a little bit of a black art, as it tends to work slightly differently on different platforms
I'm not sure entirely what you mean, but I'd look at the ActionListener support. This will require the user to hit the "action" key (typically Enter) to trigger it. If you want real time feedback, the a DocumentListener would be what you're looking for
Make use of the JTextAreas constructor to specify the preferred number of rows and columns. This will define the preferred scrollable size of the component, which will effect the size of the JScrollPane as well
In future, try and constrain you question to single, focused question, they are easier to answer and generally produce more detail

Jframe window will not work anymore

package Jframe;
import java.awt.Color;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class JavaWindows {
public static void main(String args[]) {
JFrame Window = new JFrame();
JLabel Label = new JLabel("test");
JPanel Panel = new JPanel();
ImageIcon icon = new ImageIcon("Heart.png");
Window.setIconImage(icon.getImage());
Window.add(Panel);
Window.add(Label);
Window.setSize(500,750);
Panel.setSize(500, 900);
Window.getContentPane().setBackground(Color.PINK);
Window.pack();
}
}
About 10 min ago this code worked. It made a window that was about 100,100 with a 500,900 panel that was sized correctly. The window was not 500,750 like i specified I don't know what went wrong there but all sudden the window wont run in Eclipse. I deleted window.pack(); and retyped it now its broke. Any ideas?
you have to set visibility of the frame
window.setVisible(true);

Launch two different JAVA projects from the same GUI

I have two java projects. Both with runnable GUIs.
I would like to add a button in Project1 that when pressed opens Project2 application window and closes Project 1.
Since I am using MVC for both applications it would become too cluttered to just copy paste all the code from the first project into the other one, which is why I am looking for an easier alternative.
I have built a path between the two projects, but I can't seem to find a way to start the second application on a button press.
i made you simple example of how to close JFrame after clicking a button and open new one.It is better if you write us the code you are useing note: i am not using MVC here
package test;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Test {
private JButton btn;
JFrame frame = new JFrame();
public Test(){
btn = new JButton("new window");
frame.setVisible(true);
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(btn);
frame.setLayout(new FlowLayout());
btn.addActionListener(new addButtonWatcher());
}
private class addButtonWatcher implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
JFrame newWindow = new JFrame();
newWindow.setVisible(true);
newWindow.setSize(200,200);
frame.dispose();
}
}
public static void main(String[] args) {
Test t = new Test();
}
}

How can i make a layout like the attached gif?

My question is about layout in Java Swing.
I want to make a screen like shown below. I saw this video on youtube and made a gif of the part I want.
I want 2 panels and a button like this:
When i clicked the button the JPanel will be hidden and JTable's width will be 100% like html/css like this; (And when button clicked again JPanel will be shown etc..)
How can I do this? Which layout should I use?
There is more than one way to do it, but here's an example that uses BorderLayout as the main layout, and places the button in a left aligning FlowLayout:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
public class LayoutDemo {
private LayoutDemo() {
JFrame frame = new JFrame("Demo");
frame.setLocationByPlatform(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel buttonHolder = new JPanel(new FlowLayout(FlowLayout.LEADING));
frame.add(buttonHolder, BorderLayout.NORTH);
JButton button = new JButton("Toggle visibility");
buttonHolder.add(button);
final JPanel left = new JPanel();
left.setPreferredSize(new Dimension(100, 200));
left.setBackground(Color.BLUE);
frame.add(left, BorderLayout.LINE_START);
JLabel table = new JLabel("This pretends to be a table", SwingConstants.CENTER);
table.setPreferredSize(new Dimension(400, 200));
frame.add(table);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
left.setVisible(!left.isVisible());
}
});
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new LayoutDemo();
}
});
}
}
I used setPreferredSize() to give the components some reasonable default size, but usually it should be automatically calculated by the layout manager from the sizes of the child components, or in case of a custom component, you should override getPreferredSize() return what is appropriate for the component.
The result looks like:

How do I make my chat program scroll down as the chat moves along?

I'm making a simple chat GUI. I've come into a problem where my program isn't scrolling down as the chat moves along. I'm also unsure about how to add a scroll bar/pane to the program, without messing everything up by putting my main text area into a panel and destroying the look of the interface. How do I adjust the main chat box, without screwing it up and making it look ugly by putting the chatBox in a JPanel. I'll post all of my code below.
MainGUI class:
package coltGUI;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIManager;
public class MainGUI implements ActionListener {
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
MainGUI gui = new MainGUI();
gui.display();
}
JButton sendMessage;
JTextField messageBox;
JTextArea chatBox;
public void display() {
JFrame frame = new JFrame("Colt Chat");
JPanel southPanel = new JPanel();
frame.getContentPane().add(BorderLayout.SOUTH, southPanel);
southPanel.setBackground(Color.BLUE);
southPanel.setLayout(new GridBagLayout());
messageBox = new JTextField(30);
sendMessage = new JButton("Send Message");
chatBox = new JTextArea();
chatBox.setEditable(false);
frame.getContentPane().add(BorderLayout.CENTER, chatBox);
chatBox.setLineWrap(true);
GridBagConstraints left = new GridBagConstraints();
left.anchor = GridBagConstraints.WEST;
GridBagConstraints right = new GridBagConstraints();
right.anchor = GridBagConstraints.EAST;
right.weightx = 2.0;
southPanel.add(messageBox, left);
southPanel.add(sendMessage, right);
sendMessage.addActionListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(470, 300);
}
public void actionPerformed(ActionEvent event) {
if (messageBox.getText().length() < 1) {
// do nothing
} else {
chatBox.append(messageBox.getText() + "\n");
messageBox.setText("");
}
}
}
Just add the text area to a JScrollPane and then add the scrollpane to the frame. There is no need for a panel.
//frame.getContentPane().add(BorderLayout.CENTER, chatBox);
frame.add(new JScrollPane(chatBox), BorderLayout.CENTER);
Note that constraints should be specified as the second parameter of the add(...) method, not the first.
Also, since JDK5, you don't need to use getContentPane(), the frame.add(..) method will do this for you.
If you want automatic scrolling you can check out Text Area Scrolling.
First you need to wrap chatBox in a JScrollPane like this:
frame.add(new JScrollPane(chatBox), BorderLayout.CENTER);
Second after appending the message to chatBox you need to force it to scroll to the end which can be done with the following:
chatBox.setCaretPosition(chatBox.getDocument().getLength());

Categories

Resources