Get a textarea in java using JFrame - java

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.

Related

Background Image covering JComponents

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 );

addactionListener(this) How do I place this line of code in correctly?

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

Java GUI - Possible to store JPanels inside a single main JPanel?

I am working on a semester project that I have and I was wondering if it was possible to store 3-4 JPanels instead one single "main" JPanel. The reason for me asking this is because I a trying to make a GUI checkbook program and my checkbook has 7 buttons that should open a new window once I click on it. To switch between each window I'm going to have to use the CardLayout, but my understand of the CardLayout is that I can only assign one single JPanel to that card so I can't assign multiple JPanels to a single Card layout so when the user clicks on a different card 3-4 different JPanels appear.
The reason that I am asking this is because I asked for help earlier and received help for creating my first window in this project, it produces the output I want PERFECTLY, but uses more than 1 JPanel in doing so. Since this prevents me from continuing on to the other steps of my 7 GUI Windows, I am stuck.
Here is the code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class checkbook extends JPanel implements ActionListener {
private static final String title = "Use The Buttons Below To Manage Transactions";
private static final String[] bottomButtons = { "Create a New Account",
"Load a Trans from a File", "Add New Transactions",
"Search Transactions", "Sort Transactions",
"View/Delete Transactions", "Backup Transaction", "Exit" };
static JButton Button[] = new JButton[8];
static ActionListener AL = new checkbook();
public checkbook() {
JLabel titleLabel = new JLabel(title, SwingConstants.CENTER);
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 18));
JPanel titlePanel = new JPanel();
titlePanel.add(titleLabel); // put it in a JPanel so it will expand to fill BoxLayout
JTextField textfield = new JTextField();
JPanel accountBalancePanel = new JPanel();
accountBalancePanel.add(new JLabel("Account Name:"));
accountBalancePanel.add(new JTextField(10));
accountBalancePanel.add(Box.createHorizontalStrut(4));
accountBalancePanel.add(new JLabel("Balance:"));
textfield = new JTextField("0.0", 10);
textfield.setHorizontalAlignment(JTextField.RIGHT);
accountBalancePanel.add(textfield);
JPanel northPanel = new JPanel();
northPanel.setLayout(new BoxLayout(northPanel, BoxLayout.PAGE_AXIS));
northPanel.add(titlePanel);
northPanel.add(accountBalancePanel);
JPanel southBtnPanel = new JPanel(new GridLayout(2, 4, 1, 1));
for(int i = 0; i < 8; i++){
Button[i] = new JButton(bottomButtons[i]);
southBtnPanel.add(Button[i]);
Button[i].addActionListener(AL);
}
setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
setLayout(new BorderLayout());
add(northPanel, BorderLayout.NORTH);
add(Box.createRigidArea(new Dimension(100, 100))); // just an empty placeholder
add(southBtnPanel, BorderLayout.SOUTH);
}
private static void createAndShowGui() {
checkbook mainPanel = new checkbook();
JFrame frame = new JFrame("Checkbook");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
createAndShowGui();
}
});
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == Button[7]) {
System.exit(0);
}
}
}
Credit goes to Hovercraft Full Of Eels for showing me the above example
If there is anything that is unclear about my question, please ask and I will do the best I can to fix it.
Here is what the code produces:
http://i.stack.imgur.com/WY0c3.png

How to activate ActionEvent inside JMenu to show new panel on the frame?(Basic)

