Im rather new at Java, I am have created a home page and a few buttons, When i click one of the buttons it sets the homepage panel visibility to false, opens a new class and sets that classes Jpanel to visible.
homePanel.setVisible(false);
Goodsin Barcode = new Goodsin();
Goodsin.setVisible(true);
However once it opens the new class "Goodsin" it wont show any of the Buttons or TextFileds. I know it is opening the new class as a System.out.println prints to the console but nothing displays in the JFrame and i do not know why.
Here is my code of the new class
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Goodsin {
public JPanel Goodsin;
public JTextField item1;
public String code;
public JButton btn1;
public Goodsin() {
System.out.println("TEST");
Goodsin = new JPanel();
item1 = new JTextField(10);
btn1 = new JButton("Look up Barcode");
Goodsin.setVisible(true);
Goodsin.add(item1);
item1.setSize(80, 30);
Goodsin.add(btn1);
btn1.setSize(80, 30);
}
public void getString(String code) {
System.out.println(code);
}
}
Im sure i am not doing something correct with the Jpanel or adding the textfields or button but all the answers i have seen so far havnt worked.
I suggest you add your panels to a JFrame. You can either do this by extending JFrame from the class or simply instantiating one in your constructor. Then you can simply add and remove (or set visible/invisible) as you wish. Be sure to validate your JFrame/JPanel after changing visibility though.
Try to do something like this:
Goodsin = new JPanel();
item1 = new JTextField(10);
btn1 = new JButton("Look up Barcode");
item1.setSize(80, 30);
Goodsin.add(item1);
btn1.setSize(80, 30);
Goodsin.add(btn1);
JFrame frame = new JFrame("JFrame Example");
Goodsin.setLayout(new FlowLayout());
frame.add(Goodsin);
I suggest you try the following code :
public class Goodsin extends JFrame{
public static void main(String[] args) {
Goodsin ui = new Goodsin();
JTextField item1 = new JTextField(10);
JButton btn1 = new JButton("Look up Barcode");
JPanel centralPanel = new JPanel(new FlowLayout());
centralPanel.add(item1);
centralPanel.add(btn1);
item1.setSize(80, 30);
btn1.setSize(80, 30);
ui.add(centralPanel);
ui.pack();
ui.setVisible(true);
}
}
Everything is done in the main method in my example, however you still can improve this code and refactor it in a better way.
just you have to set Bounds of Goodsin panel or set Size and add in home page frame
Related
i'm having trouble to get the 2nd frame to display the GUI Components. i've opened the frame using the JButton from the 1st frame.
Here's the screen shot
This is the first frame - ClientModule.java
2nd frame - ClientMenu.java
Here's the codes i've tried
ClientModule.java
import java.net.*;
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ClientModule extends JFrame implements Runnable{
private JPanel panel;
private JFrame frame;
private JLabel titleLbl, userLbl, passLbl, hostLbl, portLbl, ipLbl;
private JTextField userTxt, hostTxt, portTxt, ipTxt;
private JPasswordField passTxt;
private JButton loginBtn;
public static void main(String[] args)
{
new ClientModule().run();
}
public ClientModule()
{
frame = new JFrame("DMS(Drawing Message System)");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
panel = new JPanel();
panel.setPreferredSize(new Dimension(500,500));
panel.setLayout(new FlowLayout());
titleLbl = new JLabel("LogIn to Drawing Message System(DMS)");
titleLbl.setFont(new Font("Rockwell Condensed",Font.BOLD,28));
userLbl = new JLabel("Username:");
passLbl = new JLabel("Password:");
hostLbl = new JLabel("Hostname:");
portLbl = new JLabel("Port No.:");
ipLbl = new JLabel("IP Address:");
userTxt = new JTextField();
userTxt.setPreferredSize(new Dimension(100,30));
passTxt = new JPasswordField();
passTxt.setEchoChar('*');
passTxt.setPreferredSize(new Dimension(100,30));
portTxt = new JTextField();
portTxt.setPreferredSize(new Dimension(100,30));
ipTxt = new JTextField();
ipTxt.setPreferredSize(new Dimension(100,30));
hostTxt = new JTextField();
hostTxt.setPreferredSize(new Dimension(100,30));
loginBtn = new JButton("Login!");
loginBtn.setPreferredSize(new Dimension(90,30));
loginBtn.addActionListener(new LoginBtnListener());
panel.add(titleLbl);
panel.add(userLbl);
panel.add(userTxt);
panel.add(passLbl);
panel.add(passTxt);
panel.add(hostLbl);
panel.add(hostTxt);
panel.add(portLbl);
panel.add(portTxt);
panel.add(ipLbl);
panel.add(ipTxt);
panel.add(loginBtn);
frame.add(panel);
}
private class LoginBtnListener implements ActionListener
{
#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent action)
{
//thinking this frame will close after ClientMenu's frame is open
ClientModule client = new ClientModule();
client.setVisible(false);
ClientMenu menu = new ClientMenu();
menu.setVisible(true);
}
}
public void run()
{
frame.pack();
frame.setVisible(true);
}
}
ClientMenu.java
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.util.*;
public class ClientMenu extends JFrame{
JFrame frame;
JPanel panel;
JLabel titleLbl;
JButton sendBtn,receiveBtn,logoutBtn;
public ClientMenu()
{
frame = new JFrame("Drawing Message System(DMS)");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.setPreferredSize(new Dimension(500,500));
titleLbl = new JLabel("Main Menu");
titleLbl.setFont(new Font("Rockwell Condensed",Font.BOLD,28));
sendBtn = new JButton("Send a Drawing");
sendBtn.setPreferredSize(new Dimension(100,30));
receiveBtn = new JButton("Receive a Drawing");
receiveBtn.setPreferredSize(new Dimension(100,30));
logoutBtn = new JButton("Logout");
logoutBtn.setPreferredSize(new Dimension(100,30));
logoutBtn.addActionListener(new LogoutBtnListener());
panel.add(titleLbl);
panel.add(sendBtn);
panel.add(receiveBtn);
panel.add(logoutBtn);
frame.add(panel);
}
private class LogoutBtnListener implements ActionListener
{
//#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent action)
{
ClientModule client = new ClientModule();
client.setVisible(true);
ClientMenu menu = new ClientMenu();
menu.setVisible(false);
}
}
public static void main(String[] args)
{
new ClientMenu().run();
}
public void run()
{
frame.pack();
frame.setVisible(true);
}
}
I'm not sure if i'm missing something, or coded something wrong, or something else. I've already searched and tried..
any help and understanding is appreciated (:
I managed to get the second frame displayed (including its contents) by adding a call to the run() method:
ClientMenu menu = new ClientMenu();
menu.setVisible(true);
menu.run();
That being said, there are quite some problems with your code:
You have a main method in each of your classes. You should have only 1 main method per application. Since ClientModule seems to be the first Frame you want to have opened, your might want to keep the main method there and remove the one in the other class.
You have a run() method in each class. Personally, I tend to avoid naming methods like this, since it might cause confusion with the run() method which needs to be overridden when dealing with threads. You are clearly attempting to do some multi threading in your ClientModule, but will not work. Please look into this concurrency tutorial to better understand threads. You should also understand that you should never call run() yourself. The tutorial should make that clear.
Swing applications are started a little bit differently that other applications. Please refer to this tutorial for more information.
You have both your classes extend JFrame but then, provide your own. This results in other JFrames being created, which is what happened in my case (I get 2 JFrames per instantiation). If you want your class to behave like a JFrame, consider extending it, if you want to use a JFrame, then compose your class of one, not both (at least not in this case).
Lastly, to get rid of the previous JFrame you could call dispose() on the it. That being said, the approach usually is to use the Card Layout. This would allow you to have 1 frame with multiple content.
Sorry for the long post, but please consider re factoring as per the above prior to continuing.
You can use the setVisible property to 'true' or 'false'.
im trying to design java GUI frame which contains labels, textfields, radio buttons and button..
i want to position each component in specific place tried setBounds() but it didn't work..
also im trying to change background color of the frame using getContentPane().setBackground(Color.white) and setBackground(Color.white) but didnt work too.
how to do it ?
this is my code :
import javax.swing.*;
import java.awt.*;
import java.applet.*;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class test extends JFrame{
public static void main(String[] args) {
JFrame guiFrame = new JFrame();
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("WHO IS THE WINNER");
guiFrame.setSize(700,500);
guiFrame.setLocationRelativeTo(null);
final JPanel first = new JPanel();
JLabel un = new JLabel("UserName:");
JTextField textField = new JTextField(20);
JLabel sn = new JLabel("Server Name:");
JTextField textField2 = new JTextField(20);
un.setLabelFor(textField);
sn.setLabelFor(textField2);
first.add(un);
first.add(textField);
first.add(sn);
first.add(textField2);
final JPanel second = new JPanel();
JLabel level = new JLabel("Level:");
JLabel score = new JLabel("Score:");
JLabel question = new JLabel("Question:");
CheckboxGroup radioGroup = new CheckboxGroup();
Checkbox radio1 = new Checkbox("True", radioGroup,false);
Checkbox radio2 = new Checkbox("False", radioGroup,true);
second.add(score);
second.add(level);
second.add(question);
second.add(radio1);
second.add(radio2);
JButton next = new JButton( "Next");
next.addActionListener(
new ActionListener() {
#Override public void actionPerformed(ActionEvent event) {
first.setVisible(false);
} });
guiFrame.add(first, BorderLayout.NORTH);
guiFrame.add(second, BorderLayout.CENTER);
guiFrame.add(next,BorderLayout.SOUTH);
guiFrame.setVisible(true);
}
}
for the positioning for example i want the first label and text field under them the other label and text field not beside them.. same for other labels and radio buttons i don't want them it be beside each other i want o give them a specific position to be in..
can someone please help ?
Thanks :)
This answer is just for Eclipse IDE.
An easy way to place all the widgets is doing it from the Design tab, placed at the bottom-left side of the window. Just change from Source perspective to Design perspective. It will open a simple panel with everything you need. Just drag the different widgets and place them in their position.
To change the background of the frame, do it from the properties of the frame in the Design tab or add the following code to the constructor of the panel:
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
I'm trying to do a little program that use some buttons and text field.
I was able to create window with JPanel but don't have idea how to add button and text field
The code I'm using is:
public UI() {
sprites = new HashMap();
// spriteCache = stage.getSpriteCache();
JFrame okno = new JFrame ("VoLTE Script");
setBounds(0,0,SZEROKOSC,WYSOKOSC);
JPanel panel = (JPanel)okno.getContentPane();
panel.setLayout (null);
panel.add(this);
okno.setBounds(0,0,800,600);
okno.setVisible(true);
JTextField pole = new JTextField(10);
JButton przycisk = new JButton("teasda");
przycisk.setPreferredSize(new Dimension(300, 350));
przycisk.setLayout(new BorderLayout());
panel.add(przycisk);
przycisk.setVisible(true);
pole.setBounds (300,300,200,200);
pole.setLayout(null);
pole.setVisible(true);
panel.add(pole);
okno.addWindowListener(new WindowAdapter(){
public void windowClosing (WindowEvent e){
System.exit(0);
}
});
okno.setResizable(false);
createBufferStrategy(2);
strategia=getBufferStrategy();
requestFocus();
// addKeyListener(this);
// addMouseListener(this);
}
You need to use the layout properly, when using border layout you need to tell it which border to use (, BorderLayout.NORTH or something), check out the tutorials at oracles page.
P.S. Think of how your naming your fields etc. Naming something "przycisk" just gives me a reason not to read the code further.
Thank You for help and sorry for Polish names(fixed already).
I was able to add Text Area with scroll.
Looks like problem was in panel.add(this); putted before button and text field.
From my understanding if panel.add(this) is set before panel.add(pole); then panel.add(this) is set in front and pole is added but not seen.
Below my actual working code:
...
public UI() {
sprites = new HashMap();
// spriteCache = stage.getSpriteCache();
JFrame okno = new JFrame ("VoLTE Script");
setBounds(0,0,WIDTH,HEIGHT);
JPanel panel = (JPanel)okno.getContentPane();
panel.setLayout (null);
okno.setBounds(0,0,800,600);
okno.setVisible(true);
JTextArea pole = new JTextArea();
pole.setLayout(null);
pole.setLineWrap(true);
//pole.setBackground(Color.BLACK);
pole.setEditable(false);
JScrollPane scroll = new JScrollPane(pole);
scroll.setBounds(25,250,500,300);
scroll.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
panel.add(scroll);
panel.add(this);
okno.addWindowListener(new WindowAdapter(){
public void windowClosing (WindowEvent e){
System.exit(0);
}
});
okno.setResizable(false);
createBufferStrategy(2);
strategia=getBufferStrategy();
requestFocus();
// addKeyListener(this);
addMouseListener(this);
}
...
This code is from this site: Example of Java GUI
//Imports are listed in full to show what's being used
//could just import javax.swing.* and java.awt.* etc..
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class GuiApp1 {
//Note: Typically the main method will be in a
//separate class. As this is a simple one class
//example it's all in the one class.
public static void main(String[] args) {
new GuiApp1();
}
public GuiApp1()
{
JFrame guiFrame = new JFrame();
//make sure the program exits when the frame closes
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("Example GUI");
guiFrame.setSize(300,250);
//This will center the JFrame in the middle of the screen
guiFrame.setLocationRelativeTo(null);
//Options for the JComboBox
String[] fruitOptions = {"Apple", "Apricot", "Banana"
,"Cherry", "Date", "Kiwi", "Orange", "Pear", "Strawberry"};
//Options for the JList
String[] vegOptions = {"Asparagus", "Beans", "Broccoli", "Cabbage"
, "Carrot", "Celery", "Cucumber", "Leek", "Mushroom"
, "Pepper", "Radish", "Shallot", "Spinach", "Swede"
, "Turnip"};
//The first JPanel contains a JLabel and JCombobox
final JPanel comboPanel = new JPanel();
JLabel comboLbl = new JLabel("Fruits:");
JComboBox fruits = new JComboBox(fruitOptions);
comboPanel.add(comboLbl);
comboPanel.add(fruits);
//Create the second JPanel. Add a JLabel and JList and
//make use the JPanel is not visible.
final JPanel listPanel = new JPanel();
listPanel.setVisible(false);
JLabel listLbl = new JLabel("Vegetables:");
JList vegs = new JList(vegOptions);
vegs.setLayoutOrientation(JList.HORIZONTAL_WRAP);
listPanel.add(listLbl);
listPanel.add(vegs);
JButton vegFruitBut = new JButton( "Fruit or Veg");
//The ActionListener class is used to handle the
//event that happens when the user clicks the button.
//As there is not a lot that needs to happen we can
//define an anonymous inner class to make the code simpler.
vegFruitBut.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent event)
{
//When the fruit of veg button is pressed
//the setVisible value of the listPanel and
//comboPanel is switched from true to
//value or vice versa.
listPanel.setVisible(!listPanel.isVisible());
comboPanel.setVisible(!comboPanel.isVisible());
}
});
//The JFrame uses the BorderLayout layout manager.
//Put the two JPanels and JButton in different areas.
guiFrame.add(comboPanel, BorderLayout.NORTH);
guiFrame.add(listPanel, BorderLayout.CENTER);
guiFrame.add(vegFruitBut,BorderLayout.SOUTH);
//make sure the JFrame is visible
guiFrame.setVisible(true);
}
}
For the future i will recommend you to use the extends JFrame so you can only write a gui like this without initialize a JFrame:
public class CalculatorGUI extends JFrame {
public CalculatorGUI() {
setTitle("Calculator");
setBounds(300, 300, 220, 200);
}}
I suggest you check out a couple of tutorials about how to create a Java Gui or sth.
Ok guys, here comes the humility. It's been a long time since I used Java Swing so I know there is some really obvious solution to this problem. What I'm trying to do is get all of these various swing elements to appear in a window. When I run the code, nothing happens. I don't see anything at all. Every time I google the answer I get stuff about various complicated JPanel problems and I'm almost positive this isn't a difficult issue. So here's my code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
public class LimoSysDriver extends JFrame implements ActionListener {
/**
* #param args
*/
JLabel title = new JLabel("Thread Test Application");
JLabel numOne = new JLabel("1");
JLabel numTwo = new JLabel("2");
JLabel numThr = new JLabel("3");
JLabel numFou = new JLabel("4");
JProgressBar progOne = new JProgressBar();
JProgressBar progTwo = new JProgressBar();
JProgressBar progThr = new JProgressBar();
JProgressBar progFou = new JProgressBar();
JLabel counterOne = new JLabel(Integer.toString(progOne.getValue()));
JLabel counterTwo = new JLabel(Integer.toString(progTwo.getValue()));
JLabel counterThr = new JLabel(Integer.toString(progThr.getValue()));
JLabel counterFou = new JLabel(Integer.toString(progFou.getValue()));
JLabel numGrandTot = new JLabel("Grand Total");
JLabel counterTot = new JLabel();
JButton start = new JButton();
JButton pause = new JButton();
JButton resume = new JButton();
public LimoSysDriver(){
setSize(700,300);
JPanel pane = new JPanel();
pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS));
add(pane);
JPanel lowerPanel = new JPanel();
lowerPanel.setLayout(new BoxLayout(lowerPanel, BoxLayout.LINE_AXIS));
add(lowerPanel);
pane.add(title);
pane.add(numOne);
pane.add(progOne);
pane.add(counterOne);
pane.add(numTwo);
pane.add(progTwo);
pane.add(counterTwo);
pane.add(numThr);
pane.add(progThr);
pane.add(counterThr);
pane.add(numFou);
pane.add(progFou);
pane.add(counterFou);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
LimoSysDriver window = new LimoSysDriver();
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
The problem is, the window doesn't show up at all. Once I can get that sorted out, I'll be able to troubleshoot the rest of it. Thanks in advance everybody.
Some tips:
Need to make visible your JFrame calling setVisible(true)
Instead of add(pane) you can use setContentPane(pane) replacing the default container used as content pane.
Don't forget to call pack() method when you finish adding components and before making your JFrame visible..
Create your GUI objects in the Event Dispatch Thread using SwingUtilities.invokeLater()
Avoid extend from JFrame unless you need to add some functionality. If that's not the case, use a JFrame variable or class member instead.
You need to set it to visible. Use:
setVisible(true)
Hi this is a bit of a basic question. In my code I create a gui in a constructor then nest a ActionListener class to handle button changes. This code will create the gui and the action listener runs through the actionPerformed method correctly. However, I've tried multiple ways to change the panel in the gui but I feel like the way I have the program set up it is not possible for this to work. Sorry if this is a repeat but after searching for a while on S.O. I haven't found a good example that would help me with my problem.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import org.math.plot.Plot2DPanel;
import org.math.plot.plotObjects.BaseLabel;
public class GraphGui extends JFrame {
//default width and height of the GUI
private static final int WIDTH = 1200;
private static final int HEIGHT = 700;
GraphPlot gp = new GraphPlot();
Plot2DPanel plotPanel =gp.determinePlotToPlot("duration");
/**
* This is the constructor that initializes the JFrame and the layout of the GUI.
* The radio buttons are also created here and grouped accordingly.
*/
public GraphGui() {
//title of GUI
setTitle("VibeTech Graph Gui");
//First JRadioButton for date vs duration
JRadioButton durToDate = new JRadioButton("Duration vs. Date");
durToDate.addActionListener(new RadioButtonListener());
durToDate.setActionCommand("duration");
durToDate.setSelected(true);
//JRadioButton for weight vs date
JRadioButton weightToDate = new JRadioButton("Weight vs. Date");
weightToDate.addActionListener(new RadioButtonListener());
weightToDate.setActionCommand("weight");
//JRadioButton for plan type vs date
JRadioButton planToDate = new JRadioButton("Plan vs. Date");
planToDate.addActionListener(new RadioButtonListener());
planToDate.setActionCommand("level");
//button group of the buttons to display them as one group
ButtonGroup group = new ButtonGroup();
group.add(planToDate);
group.add(weightToDate);
group.add(durToDate);
//create JPanel to add objects to
JPanel jplRadio = new JPanel();
jplRadio.setLayout(new GridLayout(0, 1));
//add radio buttons
jplRadio.add(planToDate);
jplRadio.add(weightToDate);
jplRadio.add(durToDate);
Plot2DPanel dvt = new Plot2DPanel();
dvt.addLinePlot("Duration over Time", gp.getDate(), gp.getDuration());
BaseLabel title = new BaseLabel("Duration over Time", Color.RED,
0.5, 1.1);
title.setFont(new Font("Courier", Font.BOLD, 20));
dvt.addPlotable(title);
dvt.setAxisLabels("Time", "Duration");
setLayout(new BorderLayout());
add(jplRadio, BorderLayout.WEST);
add(plotPanel, BorderLayout.EAST);
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
//main method to run program
public static void main(String [ ] args)
{
//create new GUI
#SuppressWarnings("unused")
GraphGui test = new GraphGui();
}
//create a radio button listener to switch graphs on button press
class RadioButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("duration")) {
plotPanel = gp.determinePlotToPlot("duration");
} else if (e.getActionCommand().equals("weight")) {
plotPanel = gp.determinePlotToPlot("weight");
} else if (e.getActionCommand().equals("level")) {
plotPanel = gp.determinePlotToPlot("level");
}
//here is where I tried to do removes, adds, and validates but
//I have trouble getting to the frame itself to remove the JPanel
//component. I think this is a setup problem.
}
}
}
You would need to add the panel and revalidate/repaint the JFrame for it to appear:
add(plotPanel, BorderLayout.EAST);
revalidate();
repaint();
Better to use CardLayout to manage this type of functionality.
Try using CardLayout for switching between panels. Here is my solution for a similar question: https://stackoverflow.com/a/9377623/544983