Noob here. I have been browsing for hours, and I still cannot figure out the proper way to get user input to be saved as a string from a text field in my Jframe. Any help would be appreciated. I want to save the user's text into the variable userWords.
package cipher;
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
public class cipherApp extends JFrame {
private static final int WIDTH = 700;
private static final int HEIGHT = 700;
private String userWords; // stores user input into a string
public cipherApp(){
setTitle("Camo Cipher");
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args){
cipherApp newInstance = new cipherApp();
}
}
You have to use a JTextField and a JButton to submit the use input:
public class Test extends JFrame {
String userWord = "";
JTextField userInput = new JTextField(10);
JButton submit = new JButton("Submit");
public Test() {
super("Camo Cipher");
JPanel centerPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 15));
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null); // This center the window on the screen
submit.addActionListener( (e)-> {
submitAction();
});
centerPanel.add(userInput);
JPanel southPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 15, 15));
southPanel.add(submit);
Box theBox = Box.createVerticalBox();
theBox.add(Box.createVerticalStrut(100));
theBox.add(centerPanel);
theBox.add(Box.createVerticalStrut(200));
theBox.add(southPanel);
add(theBox);
}
private void submitAction() {
// You can do some validation here before assign the text to the variable
userWord = userInput.getText();
}
public static void main(String[] args) {
new Test().setVisible(true);
}
}
This is a variation of BilaDja's code (I mainly changed the graphics). This will make the window size at around half the screen, in the middle of the screen. If you would like to change the size, change the field 'jf.setSize(x, y);'.
package test;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Test extends JFrame {
private static final long serialVersionUID = -5624404136485946868L;
String userWord = "";
JTextField userInput;
public Test() {
JFrame jf = new JFrame();
JPanel panel = new JPanel();
JLabel jl = new JLabel("Test");
JButton jButton = new JButton("Click");
userInput = new JTextField("", 30);
jButton.addActionListener( (e) -> {
submitAction();
});
jf.setSize(500, 500);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(panel);
panel.add(jl);
panel.add(userInput);
panel.add(jButton);
}
private void submitAction() {
userWord = userInput.getText();
//do something with the variabe userWord here (print it to the console, etc.)
}
public static void main(String[] args) {
new Test();
}
Related
Everything looks ok to me but for some reason, nothing is showing up properly, maybe I missed something but I'm not sure why it's not working, can someone help me out?
** task **
Improve your program by adding two
combo boxes in the frame. Through the combo boxes, the user should be able to
select their preferred fonts and font sizes. The displayed text will then be updated
accordingly (see the figure below).
Here is what its suppose to look like
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JTextField;
import java.awt.*;
import java.awt.event.*;
public class ComboGUI extends JFrame implements ActionListener {
public JButton update;
public JTextField textField;
public JLabel textLabel;
public JComboBox<String> fontBox;
public JComboBox sizeBox;
public String font;
public String size;
public ComboGUI()
{
components();
panels();
actionListener();
}
public void components()
{
this.update = new JButton("update");
this.textField=new JTextField(20);
this.textField.setText("hello");
this.textLabel= new JLabel("GUI");
this.font="Arial";
this.size="20";
this.textLabel.setFont(new Font(this.font, Font.PLAIN, Integer.parseInt(this.size)));
this.fontBox=new JComboBox();
this.fontBox.addItem("Times New Roman");
this.fontBox.addItem("Calibri");
this.sizeBox= new JComboBox();
this.sizeBox.addItem("20");
this.sizeBox.addItem("30");
this.sizeBox.addItem("40");
this.setSize(400, 400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
}
public void panels(){
JPanel northPanel =new JPanel();
JLabel fontLabel =new JLabel("Font: ");
JLabel sizeLabel =new JLabel("size: ");
northPanel.add(fontLabel);
//center
BGPanel centerPanel =new BGPanel();
centerPanel.add(this.textLabel);
this.add(centerPanel,BorderLayout.CENTER);
//south
BGPanel southPanel =new BGPanel();
southPanel.add(this.textLabel);
this.add(southPanel,BorderLayout.CENTER);
}
public void actionListener(){
this.update.addActionListener(this);
this.fontBox.addActionListener(this);
this.sizeBox.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e){
if(e.getSource()==this.update){
this.textLabel.setText(this.textField.getText());
}
if(e.getSource()==this.fontBox || e.getSource()==this.sizeBox){
this.font=this.fontBox.getSelectedItem().toString();
this.size=this.sizeBox.getSelectedItem().toString();
this.textLabel.setFont(new Font(this.font,Font.PLAIN,Integer.parseInt(this.size)));
}
this.repaint();
}
public static void main(String[] args) {
ComboGUI comb =new ComboGUI();
combo.setVisible(true);
}
}
this is what im getting instead
It looks like you are missing this.setVisible(true); at the end of your constructor.
Your code should look like this:
public ComboGUI()
{
components();
panels();
actionListener();
this.setVisible(true);
}
incase anyone is trying to do something similar, this is the complete solution
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
public class ComboGUI extends JFrame implements ActionListener{
public void updateLabelText(){
size = fSize.getItemAt(fSize.getSelectedIndex());
font = fStyles.getItemAt(fStyles.getSelectedIndex());
updateLabel.setFont(new Font(font,Font.PLAIN,size));
}
public static BGPanel centrePanel;
public JComboBox<String> fStyles;
public JComboBox<Integer> fSize;
public JButton updateButton;
public JLabel updateLabel;
public JLabel fontLabel;
public JLabel sizeLabel;
public JTextField textField;
public JPanel BottomPanel;
public JPanel topPanel;
private String font;
private int size;
public ComboGUI() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400,400);
this.setLocation(0, 0);
//Top
topPanel = new JPanel();
fontLabel = new JLabel("Font:");
sizeLabel = new JLabel("Font Size:");
fStyles = new JComboBox<String>();
fStyles.addItem("Arial");
fStyles.addItem("TimesRoman");
fStyles.addItem("Serif");
fStyles.addItem("Monospaced");
fStyles.addActionListener(this);
fSize = new JComboBox<Integer>();
fSize.addItem(10);
fSize.addItem(20);
fSize.addItem(30);
fSize.addItem(40);
fSize.addActionListener(this);
topPanel.add(fontLabel);
topPanel.add(fStyles);
topPanel.add(sizeLabel);
topPanel.add(fSize);
//CentrePanel setup
centrePanel = new BGPanel();
updateLabel = new JLabel("I love PDC :)");
centrePanel.add(updateLabel);
//Bottom
BottomPanel = new JPanel();
updateButton = new JButton("Update");
textField = new JTextField(20);
textField.setText("I love PDC :)");
updateButton.addActionListener(this);
BottomPanel.add(textField);
BottomPanel.add(updateButton);
this.add(centrePanel,BorderLayout.CENTER);
this.add(BottomPanel,BorderLayout.SOUTH);
this.add(topPanel,BorderLayout.NORTH);
updateLabelText();
}
public static void main(String[] args) {
ComboGUI combo = new ComboGUI();
combo.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == updateButton){
updateLabel.setText(textField.getText().trim());
}
if(e.getSource() == fStyles){
updateLabelText();
}
if (e.getSource() == fSize){
updateLabelText();
}
}
}
This is my code and when I execute, all I get is a blank window. First when I tried to do main.setContentPane() I got this error:
"Cannot make a static reference to the non-static field panel"
So i put it in the constructor, but nothing would show.
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainFrame extends JFrame{
private JPanel panel;
private JButton performance;
private JButton concordance;
private JButton discordance;
private JButton resultat;
public void MainFrame() {
panel = new JPanel(new GridLayout(4, 1, 10, 10));
performance = new JButton("performance");
concordance = new JButton("concordance");
discordance = new JButton("discordance");
resultat = new JButton("resultat");
performance.setSize(50, 30);
concordance.setSize(50, 30);
discordance.setSize(50, 30);
resultat.setSize(50, 30);
panel.add(performance);
panel.add(concordance);
panel.add(discordance);
panel.add(resultat);
getContentPane().add(panel);
}
public static void main(String[] args) {
MainFrame main = new MainFrame();
main.setSize(300, 200);
main.setDefaultCloseOperation(EXIT_ON_CLOSE);
main.setVisible(true);
}
}
You have a method (returning void) called MainFrame that is never being called.
You should either make that the constructor, or create a constructor that calls that method like so:
public class MainFrame extends JFrame {
private JPanel panel;
private JButton performance;
private JButton concordance;
private JButton discordance;
private JButton resultat;
public MainFrame() {
super();
MainFrame();
}
public void MainFrame() {
panel = new JPanel(new GridLayout(4, 1, 10, 10));
performance = new JButton("performance");
concordance = new JButton("concordance");
discordance = new JButton("discordance");
resultat = new JButton("resultat");
performance.setSize(50, 30);
concordance.setSize(50, 30);
discordance.setSize(50, 30);
resultat.setSize(50, 30);
panel.add(performance);
panel.add(concordance);
panel.add(discordance);
panel.add(resultat);
this.getContentPane().add(panel);
}
public static void main(String[] args) {
MainFrame main = new MainFrame();
main.setSize(300, 200);
main.setDefaultCloseOperation(EXIT_ON_CLOSE);
main.setVisible(true);
main.MainFrame();
}
}
I am trying to make my program so that an integer value entered in a JTextfield can be stored into a variable. Then, when a JButton is clicked, this variable can tell a JSlider to move it's head to that of the integer value stored in the variable. My class name is Camera.Java
Code is showing no errors, however if I click my JButton, nothing happens, instead I see this error in the console:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:504)
at java.lang.Integer.parseInt(Integer.java:527)
at Camera.main(Camera.java:67)
My code:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Hashtable;
import java.util.Scanner;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.*;
public class Camera {
static JButton addtolist;
static Scanner input = new Scanner(System.in);
static JSlider cam = new JSlider();
static JTextField enterval = new JTextField();
static int x ;
public static void main (String args[]){
JFrame myFrame = new JFrame ("Matthew Damon on Mars");
myFrame.setSize(300, 600);
JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
JLabel userinp = new JLabel("Enter input: ");
cam = new JSlider(0, 15, 0);
cam.setPaintLabels(true);
enterval.setPreferredSize(new Dimension(100,80));
addtolist = new JButton("Enter");
addtolist.setPreferredSize(new Dimension(50,20));
JTextField enterval1 = new JTextField();
panel.add(addtolist);
Hashtable<Integer, JLabel> table = new Hashtable<Integer, JLabel>();
table.put(0, new JLabel("0"));
table.put(1, new JLabel("1"));
table.put(2, new JLabel("2"));
table.put(3, new JLabel("3"));
table.put(4, new JLabel("4"));
table.put(5, new JLabel("5"));
table.put(6, new JLabel("6"));
table.put(7, new JLabel("7"));
table.put(8, new JLabel("8"));
table.put(9, new JLabel("9"));
table.put(10, new JLabel("A"));
table.put(11, new JLabel("B"));
table.put(12, new JLabel("C"));
table.put(13, new JLabel("D"));
table.put(14, new JLabel("E"));
table.put(15, new JLabel("F"));
cam.setLabelTable(table);
myFrame.add(cam, BorderLayout.SOUTH);
myFrame.add(userinp, BorderLayout.NORTH);
myFrame.add(enterval1, BorderLayout.NORTH);
myFrame.add(panel, BorderLayout.CENTER);
myFrame.setVisible(true);
buttonAction();
}
public static void buttonAction() {
addtolist.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
int x = Integer.parseInt(enterval.getText());
cam.setValue(x);
} catch (NumberFormatException npe) {
// show a warning message
}
}
});
}
}
Your setting x on program creation before the user has had any chance to change its value. Get the text value from within the actionPerformed method which should be after the user has already selected a value, parse it into a number and set the slider with that value.
public void actionPerformed(ActionEvent e) {
try {
int x = Integer.parseInt(enterval.getText());
cam.setValue(x);
} catch (NumberFormatException npe) {
// show a warning message
}
}
Then get rid of all that static nonsense. The only method that should be static here is main, and it should do nothing but create an instance and set it visible.
Note that better than using a JTextField, use a JSpinner or a JFormattedTextField or if you're really stuck, a DocumentFilter to limit what the user can enter
Again, you should put most everything into the instance realm and out of the static realm. This means getting most of that code outside of the main method and into other methods and constructors, that means not trying to access fields or methods from the class, but rather from the instance. For instance, your main method should only create the main instances, hook them up and set them running and that's it. It should not be used to build the specific GUI components. For example:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import javax.swing.*;
#SuppressWarnings("serial")
public class CameraFoo extends JPanel {
// only static field here is a constant.
private static String TEXTS = "0123456789ABCDEF";
private JSpinner spinner = new JSpinner();
private JSlider slider = new JSlider(0, 15, 0);
public CameraFoo() {
List<Character> charList = new ArrayList<>();
Hashtable<Integer, JLabel> table = new Hashtable<>();
for (int i = 0; i < TEXTS.toCharArray().length; i++) {
char c = TEXTS.charAt(i);
String myText = String.valueOf(c);
JLabel label = new JLabel(myText);
table.put(i, label);
charList.add(c);
}
SpinnerListModel spinnerModel = new SpinnerListModel(charList);
spinner.setModel(spinnerModel);
slider.setLabelTable(table);
slider.setPaintLabels(true);
JPanel topPanel = new JPanel();
topPanel.add(spinner);
topPanel.add(new JButton(new ButtonAction("Press Me")));
setLayout(new BorderLayout());
add(topPanel, BorderLayout.PAGE_START);
add(slider);
}
private class ButtonAction extends AbstractAction {
public ButtonAction(String name) {
super(name);
}
#Override
public void actionPerformed(ActionEvent e) {
char ch = (char) spinner.getValue();
int value = TEXTS.indexOf(ch);
slider.setValue(value);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
createAndShowGui();
});
}
private static void createAndShowGui() {
CameraFoo mainPanel = new CameraFoo();
JFrame frame = new JFrame("CameraFoo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
}
My program is supposed to have the basic code examples in java and to do that I need help to have the dialogues where I can write have the code preloaded but I can't add spaces in the dialogues and resize them. Please help!
Main Class:
public class JavaHelperTester{
public static void main(String[] args){
JavaWindow display = new JavaWindow();
JavaHelper j = new JavaHelper();
display.addPanel(j);
display.showFrame();
}
}
Method Class:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class JavaHelper extends JPanel implements ActionListener{
JButton print = new JButton("Print Statements");
JButton classes = new JButton("Classes");
JButton varibles = new JButton("Assiging variables");
JButton signs = new JButton("Sign meanings");
JButton typesv = new JButton("Different Types of variables");
JButton scanners = new JButton("Scanner");
JButton loops = new JButton("Loops");
JButton ifstatements = new JButton("If statements");
JButton graphics = new JButton("Graphics");
JButton objects = new JButton("Making an oject");
JButton importstatments = new JButton("Import Statements");
JButton integers = new JButton("Different types of integers");
JButton methods = new JButton("Scanner methods");
JButton math = new JButton("Math in java");
JButton creation = new JButton("Method creation");
JButton arrays = new JButton("Arrays");
JButton jframe = new JButton("JFrame");
JButton stringtokenizer = new JButton("String Tokenizer");
JButton extending = new JButton("Class extending");
JButton fileio = new JButton("File I.O.");
JButton quit = new JButton("Quit");
public JavaHelper(){
setPreferredSize(new Dimension(500,350));
setBackground(Color.gray);
this.add(print);
print.addActionListener(this);
this.add(classes);
classes.addActionListener(this);
this.add(varibles);
varibles.addActionListener(this);
this.add(signs);
signs.addActionListener(this);
this.add(typesv);
typesv.addActionListener(this);
this.add(scanners);
scanners.addActionListener(this);
this.add(loops);
loops.addActionListener(this);
this.add(ifstatements);
ifstatements.addActionListener(this);
this.add(graphics);
graphics.addActionListener(this);
this.add(objects);
objects.addActionListener(this);
this.add(importstatments);
importstatments.addActionListener(this);
this.add(integers);
integers.addActionListener(this);
this.add(methods);
methods.addActionListener(this);
this.add(math);
math.addActionListener(this);
this.add(creation);
creation.addActionListener(this);
this.add(arrays);
arrays.addActionListener(this);
this.add(jframe);
jframe.addActionListener(this);
this.add(stringtokenizer);
stringtokenizer.addActionListener(this);
this.add(fileio);
fileio.addActionListener(this);
this.add(quit);
quit.addActionListener(this);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
}
public void actionPerformed(ActionEvent e){
if(e.getSource() == print){
JOptionPane.showMessageDialog (null, "System.out.println(); and System.out.print();", "Print Statements", JOptionPane.INFORMATION_MESSAGE);
}
if(e.getSource() == classes){
JOptionPane.showMessageDialog (null, "Main class : public class ClassNameTester{ // public static void main(String[] args){, Other Classes : public class ClassName", "Classes", JOptionPane.INFORMATION_MESSAGE);
}
if(e.getSource() == quit){
System.exit(0);
}
}
private void dialogSize(){
}
}
JavaWindow:
import java.awt.*;
import javax.swing.*;
public class JavaWindow extends JFrame{
private Container c;
public JavaWindow(){
super("Java Helper");
c = this.getContentPane();
}
public void addPanel(JPanel p){
c.add(p);
}
public void showFrame(){
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
I made changes to clean up the Java Helper GUI and to allow you to format the information on the JOptionPane dialogs.
Here's the Java Helper GUI.
And here's the Classes JOptionPane.
I modified your JavaHelperTester class to include a call to the SwingUtilities invokeLater method. This method puts the creation and use of your Swing components on the Event Dispatch thread (EDT). A Swing GUI must start with a call to the SwingUtilities invokeLater method.
I also formatted all of your code and resolved the imports.
package com.ggl.java.helper;
import javax.swing.SwingUtilities;
public class JavaHelperTester {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
JavaWindow display = new JavaWindow();
JavaHelper j = new JavaHelper();
display.addPanel(j);
display.showFrame();
}
};
SwingUtilities.invokeLater(runnable);
}
}
Here's your JavaWindow class.
package com.ggl.java.helper;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JavaWindow extends JFrame {
private static final long serialVersionUID = 6535974227396542181L;
private Container c;
public JavaWindow() {
super("Java Helper");
c = this.getContentPane();
}
public void addPanel(JPanel p) {
c.add(p);
}
public void showFrame() {
this.pack();
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
And here's your JavaHelper class. I made the changes to your action listener to allow you to define the text as an HTML string. You may only use HTML 3.2 commands.
I also changed your button panel to use the GridLayout. The grid layout makes your buttons look neater and makes it easier for the user to select a JButton.
package com.ggl.java.helper;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class JavaHelper extends JPanel implements ActionListener {
private static final long serialVersionUID = -3150356430465932424L;
JButton print = new JButton("Print Statements");
JButton classes = new JButton("Classes");
JButton varibles = new JButton("Assiging variables");
JButton signs = new JButton("Sign meanings");
JButton typesv = new JButton("Different Types of variables");
JButton scanners = new JButton("Scanner");
JButton loops = new JButton("Loops");
JButton ifstatements = new JButton("If statements");
JButton graphics = new JButton("Graphics");
JButton objects = new JButton("Making an oject");
JButton importstatments = new JButton("Import Statements");
JButton integers = new JButton("Different types of integers");
JButton methods = new JButton("Scanner methods");
JButton math = new JButton("Math in java");
JButton creation = new JButton("Method creation");
JButton arrays = new JButton("Arrays");
JButton jframe = new JButton("JFrame");
JButton stringtokenizer = new JButton("String Tokenizer");
JButton extending = new JButton("Class extending");
JButton fileio = new JButton("File I.O.");
JButton quit = new JButton("Quit");
public JavaHelper() {
this.setLayout(new GridLayout(0, 2));
setBackground(Color.gray);
this.add(print);
print.addActionListener(this);
this.add(classes);
classes.addActionListener(this);
this.add(varibles);
varibles.addActionListener(this);
this.add(signs);
signs.addActionListener(this);
this.add(typesv);
typesv.addActionListener(this);
this.add(scanners);
scanners.addActionListener(this);
this.add(loops);
loops.addActionListener(this);
this.add(ifstatements);
ifstatements.addActionListener(this);
this.add(graphics);
graphics.addActionListener(this);
this.add(objects);
objects.addActionListener(this);
this.add(importstatments);
importstatments.addActionListener(this);
this.add(integers);
integers.addActionListener(this);
this.add(methods);
methods.addActionListener(this);
this.add(math);
math.addActionListener(this);
this.add(creation);
creation.addActionListener(this);
this.add(arrays);
arrays.addActionListener(this);
this.add(jframe);
jframe.addActionListener(this);
this.add(stringtokenizer);
stringtokenizer.addActionListener(this);
this.add(fileio);
fileio.addActionListener(this);
this.add(quit);
quit.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == print) {
String title = ((JButton) e.getSource()).getText();
JLabel label = new JLabel(createPrintText());
JOptionPane.showMessageDialog(this, label, title,
JOptionPane.INFORMATION_MESSAGE);
}
if (e.getSource() == classes) {
String title = ((JButton) e.getSource()).getText();
JLabel label = new JLabel(createClassesText());
JOptionPane.showMessageDialog(this, label, title,
JOptionPane.INFORMATION_MESSAGE);
}
if (e.getSource() == quit) {
System.exit(0);
}
}
private String createPrintText() {
StringBuilder builder = new StringBuilder();
builder.append("<html><pre><code>");
builder.append("System.out.print()");
builder.append("<br>");
builder.append("System.out.println()");
builder.append("</code></pre>");
return builder.toString();
}
private String createClassesText() {
StringBuilder builder = new StringBuilder();
builder.append("<html><pre><code>");
builder.append("Main class : public class ClassNameTester { <br>");
builder.append(" public static void main(String[] args) { <br>");
builder.append(" } <br>");
builder.append("} <br><br>");
builder.append("Other Classes : public class ClassName { <br>");
builder.append("}");
builder.append("</code></pre>");
return builder.toString();
}
}
I am trying to display a JPanel in a JFrame. The Jrame works but I can't get the JPanel to display.
My whole class spent an hour on this today. Teacher included. Not luck. Eclipse says there are no errors Can someone please alert me to my mistake?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
// make a JFrame and bits
public class MySystemGUI extends JFrame implements ActionListener
{
private static final long serialVersionUID = 1L;
private JFrame myFrame;
private JTextField LLName, LLAddress, LLPhone, LLbankDeets;
private JButton sub1;
private JLabel LLNameT, LLAddressT, LLPhoneT, LLbankDeetsT;
private JPanel LLJP()
{
JPanel JP1 = new JPanel();
LLNameT = new JLabel ("Enter Landlord name");
LLName = new JTextField(30);
LLAddressT = new JLabel ("Enter Landlord Address ");
LLAddress = new JTextField(40);
LLPhoneT = new JLabel ("Enter Landlod Phone No.");
LLPhone = new JTextField(10);
LLbankDeetsT = new JLabel ("Enter Landlod Bank details");
LLbankDeets = new JTextField(10);
sub1 = new JButton("Submit");
JP1.add(LLNameT);
JP1.add(LLName);
JP1.add(LLAddressT);
JP1.add(LLAddress);
JP1.add(LLPhoneT);
JP1.add(LLPhone);
JP1.add(LLbankDeetsT );
JP1.add(LLbankDeets);
JP1.add(sub1);
//myFrame.add(JP1 );
return JP1;
}
// Set up frame
public MySystemGUI()
{
myFrame = new JFrame ();
JPanel myPanel = LLJP();
myFrame.add(myPanel,"South");
this.setLayout(new GridBagLayout());
this.setSize(700, 500);
this.setTitle("My System GUI");
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBackground(Color.blue);
}
//run this bitch
public static void main (String[] args)
{
new MySystemGUI();
}
#Override
public void actionPerformed(ActionEvent e)
{
}
}
You have an JFrame member
private JFrame myFrame;
which is what you are adding the components to.
myFrame.add(myPanel,"South");
But you setVisible to class frame
public class MySystemGUI extends JFrame
...
this.setVisible(true); // `this` is class frame, not `myFrame`
Take out all the this.setXxx and do myFrame.setXxx, and take out the extends JFrame
public class MySystemGUI implements ActionListener {
...
public MySystemGUI() {
...
myFrame.setLayout(new GridBagLayout());
myFrame.setSize(700, 500);
myFrame.setTitle("My System GUI");
myFrame.setVisible(true);
...
}
}
Other Notes
myFrame.add(myPanel,"South"); - "South" doesn't matter, only for BorderLayout. You set the layout to GridBaglayout.
this.setBackground(Color.blue); Wouldn't you want o set the background after the frame is visible?
Swing Programs should be run/started on the Event Dispatch Thread. See Initial Threads. Basically, you can wrap the instantiation in a SwingUtilities.invokeLater
public static void main (String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new MySystemGUI();
}
});
}
UPDATE
You're also going to want to make use of different layout managers for the panel holding the labels and field. With a FlowLayout (the default of JPanel), eveerytyhing is added consecutively in a row. Take some time to learn the layout managers at Laying out Components Withing a Container
Here is a simple fix using a GridLayout
import java.awt.Color;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
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.JTextField;
import javax.swing.SwingUtilities;
public class MySystemGUI implements ActionListener {
private static final long serialVersionUID = 1L;
private JFrame myFrame;
private JTextField LLName, LLAddress, LLPhone, LLbankDeets;
private JButton sub1;
private JLabel LLNameT, LLAddressT, LLPhoneT, LLbankDeetsT;
private JPanel LLJP() {
JPanel JP1 = new JPanel(new GridLayout(0, 2));
LLNameT = new JLabel("Enter Landlord name");
LLName = new JTextField(30);
LLAddressT = new JLabel("Enter Landlord Address ");
LLAddress = new JTextField(40);
LLPhoneT = new JLabel("Enter Landlod Phone No.");
LLPhone = new JTextField(10);
LLbankDeetsT = new JLabel("Enter Landlod Bank details");
LLbankDeets = new JTextField(10);
sub1 = new JButton("Submit");
JP1.add(LLNameT);
JP1.add(LLName);
JP1.add(LLAddressT);
JP1.add(LLAddress);
JP1.add(LLPhoneT);
JP1.add(LLPhone);
JP1.add(LLbankDeetsT);
JP1.add(LLbankDeets);
JP1.add(sub1);
return JP1;
}
public MySystemGUI() {
myFrame = new JFrame();
JPanel myPanel = LLJP();
myFrame.add(myPanel);
myFrame.setTitle("My System GUI");
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setBackground(Color.blue);
myFrame.pack();
myFrame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MySystemGUI();
}
});
}
#Override
public void actionPerformed(ActionEvent e){}
}
You have a local frame hidding your class which is actually a JFrame:
public class MySystemGUI extends JFrame implements ActionListener { // class signature
...
public MySystemGUI() {
...
myFrame = new JFrame (); // local variable
...
myFrame.add(myPanel,"South");
...
}
...
}
Your panel is added to this local frame instead to your class so it won't be visible. You can either get rid of this local variable and add panel using this.add(...) or avoid extending JFrame and use local variables instead. This last apporach is preferred:
Why shouldn't you extend JFrame and other components?
Extends JFrame vs. creating it inside the the program
My whole class spent an hour on this today. Teacher included. Not
luck.
Just find another teacher.