GridBagLayout is not positioning my JTextArea where I want it to - java

I am trying to place a JTextArea inside of JFrame using GridBagLayout. I cannot resize the text area nor is it being placed according to my gridx and gridy coordinates. Having a bit of trouble figuring out whats missing or what I am doing wrong.
I am trying to build an ATM with a GUI interface. The text area will be my screen. Kinda new to GUI's so any help would be greatly appreciated.
ATM.java
Represents an automated teller machine
import java.awt.Color;
import javax.swing.JFrame;
import java.awt.FlowLayout;
import java.awt.BorderLayout;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Component;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JButton;
import java.awt.Container;
//import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ATM extends JFrame
{
private JFrame atmContainer;
private GridBagConstraints constraints;
private GridBagLayout layout;
private JTextArea atmScreen;
private Container container;
// constants corresponding to main menu options
/*private static final int BALANCE_INQUIRY = 1;
private static final int WITHDRAWAL = 2;
private static final int DEPOSIT = 3;
private static final int EXIT = 4;*/
// no-argument ATM constructor initializes instance variables
public ATM()
{
atmContainer = new JFrame("ATM");
atmScreen = new JTextArea(5,15);
atmContainer.setLayout(new GridBagLayout());
constraints = new GridBagConstraints();
atmContainer.setSize(600, 400);
atmContainer.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //completely closes the program
atmScreen.setText("Welcome user");
atmScreen.setEnabled(false);
// atmScreen.setSize(100,100);
constraints.gridx = 1;
constraints.gridy = 0;
atmContainer.add(atmScreen, constraints);
atmContainer.setVisible(true); //makes atm visible
atmContainer.setLocationRelativeTo(null);
}
}

Seeing you are new to GUIs, I advise utilizing a GUI builder; they make designing a GUI considerably easier and more productive. This question names a few options:
Best GUI designer for eclipse?
Also, is there a reason that you are using the GridBagLayout? For beginners, it may be a difficult to understand and to use. As pointed out by camickr, using the BorderLayout will do the job just fine.
From my personal experience, it was easier for me to first learn about the FlowLayout. It is the simplest of all layouts. You should gain a good understanding by experimenting with it a little.
The Java Tutorials are rich of lessons as well; this is a visual overview of possible layout managers:
https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html#gridbag
And this demonstrates how to use a FlowLayout:
https://docs.oracle.com/javase/tutorial/uiswing/layout/flow.html

Related

JDialog in center of screen instead of desired center of JApplet

In my Java applet I have JDialog with couple of radioButtons.
The problem is that this applet is of dimensions 700x300 and the JDialog appears in the center of screen. I want this JDialog to appear in the center of JApplet layout. My constructor invocation looks like this:
final JDialog dialog = new JDialog(
SwingUtilities.windowForComponent(GUIComponentContainer.getInstance().getDocumentTable()),
I18nCommonsImpl.constants.selectCertificate(), ModalityType.APPLICATION_MODAL);
This method:
GUIComponentContainer.getInstance().getDocumentTable()
returns JTable component which is a child of my JApplet.
I also used JDialog "setLocationRelativeTo" method:
dialog.setLocationRelativeTo(GUIComponentContainer.getInstance().getApplet());
None of these seem to work. Is there any other way to accomplish my goal?
I searched along SO for similar questions, but didn't see any working solutions.
Thanks in advance.
Getting the Window for the applet works for me, at least when the applet is launched in Eclipse. For example:
import java.awt.Dimension;
import java.awt.Window;
import java.awt.Dialog.ModalityType;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
#SuppressWarnings("serial")
public class AppletCentering extends JApplet {
#Override
public void init() {
final JPanel panel = new JPanel();
panel.add(new JButton(new AbstractAction("Press Me") {
#Override
public void actionPerformed(ActionEvent e) {
Window win = SwingUtilities.getWindowAncestor(panel);
System.out.println("win class: " + win.getClass().getCanonicalName());
JDialog dialog = new JDialog(win, "My Dialog", ModalityType.APPLICATION_MODAL);
dialog.add(Box.createRigidArea(new Dimension(200, 200)));
dialog.pack();
dialog.setLocationRelativeTo(win);
dialog.setVisible(true);
}
}));
add(panel);
}
}
But having said this, your question begs the question: why are you even coding for an applet? These have been out of favor for years, and just recently has lost support from Oracle who has decided to finally drop applet browser plug in support.

