I'm trying to make a registration form for a game(assignment) for school and i have finished it but i wanted to add an image on it but it blocks everything, JButton,JTextField etc.. How can i fix this? EDITED : I MADE THE CODE A LITTLE SHORTER SAME PROBLEM OCCURS.
public class MyGUI {
JLabel xyz;
JButton b1;
public JPanel createContentPane () {
JPanel mainPanel = new JPanel();
mainPanel.setLayout(null);
xyz = new JLabel("Don't have an account? Sign up!");
xyz.setBounds(10,0,390,30);
xyz.setFont(new Font("Lucida Grande", Font.BOLD, 20));
xyz.setLayout(new FlowLayout());
mainPanel.add(xyz);
b1 = new JButton("Create Account");
b1.setBounds(40,540,310,33);
b1.setFont(new Font("Comic San Ms", Font.BOLD , 16));
b1.setForeground(Color.white);
b1.setBackground(Color.blue);
mainPanel.add(b1);
return mainPanel;
}
public static void CreateAndShowGUI() {
JFrame frame = new JFrame("Romaverse ONLINE! REGISTRATION");
Container c = frame.getContentPane();
MyGUI demo = new MyGUI();
c.add(demo.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(480,700);
frame.setVisible(true);
frame.setContentPane(new JLabel(new ImageIcon("C:\\Users\\Admin\\Desktop\\roma.jpg")));
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
CreateAndShowGUI();
}
});
}
}
Here Is the part where i put the image
frame.setContentPane(newJLabel(newImageIcon("C:\\Users\\Admin\\Desktop\\roma.jpg"));
The image doesn't block buttons, it replaces them because you are calling setContentPane. Why are you doing this? You can simply add the image together with all other controls inside the createContentPane method. Note that the order in which controls are added may affect their Z-order.
Check out the Background Panel.
It shows two approaches:
Add the image to a JLabel and then add your components to the label
Do custom painting of the image on a JPanel and then add your components to the panel.
Edit:
Basic code using approach 1:
JLabel background = new JLabel( new ImageIcon(...) );
label.setLayout( new FlowLayout() );
label.add( new JButton("Hello") );
JFrame frame = new JFrame();
frame.add( background );
Related
I am making a chat in java and need to display old messages in a JPanel. I need an image and the message that was being sent/received to be displayed, each on its own row. The code that I currently have :
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel container = new JPanel();
container.setPreferredSize(new Dimension(300, 400));
// Printing five messages
for (int i = 0; i < 5; i++) {
JPanel p = new JPanel();
p.setPreferredSize(new Dimension(300, 40));
p.setBorder(BorderFactory.createLineBorder(Color.BLACK));
p.setLayout(new BoxLayout(p, BoxLayout.X_AXIS));
JLabel img = new JLabel("Image : ");
JLabel txt = new JLabel("This is some text");
p.add(img);
p.add(txt);
img.setAlignmentX(Component.LEFT_ALIGNMENT);
txt.setAlignmentX(Component.LEFT_ALIGNMENT);
container.add(p);
}
f.add(container);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
Result :
Right now I am specifying the width and height of each message which is not so good as it should automatically resize to its content. I feel like there should be a good layout-manager for this but I am new to swing so help is appreciated as I do not know which one to use.
it should automatically resize to its content.
Having text that wraps to a new line is the main problem here.
One way might be to:
use vertical Box - it allows each component to have a different height
wrap the text in HTML - it will allow for the text to wrap
Something like:
import java.awt.*;
import javax.swing.*;
public class Chat extends JPanel
{
private Box messageBox = Box.createVerticalBox();
public Chat()
{
setLayout( new BorderLayout() );
add(messageBox, BorderLayout.PAGE_START);
addMessage("Short message");
addMessage("A longer message that should wrap as reqired onto another line. This should happen dynamically");
}
public void addMessage(String text)
{
JPanel messagePanel = new JPanel( new BorderLayout() );
JLabel label = new JLabel( new ImageIcon("about16.gif") );
messagePanel.add(label, BorderLayout.LINE_START);
JLabel message = new JLabel("<html>" + text + "</html>");
messagePanel.add(message);
messageBox.add(messagePanel);
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Chat");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Chat());
frame.pack();
frame.setSize(200, 100);
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args) throws Exception
{
java.awt.EventQueue.invokeLater( () -> createAndShowGUI() );
}
}
So I am designing a chatroom and before I can read up on sockets I need to finish up this GUI. Basically I am mostly using TextDemo as my guide. I like how it displays so I figured it'd be an easy spot to start with my code. In my code it breaks whenever I try to put in:
input.addActionListener(this);
When I comment out that line it goes back to displaying/running perfectly. Due to my errors, it looks like I'm putting it in the wrong location. I've tried moving it around a bit but I don't seem to have the problem solving skills to fix this yet. Can someone help correct me and explain what I am doing wrong here?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUI extends JPanel implements ActionListener
{
private final static String newline = "\n";
///// CREATING THE GUI /////
JFrame frame = new JFrame("Chatroom");
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
JPanel chatpanel = new JPanel();
JPanel inputpanel = new JPanel();
JPanel sendpanel = new JPanel();
JTextArea chat = new JTextArea(19, 49);
JTextArea input = new JTextArea(3, 40);
JScrollPane chatscroll = new JScrollPane(chat,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
JScrollPane inputscroll = new JScrollPane(input,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
JButton connectbutton = new JButton("Connect");
JButton disconnectbutton = new JButton("Disconnect");
JButton send = new JButton("Send");
JLabel label = new JLabel();
///// GUI CONSTRUCTOR /////
public GUI()
{
chatroomGUI();
}
public void chatroomGUI()
{
///// GUI DISPLAY /////
frame.setVisible(true);
frame.setSize(800, 450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.setBackground(Color.GRAY);
panel2.setBackground(Color.lightGray);
chatpanel.setBackground(Color.lightGray);
inputpanel.setBackground(Color.lightGray);
sendpanel.setBackground(Color.lightGray);
///// ACTION LISTENER /////
//input.addActionListener(this);
chat.setEditable(false);
chat.setFont(new Font("Dialog", Font.PLAIN, 12));
chat.setLineWrap(true);
chat.setWrapStyleWord(true);
input.setFont(new Font("Fialog", Font.PLAIN, 12));
input.setLineWrap(true);
input.setWrapStyleWord(true);
sendpanel.setLayout(new BorderLayout(0, 0));
sendpanel.setPreferredSize(new Dimension(95, 50));
chatpanel.setLayout(new FlowLayout());
chatpanel.setPreferredSize(new Dimension(565, 320));
///// ADD AREA /////
chatpanel.add(chatscroll);
inputpanel.add(inputscroll);
inputpanel.add(sendpanel, BorderLayout.EAST);
sendpanel.add(send, BorderLayout.CENTER);
panel.add(connectbutton);
panel.add(disconnectbutton);
panel.add(label);
panel2.add(chatpanel);
panel2.add(inputpanel);
frame.add(panel, BorderLayout.WEST);
frame.add(panel2);
}
///// ACTION PERFORMED /////
/*The following will take any text that is typed inside of
the "input" area and display it in the "chat" screen area.*/
public void actionPerformed(ActionEvent evt)
{
String text = input.getText();
chat.append(text + newline);
input.selectAll();
chat.setCaretPosition(chat.getDocument().getLength());
}
}
Note: My main is in another class. That code just simply looks like:
public class Chatroom
{
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new GUI();
}
});
}
}
JTextArea does not support the ActionListener API, so it does not have a addActionListener method. You should consult the JavaDocs and tutorials first
Depending on what you are trying to do, you might consider using a DocumentListener or a DocumentFilter or use the key bindings API, for example
How can I place an object in a specific location (x,y) on a JFrame?
Here find the Absolute Positioning Tutorials. Please do read carefully, as to why this approach is discouraged over using LayoutManagers
To add say a JButton to your JPanel, you can use this :
JButton button = new JButton("Click Me");
button.setBounds(5, 5, 50, 30);
panel.add(button);
Here try this example program :
import java.awt.*;
import javax.swing.*;
public class AbsoluteLayoutExample
{
private void displayGUI()
{
JFrame frame = new JFrame("Absolute Layout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setOpaque(true);
contentPane.setBackground(Color.WHITE);
contentPane.setLayout(null);
JLabel label = new JLabel(
"This JPanel uses Absolute Positioning"
, JLabel.CENTER);
label.setSize(300, 30);
label.setLocation(5, 5);
JButton button = new JButton("USELESS");
button.setSize(100, 30);
button.setLocation(95, 45);
contentPane.add(label);
contentPane.add(button);
frame.setContentPane(contentPane);
frame.setSize(310, 125);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new AbsoluteLayoutExample().displayGUI();
}
});
}
}
Try these 2... in combination with each other...
setLocation() and setBounds()
Its even better to use GroupLayout, developed by NetBeans team in 2005. WindowsBuilder Pro is a good tool for Building Gui in java
Check out this absolute layout code sample:
Absolute Layout demo
In the class inheriting the frame:
setLayout(null);
In your component:
setLocation(x,y);
I'm new to Java, I would like to know how can I get my textarea from the main class??
This is my code:
public static void main(String[] args) {
UIManager.put("swing.boldMetal", Boolean.FALSE);
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
frame = new JFrame("Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GuiManager animator = new GuiManager();
frame.add(animator, BorderLayout.CENTER);
// Display the window.
frame.pack();
frame.setSize(800, 500);
frame.setVisible(true);
}
and GuiManager:
public GuiManager() {
setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
// .............
// Create Scrolling Text Area in Swing
JPanel panelLabel = new JPanel();
panelLabel.setLayout(new FlowLayout()); // No content pane for JPanel.
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout()); // No content pane for JPanel.
JLabel ta1Label = new JLabel("Label One", JLabel.LEFT);
ta1Label.setAlignmentX(Component.LEFT_ALIGNMENT);
JTextArea ta = new JTextArea("", 10, 30);
ta.setLineWrap(true);
JScrollPane sbrText = new JScrollPane(ta);
sbrText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JLabel ta2Label = new JLabel("Label2", JLabel.RIGHT);
ta2Label.setAlignmentX(Component.RIGHT_ALIGNMENT);
JTextArea ta2 = new JTextArea("", 10, 30);
ta2.setLineWrap(true);
JScrollPane sbrText2 = new JScrollPane(ta2);
sbrText2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
panelLabel.add(ta1Label);
panelLabel.add(ta2Label);
panel.add(sbrText);
panel.add(sbrText2);
// Put everything together.
add(panelLabel);
add(panel);
setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
}
My goal is to redirect the output to these textarea, and for some output I need to redirect to the textarea on the left, but sometime I need to output on the textarea on the right. What would be the best solution to do that? Thank you.
Everything that you want to access seems to be in GuiManager. However, you put the declaration for it in a method. This means that it becomes a local variable. Once the method is finished with it's code, the variable is gone and cannot be accessed any longer.
The fix? Just make it available to all the other classes.
public static GuiManager animator = new GuiManager();
Put that where you declared all your other variables for that class, and take out the one that was located in the 'createAndShowGUI()' method.
I would like to know what code to insert and where to add a simple label that can just say the word "Label" and a input text box that I can enter a number.
public CalculateDimensions() {
JTabbedPane Tab = new JTabbedPane();
JPanel jplInnerPanel1 = createInnerPanel("First Tab");
Tab.addTab("One", jplInnerPanel1);
Tab.setSelectedIndex(0);
JPanel jplInnerPanel2 = createInnerPanel("Second Tab");
Tab.addTab("Two", jplInnerPanel2);
JPanel jplInnerPanel3 = createInnerPanel("Third Tab");
Tab.addTab("Three", jplInnerPanel3);
JPanel jplInnerPanel4 = createInnerPanel("Fourth Tab");
Tab.addTab("Four", jplInnerPanel4);
JPanel jplInnerPanel5 = createInnerPanel("Fifth Tab");
Tab.addTab("Five", jplInnerPanel5);
setLayout(new GridLayout(1, 1));
add(Tab);
}
protected JPanel createInnerPanel(String text) {
JPanel jplPanel = new JPanel();
JLabel jlbDisplay = new JLabel(text);
jlbDisplay.setHorizontalAlignment(JLabel.CENTER);
jplPanel.setLayout(new GridLayout(1, 1));
jplPanel.add(jlbDisplay);
return jplPanel;
}
public static void main(String[] args) {
JFrame frame = new JFrame("Calculations");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.getContentPane().add(new CalculateDimensions(),
BorderLayout.CENTER);
frame.setSize(400, 400);
frame.setVisible(true);
}
}
The Swing tutorial is an excellent resource for building GUIs.
Take a look at the visual guide and click on the components you want for detailed how to guides for creating text boxes, and other items.
http://download.oracle.com/javase/tutorial/ui/features/components.html
in your public static void main() method you should not instantiate JFrame frame = new JFrame("Calculations");
This is where you are going wrong!
That line should read:
CalculateDimensions frame = new CalculateDimensions("Calculations");
You will also need to change the line says
public class CalculateDimensions {
(it's near the top) says
public class CalculateDimensions extends JFrame {
then inside the method called public class CalculateDimensions { you need to add a line after JPanel jplInnerPanel1 = createInnerPanel("First Tab"); which says
jplInnerPanel1.add(new JLabel("Label");