I just started to learn swing by myself, I'm little bit confused why my event does not work here:
1.I'm trying to delete everything from my panel if the user click menu bar -> load but it force me to change the panel to final because i'm using it inside the event!
2.I have defined new panel in my event and defined two more container to add to that panel and then add it to the main frame but it seems nothing happening!
Please help me if you can find out what is wrong.
Sorry in advance for messy code.
I appreciate any hints.
public class SimpleBorder {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable()
{
public void run()
{
myFrame frame = new myFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class MyFrame extends JFrame {
public MyFrame()
{
setSize(500,500);
JPanel panel = new JPanel();
panel.setLayout(null);
JLabel label = new JLabel("my name is bernard...");
Color myColor = new Color(10, 150, 80);
panel.setBackground(myColor);
label.setFont(new Font("Serif", Font.PLAIN, 25));
Dimension size = label.getPreferredSize();
Insets insets = label.getInsets();
label.setBounds(85+insets.left, 120+insets.top , size.width, size.height);
panel.add(label);
JMenuBar menu = new JMenuBar();
setJMenuBar(menu);
JMenu col = new JMenu("Collection");
menu.add(col);
JMenu help = new JMenu("Help");
menu.add(help);
Action loadAction = new AbstractAction("Load")//menu item exit goes here
{
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent event)
{
JTextArea text = new JTextArea(10, 40);
JScrollPane scrol1 = new JScrollPane(text);
String[] items = {"A", "B", "C", "D"};
JList list = new JList(items);
JScrollPane scrol2 = new JScrollPane(list);
JPanel panel2 = new JPanel(new BorderLayout());
panel2 = new JPanel(new GridLayout(1, 2 ));
panel2.add(scrol1,BorderLayout.WEST);
panel2.add(scrol2,BorderLayout.EAST);
add(panel2);
}
};
JMenuItem load = new JMenuItem(loadAction);
col.add(load);
add(panel);
}
}
Call revalidate()/repaint() on your JFrame instance after adding the new panel:
JPanel panel2 = new JPanel(new BorderLayout());
// panel2 = new JPanel(new GridLayout(1, 2 ));//why this it will overwrite the above layout
panel2.add(scrol1,BorderLayout.WEST);
panel2.add(scrol2,BorderLayout.EAST);
add(panel2);
revalidate();
repaint();
Also call pack() on you JFrame instance so all components are spaced by the layoutmanager. As said in a comment dont extend the JFrame class, create a variable of the frame and initiate all that you need on the frames instance, and dont set a layout to null, unless you love hard work :P
Alternatively as mentioned by mKorbel, a CardLayout may be more what you want, it will allow you to use a single JPanel and switch between others/new ones:
JPanel cards;
final static String BUTTONPANEL = "Card with JButtons";
final static String TEXTPANEL = "Card with JTextField";
//Where the components controlled by the CardLayout are initialized:
//Create the "cards".
JPanel card1 = new JPanel();
...
JPanel card2 = new JPanel();
...
//Create the panel that contains the "cards".
cards = new JPanel(new CardLayout());
cards.add(card1, BUTTONPANEL);
cards.add(card2, TEXTPANEL);
//add card panel to frame
frame.add(cards);
//swap cards
CardLayout cl = (CardLayout)(cards.getLayout());//get layout of cards from card panel
cl.show(cards, TEXTPANEL);//show another card

Elements in Layouts in Java all in same position

I'm coding in Java Swing and for some reason, when I add two elements to a gridlayout, they both assume the same position. I have tried simplifying it into something that would not fail and then building up from there, but alas, it's still not working.
The misbehaving code within the program is:
bodyPanelMain.setLayout(new GridLayout(4, 1, 10, 10));
JTextArea one = new JTextArea("Hi");
one.setLineWrap(true);
one.setSize(100, 100);
JTextArea two = new JTextArea("Goodbye");
two.setLineWrap(true);
two.setSize(100, 100);
bodyPanelMain.add(one);
bodyPanelMain.add(two);
bodyPanelMain.repaint();
If I make JTextArea's width 200 and background a different color, it's clear that it's visible behind it, so it's most certainly adding all the proper elements, their positions are just wrong.
EDIT: Here's a very very short version of what I am trying to do.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class minimessageboard extends Applet implements ActionListener {
JPanel mainPanel;
JPanel buttonPanel;
JButton announcements, websites;
JPanel bodyPanel, bodyPanelMain;
public minimessageboard() {
this.setSize(600, 400);
mainPanel = new JPanel(new BorderLayout());
mainPanel.setPreferredSize(new Dimension(this.getWidth(), this.getHeight()));
this.add(mainPanel);
buttonPanel = new JPanel(new GridLayout(6, 1, 10, 10));
mainPanel.add(buttonPanel, BorderLayout.WEST);
announcements = new JButton("Announcements");
this.formatButton(announcements);
announcements.setActionCommand("announcements");
buttonPanel.add(announcements);
websites = new JButton("Websites");
this.formatButton(websites);
websites.setActionCommand("websites");
buttonPanel.add(websites);
bodyPanel = new JPanel(new BorderLayout());
bodyPanel.setSize(200, 500);
bodyPanel.setPreferredSize(new Dimension(200, 500));
mainPanel.add(bodyPanel, BorderLayout.CENTER);
bodyPanelMain = new JPanel(new BorderLayout());
bodyPanel.add(bodyPanelMain, BorderLayout.CENTER);
bodyPanelMain.setLayout(new GridLayout(4, 1, 10, 10));
JButton one = new JButton("Roar");
bodyPanelMain.add(one);
bodyPanelMain.revalidate();
bodyPanelMain.repaint();
}
public static void main(String args[]) {
JFrame overall = new JFrame();
overall.pack();
overall.setVisible(true);
overall.add(new minimessageboard());
}
public void formatButton(JButton b){
b.setPreferredSize(new Dimension(150, 33));
b.addActionListener(this);
}
public void actionPerformed(ActionEvent arg0) {
String action = arg0.getActionCommand();
bodyPanelMain.removeAll();
if (action.equals("websites")){
System.out.println("Fires!");
bodyPanelMain.setLayout(new GridLayout(4, 1, 10, 10));
JButton one = new JButton("Hi");
JButton two = new JButton("Goodbye");
bodyPanelMain.add(one);
bodyPanelMain.add(two);
bodyPanelMain.revalidate();
}
bodyPanelMain.repaint();
}
}
Basically, when you click on websites, "Hi" and "Bye" should show up. If I move the code within the block in the websites if statement (if (action.equals("websites")) up to the original constructor, it appears perfectly fine. The code outputs "Fires!", so I am 100% certain it gets to that part. For note, I changed it from JTextArea to JButton because I will be using JButtons, not JTextArea.
Don't set the size of a JTextArea as it won't work well when your text extends beyond the text area size and you find that it just won't scroll. Instead set the preferred row and column values, and then let the JTextArea size itself. On to your problem: are you adding these components after the GUI has rendered itself? If so, do you call revalidate() on the bodyPanelMain after it receives the JTextAreas? If this doesn't help, consider creating and posting an sscce.
For example, this works fine for me:
import java.awt.GridLayout;
import javax.swing.*;
public class SwingFoo {
private static final int ROWS = 10;
private static final int COLS = 16;
private static void createAndShowGui() {
JPanel bodyPanelMain = new JPanel();
bodyPanelMain.setLayout(new GridLayout(4, 1, 10, 10));
JTextArea one = new JTextArea("Hi", ROWS, COLS);
one.setLineWrap(true);
// one.setSize(100, 100);
JTextArea two = new JTextArea("Goodbye", ROWS, COLS);
two.setLineWrap(true);
// two.setSize(100, 100);
bodyPanelMain.add(new JScrollPane(one));
bodyPanelMain.add(new JScrollPane(two));
// bodyPanelMain.repaint();
JFrame frame = new JFrame("SwingFoo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(bodyPanelMain);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

Categories

Resources