Getting Labels a name with a label - java

This panel class is suppose to print out "Course Info" Yet when I do try to print it out on the GUI, the gui frame shows up but not the Panel. So I feel the panel code is the problem, how to get the "Course Info" to appear? And if the label is working correctly, why when I post the label to the gui, it just shows another blank Frame?
Panel:
import javax.swing.*;
import java.awt.*;
public class TopPanel extends JPanel {
public TopPanel(){
JPanel panel = new JPanel();
JLabel Crse = new JLabel("Course Info");
Crse.setFont(new Font("Serif", Font.PLAIN, 14));
panel.add(Crse);
}
}
GUI code:
import javax.swing.*;
import java.awt.*;
public class CourseGUI extends JFrame {
public CourseGUI()
{
super("CourseGUI Frame");
JPanel topPanel = new JPanel();
topPanel.setBackground(java.awt.Color.WHITE);
Dimension d = new Dimension(800,600);
topPanel.setPreferredSize(d);
this.setLayout(new BorderLayout());
this.add(topPanel, BorderLayout.NORTH);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(800,600);
//JPanel tp = new TopPanel();
//this.add(tp.BorderLayout.North);
JPanel panel = new TopPanel();
this.add(panel, BorderLayout.SOUTH);
this.setVisible(true);
}
public static void main(String[] args)
{
new CourseGUI();
}
}

Try like this
public TopPanel(){
JLabel Crse = new JLabel("Course Info");
Crse.setFont(new Font("Serif", Font.PLAIN, 14));
add(Crse);
}
You are creating new JPanel which will not going to get added in JFrame.
As you are doing this.
this.add(topPanel, BorderLayout.NORTH);
for JFrame but topPanel don't have anything to display because you didn't add anything.

Related

Is there an option to add ScrollPane without disabling CardLayout?

I have a card layout where I switch panels with a button. However, the code (switching panels) works only when lines:
JScrollPane scrPane = new JScrollPane(card1);
frame.add(scrPane);
are removed. In other case, clicking button achieves nothing. Is there an option to keep the scrolling (I need this, since the main application will have a lot of wrapped text) without disabling an option to switch cards?
package com.code;
import javax.swing.*;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.awt.event.*;
public class Card {
public static void main(String[] args) {
JFrame frame = new JFrame("App");
frame.setVisible(true);
frame.setSize(1200, 800);//Give it a size
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel mainPanel = new JPanel(new CardLayout());
frame.add(mainPanel);
JPanel menu = new JPanel(new FlowLayout(FlowLayout.LEFT));
JPanel card1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
JPanel card2 = new JPanel(new FlowLayout(FlowLayout.LEFT));
mainPanel.add(menu, "menu");
mainPanel.add(card1, "card1");
mainPanel.add(card2, "card2");
JLabel l1 = new JLabel("label 1");
JLabel l2 = new JLabel("label 2");
card1.add(l1);
card2.add(l2);
JButton click = new JButton("Click!");
menu.add(click);
JScrollPane scrPane = new JScrollPane(card1);
frame.add(scrPane);
click.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cardLayout = (CardLayout) mainPanel.getLayout();
cardLayout.show(mainPanel, "card1");
}
});
}
}
A JFrame (its content pane) uses BorderLayout by default. That means you can have only 1 component at BorderLayout.CENTER. When you frame.add(component) the default constraints is BorderLayout.CENTER.
Now, you frame.add(mainPanel); and then frame.add(scrPane);. So main panel is removed, since scrPane is being added after it.
Doing JScrollPane scrPane = new JScrollPane(card1); it means you add a scrollpane to card1, and not in content pane. I guess that you want it to the content pane (the whole frame). So the fix is to delete frame.add(mainPanel); and do the following:
JScrollPane scrPane = new JScrollPane(mainPanel);
frame.add(scrPane);
Now, the main panel is added to scrPane and scrPane is added to the frame.
However, your GUI will be empty after that, because you frame.setVisible(true); before you are finished adding components to it. Take a look at Why shouldn't I call setVisible(true) before adding components?
Eventually, full code is:
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("App");
frame.setSize(1200, 800);//Give it a size
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel mainPanel = new JPanel(new CardLayout());
JPanel menu = new JPanel(new FlowLayout(FlowLayout.LEFT));
JPanel card1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
JPanel card2 = new JPanel(new FlowLayout(FlowLayout.LEFT));
mainPanel.add(menu, "menu");
mainPanel.add(card1, "card1");
mainPanel.add(card2, "card2");
JLabel l1 = new JLabel("label 1");
JLabel l2 = new JLabel("label 2");
card1.add(l1);
card2.add(l2);
JButton click = new JButton("Click!");
menu.add(click);
JScrollPane scrPane = new JScrollPane(mainPanel);
frame.add(scrPane);
click.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout cardLayout = (CardLayout) mainPanel.getLayout();
cardLayout.show(mainPanel, "card1");
}
});
frame.setVisible(true);
});
}
Some good links I suggest you to read are the Initial Threads and What does .pack() do?

