Currently, I'm working on java Frame. I have an issue with making the size of the textfield bigger since I can't really see what I typed. I used command+a, then copied and pasted what I typed in another textarea, and it showed as I typed. However, I want to make my textfield bigger. Please let me know what I can do.
This is main class.
public static void main(String[]args)
{
Frame f = new Frame("This is practice title bar!");
f.addWindowListener(new ExitListener());
f.setLayout(new GridLayout(2,1,20,20));
Panel myPanel = new Panel();
myPanel.setLayout(new GridLayout(3,3,20,20));
Label lName = new Label("Name");
lName.setAlignment(Label.CENTER);
myPanel.add(lName);
Label lAge = new Label("Age");
lAge.setAlignment(Label.CENTER);
myPanel.add(lAge);
Label lWeight = new Label("Weight");
lWeight.setAlignment(Label.CENTER);
myPanel.add(lWeight);
TextField tfName = new TextField();
myPanel.add(tfName);
TextField tfAge = new TextField();
myPanel.add(tfAge);
kgPanel kp = new kgPanel();
myPanel.add(kp);
Label empty = new Label("");
myPanel.add(empty);
Button addBtn = new Button("Add");
addBtn.addActionListener(new UserActionListener());
myPanel.add(addBtn);
Label empty2 = new Label("");
myPanel.add(empty2);
f.add(myPanel);
TextArea ta = new TextArea();
f.add(ta);
f.pack();
f.setSize(500,500);
f.setVisible(true);
}
This is kgPanel class.
import java.awt.*;
public class kgPanel extends Panel
{
public TextField weightTf = null;
public Label measurement = null;
public kgPanel()
{
tfAndKg();
}
public kgPanel(LayoutManager layout)
{
super(layout);
tfAndKg();
}
public void tfAndKg()
{
weightTf = new TextField();
add(weightTf);
measurement = new Label("kg");
add(measurement);
}
}
And the image is a result. Please let me know which part should I edit to make my textfield bigger.
Thank you
I tried to use
weightTf.setSize()
and
weightTf.setBounds()
but didn't work.
Please help me.
Related
So I'm new to Java learning some basics from videos on YouTube, I'm learning to make a GUI/Window and at the moment I'm trying to get iamges to be displayed but I'm not sure if code is wrong/old or the images are not in the right spot/location. Here's what I've written up so far. Help would be much appreciated. Please and Thank you.
import java.awt.*;
import javax.swing.*;
public class FirstGUI extends JFrame {
private static Object out;
private JLabel label;
private JButton button;
private JTextField textfield;
private ImageIcon image1;
private JLabel label1;
private ImageIcon image2;
private JLabel label2;
public FirstGUI() {
setLayout (new FlowLayout());
label = new JLabel("Hi, I'm a label!");
add(label);
textfield = new JTextField(15);
add(textfield);
button = new JButton("Click me!");
add(button);
button = new JButton("No, CLICK ME!!");
add(button);
label = new JLabel("This is the end of the program?");
add(label);
image1 = new ImageIcon(getClass().getResource("Apiary.png"));
label1 = new JLabel(image1);
image2 = new ImageIcon(getClass().getResource("bee.png"));
label2 = new JLabel(image2);
}
public static void main(String[] args) {
FirstGUI gui = new FirstGUI();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//* gui.setSize(400, 400);
gui.setVisible(true);
gui.setTitle("Hello World");
gui.pack();
}
}
What I get in the errors are:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.(Unknown Source)
at FirstGUI.(FirstGUI.java:39)
at FirstGUI.main(FirstGUI.java:50)
First you're not adding the labels to the frame, so even if that executes it won't show the image icons. So don't forget to add the labels to the frame:
add(label1);
add(label2);
Second I tried your code and it worked fine for me, it only printed the error you mentioned when I didn't import the image icon to the package i'm working in.
For this you need to do this:
Right click on your src package-> import-> General -> File System and then click next and select the directory that contains the images, click Ok and then add the images you specified in the code.
trying to make program where after clicking on buttom it should open new JFrame inside it should have different labels and TextFields....It all compile and work how it should beside History JTextField and hisScrollPAne these ScrollPAne not appeared at all TextField Appeared in completly wrong place....if change bounds armor JTextField and historyJTextField then it history appearing in right place but armor in wrong..not sure what I did wrong.....dimenssions of JFrame(800,900)
This is whole code related to this JFrame...
private void object704JButtonActonPerformed(ActionEvent event)
{
JFrame object704 = new JFrame("object704");
object704.setLayout(new BorderLayout());
JLabel titleJLabel704 = new JLabel();
titleJLabel704.setBounds(0,20,800,36);
titleJLabel704.setFont(new Font("Serif",Font.BOLD,30));
titleJLabel704.setText("Object704");
titleJLabel704.setHorizontalAlignment(JLabel.CENTER);
object704.add(titleJLabel704);
JLabel obPicJLabel = new JLabel();
obPicJLabel.setBounds(190,90,400,215);
obPicJLabel.setIcon(new ImageIcon("gr/objPic.jpg"));
object704.add(obPicJLabel);
JLabel weaponJLabel = new JLabel();
weaponJLabel.setBounds(113,345,70,30);
weaponJLabel.setFont(new Font("Serif",Font.BOLD,20));
weaponJLabel.setText("Weapon");
object704.add(weaponJLabel);
JLabel armorJLabel = new JLabel();
armorJLabel.setBounds(345,345,70,30);
armorJLabel.setFont(new Font("Serif",Font.BOLD,20));
armorJLabel.setText("Armor");
object704.add(armorJLabel);
JLabel historyJLabel = new JLabel();
historyJLabel.setBounds(590,345,70,30);
historyJLabel.setFont(new Font("Serif",Font.BOLD,20));
historyJLabel.setText("History");
object704.add(historyJLabel);
JTextArea weaponJTextArea = new JTextArea("Test2");
weaponJTextArea.setEditable(false);
weaponJTextArea.setBounds(40,380,225,400);
object704.add(weaponJTextArea);
JScrollPane scrollJScrollPane = new JScrollPane(weaponJTextArea);
scrollJScrollPane.setBounds(40,380,225,400);
object704.add(scrollJScrollPane);
JTextArea armorJTextArea = new JTextArea("Test1");
//armorJTextArea.setEditable(false);
armorJTextArea.setVerticalAlignment(JTextArea.CENTER);
armorJTextArea.setBounds(287,380,225,400);
object704.add(armorJTextArea);
JScrollPane armScrollPane = new JScrollPane(armorJTextArea);
armScrollPane.setBounds(287,380,225,400);
object704.add(armScrollPane);
JTextField historyJtextField = new JTextField("test");
//historyJtextField.setEditable(false);
historyJtextField.setBounds(530,380,200,400);
object704.add(historyJtextField);
JTextArea historyJTextArea = new JTextArea();
historyJTextArea.setEditable(false);
historyJTextArea.setBounds(530,380,200,400);
object704.add(historyJTextArea);
JScrollPane hisScrollPane = new JScrollPane(historyJTextArea);
hisScrollPane.setBounds(530,380,200,400);
object704.add(hisScrollPane);
object704.setSize(850,900);
object704.setVisible(true);
I'm getting the error message null pointer exception on the line img.setIcon(bg); in the controller class in my action listener and I'm not sure why. I've commented where the error is highlighted. Any ideas on why?
public class Display {
public ImageIcon bg;
public JLabel img;
public void UI() {
Controller listener = new Controller();
bg = new ImageIcon("prophase.png");
img = new JLabel(bg, JLabel.CENTER);
JFrame gameFrame = new JFrame();
JPanel top = new JPanel();
JPanel bottom = new JPanel();
JPanel imgPane = new JPanel();
JPanel panel1 = new JPanel();
imgPane.setLayout(new BorderLayout());
panel1.setLayout(new BorderLayout());
panel1.setOpaque(false);// !!
top.setBorder(BorderFactory.createTitledBorder(""));
bottom.setBorder(BorderFactory.createTitledBorder(""));
JLabel jl = new JLabel("What stage of mitosis is this?", JLabel.CENTER);
imgPane.add(img);// center
top.add(jl);// top center
top.add(listener.wordListener());// top center
bottom.add(listener.answer);// bottom
panel1.add(imgPane, BorderLayout.CENTER);// background image (center)
panel1.add(top, BorderLayout.NORTH);// text field and jlabel (top)
panel1.add(bottom, BorderLayout.SOUTH);// blank spaces and letters used
gameFrame.setJMenuBar(menuBar());
gameFrame.setTitle("Mitosis");
gameFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameFrame.setIconImage(new ImageIcon("logo.png").getImage());
gameFrame.setResizable(false);
gameFrame.add(panel1);
gameFrame.setSize(400, 300);
gameFrame.setLocationRelativeTo(null);
gameFrame.setVisible(true);
}
}
another class:
public class Controller {
Display display = new Display();
private JFrame dialogFrame = new JFrame();
private ImageIcon logo = new ImageIcon("logo.png");
public String word;
public JLabel answer = new JLabel(" ", JLabel.CENTER);
public JTextField wordListener() {
JTextField tf = new JTextField(10);
tf.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {// right click key
JTextField tf = (JTextField) e.getSource();
word = tf.getText();
if (word.equalsIgnoreCase("Prophase")) {
answer.setText("Correct!");
ImageIcon bg = display.bg;
JLabel img = display.img;
bg = new ImageIcon("interphase.png");
img.setIcon(bg);//error
answer.setText(" ");
} else {
answer.setText("Incorrect, try again.");
}
tf.setText("");
}// end actionPerformed method
});
return tf;
}
}
The default constructor of Display doesn't initialize the attribute img, which is then initialized to null by default. The exception is clearly due to the fact that you are trying to use img without initializing it anywhere. You should define a default constructor for Display that does something like this:
public Display(){
UI();
}
Because in UI() you are initializing img.
Also you have to initialize your display before using img, like this:
Display display = new Display();
Please check if the path for your image is correct
bg = new ImageIcon("interphase.png");
If a resource is not found you will get a NullPointerException when you try to use that imageicon somewhere else.
Try something along the lines
getClass().getResource("interphase.png");
prepend the directory name if needed, in order to get to your image in your resources.
Also, make sure you are initialising the variable in the Display class before using it.
I am trying to create a form manually with code rather than the designer, I have already created using the designer.
This is the manual code that I came up with so far but I am having problem aligning the label and textfield side by side
mport java.awt.*;
import javax.swing.*;
/**
*
* #author jackandjill
*/
public class summinup_copy extends JFrame
{
private JLabel lblTitle, lblOctal, lblDecimal, lblMessage ;
private JTextField txtOctal, txtDecimal;
private JButton calculate_btn;
public summinup_copy()
{
JPanel panel = (JPanel)this.getContentPane();
panel.setLayout(new BorderLayout());
JPanel panCentre = new JPanel();
panCentre.setLayout(new GridLayout(3,3));
lblTitle = new JLabel("Area of Triangle");
lblTitle.setFont(new Font("Arial", 1, 20));
lblTitle.setHorizontalAlignment(JLabel.CENTER);
lblOctal = new JLabel("Octal");
lblOctal.setHorizontalAlignment(JLabel.CENTER) ;
//lblDecimal = new JLabel("Decimal");
//
//lblDecimal.setHorizontalAlignment(JLabel.CENTER);
lblMessage = new JLabel("Result will be displayed here");
lblMessage.setForeground(Color.red);
lblMessage.setHorizontalAlignment(JLabel.CENTER);
txtOctal = new JTextField("0", 5);
txtOctal.setHorizontalAlignment(JLabel.CENTER);
//txtDecimal = new JTextField("0", 5);
//
//txtDecimal.setHorizontalAlignment(JLabel.CENTER);
calculate_btn = new JButton("Calculate Area");
//AHandlerClass aListener = new AHandlerClass() ;
//btnOtoD.addActionListener(aListener);
//btnDtoO.addActionListener(aListener);
panCentre.add(lblOctal);
//panCentre.add(lblDecimal);
panCentre.add(txtOctal);
//panCentre.add(txtDecimal);
panCentre.add(calculate_btn);
//panCentre.add(btnDtoO);
panel.add(lblTitle, BorderLayout.NORTH);
panel.add(lblMessage,BorderLayout.SOUTH);
panel.add(panCentre, BorderLayout.CENTER);
}
public static void main(String args[]) {
summinup_copy myGui = new summinup_copy();
myGui.setTitle("Bharath");
myGui.setSize(400, 200);
myGui.setVisible(true);
}
}
As you have already figured out, you have to use LayoutManagers when coding a Swing GUI by hand. Here are some links that can help you figure out which LayoutManager is appropriate for a given look:
http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html
http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html
In order to place a JLabel next to a JTextField or other component, I usually use GridLayout or GridBagLayout. I find that it takes a lot of trial and error trying to get components to look the way I want. Often you have to have layers of embedded JPanels to get it just right.
I'm writing a Java programm, according to MVC model.
So the problem is that the Frame doesn't react to button click.
(The text, that I write isn't added to the TextArea after click)
At first I call constructors for View and Controller
MessageFrame mf = new MessageFrame(con);
MessageFrameListener mfl = new MessageFrameListener(mf);
Here is the part of MessageFrameListener class (controller)
public class MessageFrameListener{
private MessageFrame mf;
public MessageFrameListener(MessageFrame m_f){
mf = m_f;
m_f.addButtonListener(new SButtonListener());
}
//#Override
public class SButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
String insert = mf.getInput();
mf.addLine(insert);
mf.refreshInput();
}
}
}
Here is the part from MessageFrame class (View)
public class MessageFrame{
public JTextField messField;
public JTextArea dialogArea;
public JButton sendButton;
public JFrame frame;
public Contact con;
public MessageFrame (Contact con_get) {
con = con_get;
frame = new JFrame();
frame.setSize(538, 299);
JPanel panel_1 = new JPanel();
frame.getContentPane().add(panel_1, BorderLayout.NORTH);
JPanel panel_2 = new JPanel();
frame.getContentPane().add(panel_2, BorderLayout.SOUTH);
panel_2.setLayout(new BoxLayout(panel_2, BoxLayout.X_AXIS));
messField = new JTextField();
panel_2.add(messField);
messField.setColumns(10);
JButton sendButton = new JButton("Send");
panel_2.add(sendButton);
JPanel panel_3 = new JPanel();
frame.getContentPane().add(panel_3, BorderLayout.EAST);
JPanel panel_4 = new JPanel();
frame.getContentPane().add(panel_4, BorderLayout.CENTER);
panel_4.setLayout(new BorderLayout(0, 0));
JTextArea dialogArea = new JTextArea();
panel_4.add(dialogArea);
frame.setVisible(true);
}
public String getInput(){
return messField.getText();
}
public void refreshInput(){
messField.setText("");
}
public void addLine(String line){
dialogArea.append(line);
}
public void addButtonListener(ActionListener bal){
sendButton.addActionListener(bal);
}
}
You will definately find the answer if you check the output of your program or debug it.
Exception in thread "main" java.lang.NullPointerException
at test3.MessageFrame.addButtonListener(Main.java:93)
at test3.MessageFrameListener.<init>(Main.java:28)
at test3.Main.main(Main.java:18)
Your are hiding the reference to the JButton sendButton by declaring it again in the constructor so the field is never initialised.
JButton sendButton = new JButton("Send");
panel_2.add(sendButton);
Since you've posted code scraps and have not posted a functioning SSCCE that we can test, all we can do is guess -- so you'll get what you paid for, and here goes my guess:
You're listening on the wrong MessageFrame. Your program has 2 or more MessageFrame objects, one of which is displayed, and the other which is being listened to, and so your displayed MessageFrame will of never trip the listener.
If this doesn't help, and you need better help, then please provide us with a better question, and an sscce.
You are adding an empty string:
String insert = mf.getInput(); //all it does is: messField.getText();
mf.addLine(insert); //adding the empty string
mf.refreshInput(); //all it does is: messField.setText("");