So, I'm working on a project for my Java class. The objective is to create a basic GUI program that displays Hello World as a string and provides four buttons for manipulating the string. Something like this: example
I haven't even gotten to the manipulation part of the program yet as I can't seem to get my window formatted correctly no matter what I try.
I am able to get my four buttons to display, but everything I have thrown at it to get the JLabel to display Hello World above the buttons is utterly failing me.
This seems so very simple, so I'm afraid there's something obvious I'm missing. I've scoured the web for a week and found lots of info on how to do this in theory, so from what I can understand, this must be a problem with my syntax.
To date I have not found an implementation that does anything along the lines of what I am needing to do. This is driving me crazy and I'm going to go past my due date either way. I just have to have an answer! Thank you so much to anyone who can point me in the right direction!
Here is my code in its current form. I felt like I was getting close with this, but it returns an exception to the console when running. Again, all help is greatly appreciated!
import java.awt.*;
import javax.swing.*;
public class HelloWorld
{
private JButton uppercaseButton;
private JButton lowercaseButton;
private JButton phraseButton;
private JButton resetButton;
private JPanel grid;
public JPanel ButtonGrid()
{
JPanel grid = new JPanel();
grid.setLayout(new GridLayout(2, 2));
uppercaseButton = new JButton("Uppercase");
lowercaseButton = new JButton("Lowercase");
phraseButton = new JButton("New Phrase");
resetButton = new JButton("Reset");
grid.add(uppercaseButton);
grid.add(lowercaseButton);
grid.add(phraseButton);
grid.add(resetButton);
return grid;
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("THIS IS MY TITLE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lbl = new JLabel("HELLO WORLD");
lbl.setPreferredSize(new Dimension(175, 100));
frame.getContentPane().add(lbl, BorderLayout.PAGE_START);
ButtonGrid b = new ButtonGrid();
b.setVisible( true );
b.setSize( 300, 200 );
frame.getContentPane().add(b, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public static void main( String[] args ){
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
ButtonGrid b = new ButtonGrid();
ButtonGrid is not a class, it is a method of the HelloWorld class that returns an instance of a JPanel.
So you need to create an instance of the HelloWorld class so you can invoke the method:
HelloWord hw = new HelloWorld()
JPanel b = hw.ButtonGrid();
And since "buttonGrid" is a method is should NOT start with an upper case character so you need to rename the method and then use:
//ButtonGrid b = new ButtonGrid();
HelloWord hw = new HelloWorld()
JPanel b = hw.buttonGrid();
Thanks to both suggestions for pointing me in the right direction!
What ended up working was basically what redxef suggested first. Camickr then helped me further because I was thinking about my methods all wrong. By combining both of those JPanels into the first method and renaming it HelloWorld, I was able to clean up some other issues I was having as well.
I'm happy to report that as a result, the project was finished and turned in with about an hour to spare. Again, thanks so much!!
Related
I am a beginner at Java and coding. I don't know if this problem is occurring because I forgot something in the code or something is not correct in the code.
I have already tried looking through all the questions on Stack Overflow that are similar to my question and none of them helped me. I've been doing trial and error but still cannot fix it.
import javax.swing.JFrame;
import javax.swing.JLabel;
public class JLabel {
public static void main(String args[]) {
JFrame myFrame = new JFrame();
String myTitle = "Blank Frame";
JLabel label1 = new JLabel("Test");
`````
label1.setText("Test Text");
`````
myFrame.setTitle(myTitle);
myFrame.setTitle(900,600);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}
}
At 'label1.setText("Test Text");' is where the problem is. My goal for this code is to create a window that has some text in it. Hopefully, the fix is simple and not as complicated as many codes.
You need to rename your class, as that's an already existing class that you're using. Creating a LJabel object will now create an instance of your object rather than the java.swing equivalent.
You didn't add the label to the frame.
myFrame.add(label1);
You're also calling setTitle() twice when I believe you meant to call setSize().
This code works for me :
public static void main(String[] args) {
JFrame myFrame = new JFrame();
String myTitle = "Blank Frame";
JLabel label1 = new JLabel("Test");
label1.setText("Test Text");
myFrame.add(label1);
myFrame.setTitle(myTitle);
myFrame.setSize(900,600);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}
remove the ````` things and you are fine...
or are these just for the example?
This message tells you that the method setText is not define in your defined class JLabel which is not equivalent of JLabel class available in Swing packages.
Rename your own defined class JLabel to JLabelTest for example.
Also, remove this line myFrame.setTitle(900,600);, the definition of setTitle doesn't allow those parameters, and replace it with myFrame.setSize(900,600);
Your complete code should be:
import javax.swing.JFrame;
import javax.swing.JLabel;
public class JLabelTest {
public static void main(String args[]) {
JFrame myFrame = new JFrame();
String myTitle = "Blank Frame";
JLabel label1 = new JLabel("Test");
label1.setText("Test Text");
myFrame.setTitle(myTitle);
myFrame.setSize(900,600);
myFrame.getContentPane().add(label1); // to display the label
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}
}
Just an personal advise; try to read very carefully your tutorial and understand how Swing works step by step.
Hope this will help you.
I hope everyone is doing alright this fine day.
I'm learning swing and I was confused by how to reference an image. I understand that I should use a JLabel and then add that JLabel to the Frame using this.add();, but even looking at the oracle documentation here:
https://docs.oracle.com/javase/6/docs/api/javax/swing/ImageIcon.html
It is still unclear how to reference a file without giving the entire path like
C:\Users\someUser\eclipse-workspace\andSoOn.png
And I can't do that. I have to send my work to my teacher once I'm done, and the code won't reference the file like it does on my system. I tried several things, and I ended up making a new folder in the src in eclipse called ImageAssets and moving the files there, but nothing seems to work. Here is what it looks like
Here is an example of my attempt to display an image from within the package.
import java.awt.*;
import javax.swing.*;
public class Hangman extends JFrame
{
JButton playGameButton,
OptionsButton;
private ImageIcon hangman7;
private JLabel mainLabel;
public static void main(String[] args)
{
new Hangman();
}
public Hangman()
{
this.setSize(1000,800);
this.setLocationRelativeTo(null);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Hangman");
this.setResizable(false);
playGameButton = new JButton("Start Game");
OptionsButton = new JButton("Options");
//hangman7 = new ImageIcon(getClass().getResource("Images\\ hangman7.png"));//just an attempt at something
mainLabel = new JLabel();
mainLabel.setIcon(new ImageIcon("hangman7.png"));
JPanel somePanel = new JPanel();
somePanel.setLayout(new BorderLayout());
somePanel.add(playGameButton, BorderLayout.WEST);
somePanel.add(OptionsButton, BorderLayout.EAST);
somePanel.add(mainLabel, BorderLayout.CENTER);
this.add(somePanel);
this.validate();
}
Thank you so much for taking the time to help me. I tried to be very detailed; if anything is unclear please ask.
In your case, you want let the class loader find the resource, like this:
mainLabel.setIcon(
new ImageIcon(getClass().getResource("/ImageAssets/hangman7.png")));
I am trying to enter an event for JButon I create:
JButton botton1=new JButton("welcom to my show db! lets start");
botton1.setFont(new Font ("Eras Medium ITC",Font.BOLD,20));
this.add(botton1);
JPanel Basic_panel=new JPanel();
Basic_panel.setName("SHOW DB ");
Basic_panel.setBounds(x,y,width,hight);
botton1.addActionListener(this) ;
}
public void actionPerformed(ActionEvent e) {
if (e.getSource()==botton1){
Now I want to enter another JFrame I made, and make the first disappear. How?
For your original question:
How to add action to a button?
you might want to check How to write an Action Listener.
For your second question:
Now I want to enter another JFrame I made, and make the first disappear. How?
please check both approaches :)
Option 1 (Recommended)
If you want to do it the right way, you should use a CardLayout as recommended by #AndrewThompson in his comment above.
I also saw you were using a Null Layout (because of setBounds() method), you might also want to get rid of it, see Why is it frowned upon to use a null layout in Swing? and Null Layout is Evil to know why, insted you should be using a Layout Manager or combinations of them as shown in the following code based on #AndrewThompson's answer (The same that was linked in his comment above) but a bit modified to work with a JFrame instead of a JOptionPane, so give him credit by upvoting his Original Answer too!
This produces the following outputs:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class CardLayoutDemo {
JButton button1, button2;
CardLayoutDemo() {
JFrame gui = new JFrame("CardLayoutDemo");
button1 = new JButton("Go to pane 2");
button2 = new JButton("Go to pane 1");
JPanel pane1 = new JPanel();
pane1.setLayout(new BoxLayout(pane1, BoxLayout.PAGE_AXIS));
JPanel pane2 = new JPanel();
pane2.setLayout(new BoxLayout(pane2, BoxLayout.PAGE_AXIS));
final CardLayout cl = new CardLayout();
final JPanel cards = new JPanel(cl);
pane1.add(new JLabel("This is my pane 1"));
pane1.add(button1);
pane2.add(new JLabel("This is my pane 2"));
pane2.add(button2);
gui.add(cards);
cards.add(pane1, "frame1");
cards.add(pane2, "frame2");
ActionListener al = new ActionListener(){
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == button1) {
cl.show(cards, "frame2");
} else if (ae.getSource() == button2) {
cl.show(cards, "frame1");
}
}
};
button1.addActionListener(al);
button2.addActionListener(al);
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.pack();
gui.setVisible(true);
}
public static void main(String[] args) {
new CardLayoutDemo();
}
}
With this option you only have 1 JFrame but you can change through different views, and you don't annoy user with multiple windows on the task bar.
One more tip here is: If you're going to open this second JFrame to prevent user from doing something on the 1st one, you should consider using a JOptionPane or this second JFrame will contain just a bit information which you don't want to have there for the whole time (Something like a pop up).
Option 2 (Not recommended)
But if you really really really want to use multiple JFrames (which is not recommended) you can dispose() it. At the time you're calling your new JFrame to be created. For example, the following code produces this output:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TwoJFrames {
JFrame frame;
JButton button;
TwoJFrames() {
frame = new JFrame("1st frame");
button = new JButton("Click me!");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new AnotherFrame();
frame.dispose();
}
});
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String args[]) {
new TwoJFrames();
}
class AnotherFrame {
JFrame frame2;
JLabel label;
AnotherFrame() {
frame2 = new JFrame("Second Frame");
label = new JLabel("This is my second frame");
frame2.add(label);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.pack();
frame2.setVisible(true);
}
}
}
In this case you might want to consider setVisible() instead if you want to go back to previous state or reopen this one when closing the second JFrame
Both of my above codes are called a Minimal, Complete, and Verifiable example (MCVE) or Runnable Example or Short, Self Contained, Correct Example (SSCCE) which are code you can copy-paste and see the same output as me, when you have an error in your code, these examples are very handy because we can see where your errors are or be able to find them easier and/or faster.
You should consider reading all the links I provided (included these ones) and for your future questions to make something like I've done above, that way you'll prevent confusion and you'll get more, faster and better responses.
I'm very new to Java and OOP in general and I want to call my GUI class from my Main class which will be the start point for my program.
This should be pretty simple but any help will be appreciated
GUIForm1 Code:
import javax.swing.*;
import java.awt.*;
public class GUIForm1 {
private JPanel MainPanel;
private JPanel MenuPanel;
Private JPanel AnimationPanel;
private JButton greenTrail;
private JButton purpleTrail;
private JSeparator animationMenuDivider;
private JSlider rangeSlider;
//more components
public GUIForm1() {
JFrame frame = new JFrame("GUIForm1");
frame.setContentPane(new GUIForm1().MainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.pack();
frame.setVisible(true);
}
}
Main Class Code:
public class ProjectileSim {
public static void main(String[] args){
GUIForm1 gui = new GUIForm1();
}
}
Your code is good. Your main class instantiation of the GUIForm class is also correct. The reason why you are having an issue is here:
frame.setContentPane(new GUIForm1().MainPanel);
That is your issue in the code. You are trying to call the constructor of your class within your class to set a MainPanel that is non-existent.
If you are using NetBeans (Or any IDE) it is simple enough for you to just drag a JPanel onto your GUI and then you can set your frames content frame to that (for example):
frame.setContentPane(myNewJPanel);
Give it a go. Comment out the line where you are setting your contentframe and see what I mean.
(this is how you comment out by the way :
//frame.setContentPane(new GUIForm1().MainPanel);
You just insert 2 forward slashes in front of the line that you do not want to be executed.
All the best. Let me know of the outcome.
add text Jfield or JButton or change the colour of the panel you feel somthing new.
And the main method is must in java which should exist in public classs.
Your problem is very general. I would advise you to go through https://docs.oracle.com/javase/tutorial/uiswing/start/index.html at the beginning.
But, what you should do in order to get any visible result at all would be:
public GUIForm1() {
JFrame frame = new JFrame("GUIForm1");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.setVisible(true);
}
Normally you should initialize the GUI objects (like JButtons, JFrame etc.) and then add them to the Content Pane, and after that set everything to visible. But go through the tutorials, since they cover all the basics.
I'm currently doing a Java assignment as a computer science fresher. As a part of that assignment I'm trying to bring up a secondary frame that the user can write UML code into which will then be passed into my main application and then into a class diagram.
The bit that I'm stuck with is that the JTextBox that I have put into this secondary frame is the size I want it to be, however the writing starts in the middle and does not change to a new line when it gets to the other size of the frame.
This is the image of what is currently happening:
Code
And this is the code that I currently have for this class if it's needed.
package classdesign;
import java.awt.*;
import javax.swing.*;
public class ClassCreation extends JFrame {
private JFrame frame;
private JLabel instructionlabel;
private JTextField inputUML;
private JButton upButton;
private String Message;
public void ClassCreation(){
frame = new JFrame();
frame.setSize(300, 400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Class Design");
JPanel CreationPanel = new JPanel();
CreationPanel.setLayout(new BorderLayout());
instructionlabel = new JLabel("Fill Class details in using UML");
CreationPanel.add(instructionlabel,BorderLayout.NORTH);
inputUML = new JTextField("",20);
CreationPanel.add(inputUML,BorderLayout.CENTER);
frame.add(CreationPanel);
}
public Frame getFrame() {
return frame;
}
}
So, to summarise what I was hoping somebody could tell me how to do is to get the text input from the user to start in the top left and change to the next line when it gets to the far right, like any normal text editor etc...
use JTextPane or JEditorPane. Sample can be found at
http://docs.oracle.com/javase/tutorial/uiswing/components/editorpane.html
JTextField is a lightweight component that allows the editing of a single line of text. (source)
As it is a single-line component, whatever its size is the cursor will always be centered and will never go to the next line.
I would suggest you use a JTextArea as it is a multi-line area and allow the user to enter input as you want him to.
An example of using a text area (with a few other tips thrown in free - check the comments).
import java.awt.*;
import javax.swing.*;
// Has an instance of frame, does not need to extend it.
public class ClassCreation { //extends JFrame {
private JFrame frame;
private JLabel instructionlabel;
// as mentioned by talnicolas
private JTextArea inputUML;
// Don't give a method the same name as a class!!
//public void ClassCreation(){
public void initGui(){
frame = new JFrame();
//frame.setSize(300, 400); //pack() instead!
//frame.setLocationRelativeTo(null); // do something better
frame.setLocationByPlatform(true); // better!
//frame.setVisible(true); // do later
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Class Design");
JPanel CreationPanel = new JPanel();
CreationPanel.setLayout(new BorderLayout());
instructionlabel = new JLabel("Fill Class details in using UML");
CreationPanel.add(instructionlabel,BorderLayout.NORTH);
inputUML = new JTextArea("",7,30);
// very important next 2 lines
inputUML.setLineWrap(true);
inputUML.setWrapStyleWord(true);
// add it to a scrollpane
CreationPanel.add(new JScrollPane(inputUML),BorderLayout.CENTER);
frame.add(CreationPanel);
frame.pack(); // assume the natural size!
frame.setVisible(true);
for (int ii=0; ii<150; ii++) {
inputUML.append(SENTENCE);
inputUML.setCaretPosition( inputUML.getText().length() );
}
}
public static void main(String[] args) {
// Swing GUIs should be created and altered on the EDT.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ClassCreation cc = new ClassCreation();
cc.initGui();
}
});
}
private static String SENTENCE = "The quick brown fox jumps over the lazy dog! ";
}