How to pass JTextfield info from a JDialog into a JFrame (separate classes)

I have been trying to pass the info of my JTextField that is in a JDialog into my JFrame. Both the JDialog and JFrame are in separate classes. I have tried to store the JTextField into a JLable using the .setText and .getText and then passing the JLable into the JFrame but with no luck.
I know there are many similar questions but I have tried many different approaches but still no luck. I am relatively new to Java and do not know all the in's and out's. Any help is very appreciated!
My code for the JFrame:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JPanel;
public class StockApp extends JFrame implements PropertyChangeListener {
private JPanel main = new JPanel();
private JPanel north = new JPanel();
private JPanel center = new JPanel();
private JPanel south = new JPanel();
private JButton buyStock = new JButton("Buy Stock");
private JButton sellStock = new JButton("Sell Stock");
public TestTest variables = new TestTest();
private JLabel stockNameNorth = new JLabel("Stock Name");
private JLabel stockPriceNorth = new JLabel("Stock Price");
String stockName = variables.getStockName();
String stockPrice = variables.getStockPrice();
public StockApp() {
setTitle("StockApp");
getContentPane().setBackground(Color.white);
setSize(400,400);
setLocation(500,200);
setVisible(true);
main.setLayout(new BorderLayout());
north.setLayout(new FlowLayout());
center.setLayout(new FlowLayout());
south.setLayout(new FlowLayout());
stockNameNorth.setText(stockName);
stockPriceNorth.setText(stockPrice);
add(main);
north.add(stockNameNorth);
north.add(stockPriceNorth);
south.add(buyStock);
south.add(sellStock);
main.add(north, BorderLayout.NORTH);
main.add(center, BorderLayout.CENTER);
main.add(south, BorderLayout.SOUTH);
}
}
And Dialog:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TestTest extends JDialog implements ActionListener {
private JPanel main = new JPanel();
private JPanel north = new JPanel();
private JPanel center = new JPanel();
private JPanel south = new JPanel();
private JLabel stockNameLabel = new JLabel("Stock name: ");
private JLabel stockPriceLabel = new JLabel("Stock price(£): ");
private JTextField stockNameIn = new JTextField(5);
private JTextField stockPriceIn = new JTextField(5);
private JButton buttonOK = new JButton("OK");
public JLabel stockPrice = new JLabel();
public JLabel stockName = new JLabel();
public TestTest() {
getContentPane().setBackground(Color.white);
setSize(400,400);
setLocation(500,200);
setModal(false);
setVisible(true);
getRootPane().setDefaultButton(buttonOK);
main.setLayout(new BorderLayout());
north.setLayout(new FlowLayout());
center.setLayout(new FlowLayout());
south.setLayout(new FlowLayout());
add(main);
north.add(stockNameLabel);
north.add(stockNameIn);
center.add(stockPriceLabel);
center.add(stockPriceIn);
south.add(buttonOK);
main.add(north, BorderLayout.NORTH);
main.add(center, BorderLayout.CENTER);
main.add(south, BorderLayout.SOUTH);
buttonOK.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == buttonOK){
stockName.setText(stockNameIn.getText());
stockPrice.setText(stockPriceIn.getText());
dispose();
new StockApp();
}
}
public String getStockName() {
return stockNameIn.getText();
}
public String getStockPrice() {
return stockPriceIn.getText();
}
}
I am trying to pass the stockName and stockPrice variables from the JDialog into the JFrame. I then want the name and price to display at the top of the JFrame.
For demonstration, what the problem is, we need less Fields and Buttons.
So far, no component of StockApp needs to be accessed from different methods, so there is no need to make them visible outside of the ctor.
More explanations in the code.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
public class StockApp extends JFrame {
public StockApp() {
// move those unreferenced panels here, so we don't have to reason about them:
JPanel main = new JPanel();
JPanel north = new JPanel();
JPanel center = new JPanel();
JPanel south = new JPanel();
// add price later, when name works
JButton buyStock = new JButton("Buy Stock");
JLabel stockNameNorth = new JLabel("Stock Name");
// critical change: Make the label, which you like to update,
// accessible by whom it should be updated:
TestTest variables = new TestTest (stockNameNorth);
setTitle ("StockApp");
getContentPane().setBackground(Color.white);
setSize (600,400);
setLocation (500,200);
setVisible (true);
// make the close-frame action terminate the program:
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
main.setLayout (new BorderLayout());
north.setLayout (new FlowLayout());
center.setLayout (new FlowLayout());
south.setLayout (new FlowLayout());
add (main);
north.add (stockNameNorth);
south.add (buyStock);
main.add (north, BorderLayout.NORTH);
main.add (center, BorderLayout.CENTER);
main.add (south, BorderLayout.SOUTH);
}
// Main method to start the damn thing
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new StockApp ();
}
});
}
}
// no need to make this class public in a short test:
class TestTest extends JDialog implements ActionListener {
// this are elements, visible outside the construction phase,
// we need to have access to from more than one method.
// Make this important distinction visible to the reader:
JLabel name;
JTextField stockNameIn = new JTextField (5);
JButton buttonOK = new JButton ("OK");
// add the JLabel to update to the ctor, so that it can't be forgotten
// to be set
public TestTest (JLabel pname) {
// we copy the reference to the label, to have access to it in
// the actionPerformed method.
name = pname;
JPanel main = new JPanel();
JPanel north = new JPanel();
JPanel center = new JPanel();
JPanel south = new JPanel();
JLabel stockNameLabel = new JLabel ("Stock name: ");
getContentPane().setBackground(Color.white);
// different size/location than frame, so that they don't hide
// each other completly
setSize (400,600);
setLocation (700,300);
setModal (false);
setVisible (true);
getRootPane().setDefaultButton(buttonOK);
main.setLayout (new BorderLayout());
north.setLayout (new FlowLayout());
center.setLayout (new FlowLayout());
south.setLayout (new FlowLayout());
add (main);
north.add (stockNameLabel);
north.add (stockNameIn);
south.add (buttonOK);
main.add (north, BorderLayout.NORTH);
main.add (center, BorderLayout.CENTER);
main.add (south, BorderLayout.SOUTH);
buttonOK.addActionListener(this);
}
// here we need access to the button - was it the OK-Button, clicked?
// and the textfield stockNameIn, to read the text
// and the name field from the frame, to set the text
public void actionPerformed(ActionEvent e) {
if (e.getSource () == buttonOK) {
name.setText (stockNameIn.getText());
dispose();
}
}
}