How To Add JLabel to Already Existing Jframe?

lol i dont even know if i worded that right
i am a really new programmer and this is my code for the main class:
package culminatingnew;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class CulminatingNew {
public static void main(String[] args) {
Container container = null;
JFrame jframe = new JFrame("Math Adventure");
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setLocationRelativeTo(null);
jframe.setBounds (150, 0, 1000, 1000);
jframe.setBackground(Color.blue);
jframe.setVisible(true);
JLabel labelText = new JLabel("Welcome!");
jframe.getContentPane().add(new CharacterChoose());//
jframe.setVisible(true);
jframe.getContentPane().add(labelText);
jframe.setVisible(true);
So basically, I'm making a game. In another class in the assignment package is CharacterChoose, where the user is greeted with a picture of their character. All I want to do is add text to this same screen saying "Welcome", but whenever I try this it just ignores the CharacterChoose screen and opens a new blank frame that says "Welcome". Is there any way to fix this?
GUI's are not linear/procedural programs, the are event driven, that is, something happens and you respond to it.
Instead, maybe consider using a button saying "Continue" or something, which the user must press, once pressed, you can then present the next view.
I'd recommend having a look at CardLayout for easier management of switching between views.
See How to Use Buttons, Check Boxes, and Radio Buttons, How to Write an Action Listeners and How to Use CardLayout for more details

How do i get the image from my jlable to auto scale or resize to the size of the JLabel [duplicate]

This question already has answers here:
Java: JPanel background not scaling
(2 answers)
Closed 8 years ago.
Im trying to add an image to a JLabel and i have encountered a problem where the image is to big for the JLabel so I'm looking for a way to make the image automatically scale to the size of the JLabel.
Here is my main body of code where i call up my GUImain class:
public class Main
{
public static void main(String[] args)
{
int i = 0;
int t = 0;
int st = 0;
int h = 0;
Texts textObject = new Texts();
textObject.TextList();
Commands commandObject = new Commands();
commandObject.commands();
GUImain guiObject = new GUImain();
guiObject.displayGUI();
}
}
And here is the code for my GUImain class, i will only include one image button because there are allot of objects in my code.
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JTextPane;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JScrollBar;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
public class GUImain
{
private JFrame frame;
private JTextField textField;
private ImageIcon image1;
public void displayGUI()
{
this.frame.setVisible(true);
}
//Launch the application.
public static void main(String[] args)
{
GUImain window = new GUImain();
}
//Create the application.
public GUImain()
{
frame = new JFrame();
frame.setBounds(100, 100, 611, 471);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
...
JLabel lblHunger = new JLabel();
Image img2 = new ImageIcon(this.getClass().getResource("/Food.png")).getImage();
lblHunger.setIcon(new ImageIcon(img2));
lblHunger.setBounds(211, 58, 50, 50);
panel.add(lblHunger);
}
}
}
Don't use a null layout!!!
Swing was designed to be used with layout managers. Let each component determine its preferred size and then let the layout manager size and position the component based on the rules of the layout manager.
Instead of doing custom painting you can use Darry'ls Stretch Icon. The Icon will be painted based on the space available to the icon.
i have encountered a problem where the image is to big for the JLabel
Just reread that part of the question. In that case you may want to use the Image.getScaledInstance(...) method to scale the image to an appropriate size. The you can use a regular Icon and the appropriate layout manager.
what layout would i be able to use to easily choose the dimensions and where the objects are positioned
You are not supposed to choose the size/location of a component. That is the job of the layout manager. Read the tutorial on Layout Managers and choose the one (or combination of layout managers) that is appropriate for your requirements.

How to set size of applet?

I have written a little test applet and start the applet via Eclipse appletviewer.
I have noted tag at the begginig of the code, but appletviewer doesn't see it. It starts the applet in standart window with the same size every time.
I use JDK 1.7, Eclipse Kepler
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
/*<applet code="TestApplet" width=200 height=40>
</applet>
*/
public class TestApplet extends JApplet{
private Container cp;
private JPanel mainPanel, testPanel1;
private JLabel testLabel1 = new JLabel("Test1"),
testLabel2 = new JLabel("Test2");
private JTextField testTextField1 = new JTextField(),
testTextField2 = new JTextField();
private JButton testButton1 = new JButton("TestButton1"),
testButton2 = new JButton("TestButton2");
public void init(){
cp = getContentPane();
testPanel1 = new JPanel(new GridLayout(3,1));
cp.add(testPanel1);
testPanel1.add(testLabel1);
testPanel1.add(testTextField1);
testPanel1.add(testButton1);
}
public void start(){
}
public void stop(){
}
public void destroy(){
}
}
How can I change size of the applet window when I start it using Eclipse?
You can change it in Run Configurations in Eclipse:
Run -> Run Configurations -> Java Applet -> New Configuration. the default size can be changed in the Parameters tab.
Note that this is only for testing and the actual applet your user sees is depends on how the applet is launched for them (Which is done typically via a <applet>, <object> or <embed> tags in a webpage. all of these tags support size attributes.)

How to display a Hierarchy (Java)

I have this project and it allows users to kind of create there own projects within it and save it off and do much more. Im doing this all in Java using the program Eclipse. Today I mainly wanted to know how would i go about displaying a Hierarchy? Ill be a little more specific, when the user creates a project it ask them where they want to have there project folder. Lets say they choose a folder name JavaProjects and its in there Desktop (I use windows so excuse me if it isnt the same on Mac and Linux) and within that folder they have a Scripts folder and an Art Folder and within there art folder they have a Texture folder and a Logo Folder (Im also coming up with these folders in my head as i make this) How can i have it where in my JPanelEast it display a format kind of like the Package Explorer In Eclipse? Would I be able to just scan the folder they put in and have all the folders and files neatly laid out like that? Or would i have to do something much more out of my knowledge?
If it helps here is my code, minus a menu bar and action listeners
package Engine;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.SwingConstants;
#SuppressWarnings("serial")
public class TestProjectBuilder extends JFrame {
JPanel jPanelNorth = new JPanel();
JPanel jPanelSouth = new JPanel();
JPanel jPanelEast = new JPanel();
JPanel jPanelCenter = new JPanel();
JButton jButtonDebug = new JButton("Debug");
JButton jButtonPause = new JButton("Pause");
JButton jButtonRun = new JButton("Run");
JLabel jLabelHeir = new JLabel("");
GridLayout gridLayout1 = new GridLayout(4,1);
public TestProjectBuilder() {
setTitle("Test Project Builder");
setSize(1400, 800);
jPanelNorth.setBackground(Color.DARK_GRAY);
jPanelNorth.setBorder(BorderFactory.createRaisedBevelBorder());
jPanelNorth.setPreferredSize(new Dimension(14, 40));
jPanelNorth.setToolTipText("North Panel");
jPanelNorth.add(jButtonDebug);
jButtonDebug.setHorizontalAlignment(SwingConstants.CENTER);
jPanelNorth.add(jButtonPause);
jButtonPause.setHorizontalAlignment(SwingConstants.CENTER);
jPanelNorth.add(jButtonRun);
jButtonRun.setHorizontalAlignment(SwingConstants.CENTER);
jPanelSouth.setBackground(Color.DARK_GRAY);
jPanelSouth.setBorder(BorderFactory.createTitledBorder(""));
jPanelSouth.setPreferredSize(new Dimension(10,200));
jPanelSouth.setToolTipText("South Panel");
jPanelEast.setBackground(Color.DARK_GRAY);
jPanelEast.setBorder(BorderFactory.createEtchedBorder());
jPanelEast.setPreferredSize(new Dimension(300,10));
jPanelEast.setToolTipText("East Panel");
jPanelCenter.setBackground(Color.GRAY);
jPanelCenter.setBorder(BorderFactory.createEtchedBorder());
jPanelCenter.setPreferredSize(new Dimension(56,10));
jPanelCenter.setToolTipText("Center Panel");
this.getContentPane().add(jPanelNorth, BorderLayout.NORTH);
this.getContentPane().add(jPanelSouth, BorderLayout.SOUTH);
this.getContentPane().add(jPanelEast, BorderLayout.EAST);
this.getContentPane().add(jPanelCenter, BorderLayout.CENTER);
jPanelCenter.setLayout(gridLayout1);
}
public static void main(String[] args) {
TestProjectBuilder tpb = new TestProjectBuilder();
tpb.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tpb.setVisible(true);
}
}
Thanks for all Help in advance
You might start with the code for File Browser GUI.
The Java Tutorial has a section on using TreeViews for this.
http://docs.oracle.com/javase/tutorial/uiswing/components/tree.html
I post the link here, because this a bit to complicated for a simple answer.

Categories