Java Button Placement using BorderLayout

This code displays nothing, I have exhausted many avenues but it does not display anything on the GUI (I have a main class that calls this as well already). Please help. I am trying to put the two JButtons horizontally at the bottom of the page and the JTextField and JLabel at the center of the screen.
package test;
import javax.swing.*;
import java.awt.*;
public class Gui extends JFrame {
private JLabel label;
private JButton clear;
private JButton copy;
private JTextField textfield;
public Gui(){
super("test");
clear = new JButton("Clear");
copy = new JButton("Copy");
label = new JLabel("");
textfield = new JTextField("enter text here");
JPanel bottom = new JPanel(new BorderLayout());
JPanel subBottom = new JPanel();
subBottom.add(copy);
subBottom.add(clear);
JPanel centre = new JPanel (new BorderLayout());
JPanel subCentre = new JPanel();
subCentre.add(label);
subCentre.add(textfield);
bottom.add(subBottom, BorderLayout.PAGE_END);
centre.add(subCentre, BorderLayout.CENTER);
}
}
Your code is a bit over-complicated. You only need two panels, centre, and buttons. There are two reasons your UI is not showing up:
You never added the panels to the frame
You never set visible to true(Achieve this by using setVisible(true)), unless you did this in the class you ran it in.
One simple way to achieve your desired UI is like so(I added a main method to show the window):
import javax.swing.*;
import java.awt.*;
public class test extends JFrame {
public Test() {
super("test");
JPanel buttons = new JPanel();
JPanel centre = new JPanel();
add(buttons, BorderLayout.SOUTH); //these lines add the
add(centre, BorderLayout.CENTER); //panels to the frame
JButton clear = new JButton("Clear"); // No need
JButton copy = new JButton("Copy"); // to declare
JLabel label = new JLabel("Label"); // these
JTextField textfield = new JTextField("enter text here"); // privately
buttons.add(copy);
buttons.add(clear);
centre.add(label);
centre.add(textfield);
pack();
setLocationRelativeTo(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
} //end constructor
//added main method to run the UI
public static void main(String[] args) {
new Experiments();
} //end main
} //end class
And it shows the window:
I got closer but its not pretty code, the JFrame is 500x500 so this works based on that... any better suggestions than what I have?
package lab6;
import javax.swing.*;
import java.awt.*;
public class Gui extends JFrame {
private JLabel label;
private JButton clear;
private JButton copy;
private JTextField textfield;
public Gui(){
super("test");
clear = new JButton("Clear");
copy = new JButton("Copy");
label = new JLabel("label");
textfield = new JTextField("enter text here");
JPanel masterPanel = new JPanel(new BorderLayout());
JPanel top = new JPanel();
top.setPreferredSize(new Dimension(100, 200));
JPanel bottom = new JPanel();
JPanel subBottom = new JPanel();
subBottom.add(copy);
subBottom.add(clear);
JPanel centre = new JPanel ();
JPanel subCentre = new JPanel();
subCentre.add(label);
subCentre.add(textfield);
bottom.add(subBottom);
centre.add(subCentre);
masterPanel.add(bottom, BorderLayout.PAGE_END);
masterPanel.add(top, BorderLayout.PAGE_START);
masterPanel.add(centre, BorderLayout.CENTER);
add(masterPanel);
}
}

Can't position Buttons or JLabels

I am new to working with GUI's in Java and I am having a problem moving my text and buttons around. No matter what coordinates I give my button or any of the other JLabel it doesn't move, I was wondering how I could fix it this in such a way that I can place my components where ever I want on the JPanel
public class IntroPage extends JFrame {
public static void main(String[] args) {
IntroPage main = new IntroPage();
main.setVisible(true);
}
private JPanel contentPane;
public IntroPage (){
//make sure the program exits when the frame closes
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Welcome");
contentPane = new JPanel();
setSize(400,700);
//This will center the JFrame in the middle of the screen
setLocationRelativeTo(null);
//Welcome Page stuff :D
JLabel ApplauseLabel = new JLabel("Welcome to U.X.Dot.X");
ApplauseLabel.setFont(new Font("Gill Sans MT", Font.PLAIN, 30));
ApplauseLabel.setLocation(100, 50);
contentPane.add(ApplauseLabel);
JLabel slogan = new JLabel("Register below");
slogan.setFont(new Font("Gill Sans MT", Font.PLAIN, 15));
slogan.setLocation(100, 400);
contentPane.add(slogan);
//FacebookSignUp.
JButton FBbutton = new JButton("Login With FaceBook");
FBbutton.setBackground(Color.BLUE);
FBbutton.setSize(50,50);
FBbutton.setLocation(20, 40);
FBbutton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Add JPanel to go to FB API. Much later
}
});
contentPane.add(FBbutton);
add(contentPane);
//make sure the JFrame is visible
setVisible(true);
}
}
You're ignoring the layout managers of your contentPane JPanel. Understand that it uses FlowLayout by default, and will ignore your setLocation and setBounds statements. Ror the JPanel to accept absolute positioning, you would have to give it a null layout via contentPane.setLayout(null).
Having said that, I do not advise you to do this! While null layouts, setLocation(...) and setBounds(...) might seem to Swing newbies like the easiest and best way to create complex GUI's, the more Swing GUI'S you create the more serious difficulties you will run into when using them. They won't resize your components when the GUI resizes, they are a royal witch to enhance or maintain, they fail completely when placed in scrollpanes, they look gawd-awful when viewed on all platforms or screen resolutions that are different from the original one.
For example the following GUI
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import javax.swing.*;
public class IntroPage2 extends JPanel {
public static final String TITLE = "Welcome to U.X.Dot.X";
private JLabel welcomeLabel = new JLabel(TITLE, SwingConstants.CENTER);
private JButton fbButton = new JButton("Login With Facebook");
public IntroPage2() {
fbButton.setBackground(Color.BLUE);
fbButton.setForeground(Color.CYAN);
welcomeLabel.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 30));
int wlGap = 20;
welcomeLabel.setBorder(BorderFactory.createEmptyBorder(wlGap, wlGap, wlGap, wlGap));
JLabel registerBelowLabel = new JLabel("Register Below");
registerBelowLabel.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15));
JPanel centralPanel = new JPanel(new GridBagLayout());
centralPanel.setPreferredSize(new Dimension(300, 600));
centralPanel.add(registerBelowLabel);
JPanel topPanel = new JPanel(new BorderLayout());
topPanel.add(fbButton, BorderLayout.LINE_START);
topPanel.add(welcomeLabel, BorderLayout.CENTER);
setLayout(new BorderLayout());
int ebGap = 8;
setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
add(topPanel, BorderLayout.PAGE_START);
add(centralPanel, BorderLayout.CENTER);
}
private static void createAndShowGui() {
IntroPage2 mainPanel = new IntroPage2();
JFrame frame = new JFrame("Welcome");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}
would create something like:

PictureCount does not change

the code is used to create an application which shows picture and if your anwser is correct your supposed to see the next picture but the pictureCount does not go up. all of the variables ar declared after the main class and i created an Actionlistener to check if the awnser is correct.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main {
public static void main(String[] args) {new Main().test();}
public int pictureCount = 1;
JFrame frame = new JFrame();
JButton button1 = new JButton("Submit");
JTextField text = new JTextField();
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JLabel label = new JLabel(new ImageIcon("C:\\Users\\Admin\\Desktop\\practicum 3\\" + pictureCount + ".jpg"));
void test(){
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
if(text.getText().equals("5")){
pictureCount++;
new Main().test();
}
}
});
panel1.add(button1);
panel2.add(text);
panel3.add(label);
text.setPreferredSize(new Dimension(100,50));
panel1.setPreferredSize(new Dimension(1000, 200));
panel2.setPreferredSize(new Dimension(1000, 100));
panel3.setPreferredSize(new Dimension(1000, 450));
frame.getContentPane().add(BorderLayout.SOUTH, panel1);
frame.getContentPane().add(BorderLayout.CENTER, panel2);
frame.getContentPane().add(BorderLayout.NORTH, panel3);
frame.setSize(1000,750);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Operation Screen");
frame.setLocationRelativeTo(null);
}
}
You need to read in all the pictures as ImageIcons into an array or ArrayList, say called imageIconArray and then display imageIconArray[0] in your JLabel when you start.
When the button is pressed, increment pictureCount, and then reset the JLabel's icon via its setIcon(...) method:
// in the ActionListener code:
pictureCount++;
label.setIcon(imageIconArray[pictureCount];
Whatever you do, don't create a new Main object, despite what others might say. Why create a new GUI when all you need to do is swap displayed images?

Categories