attempting to run GUI application, but the GUI never appears - java

In trying to run my basic GUI application from Main I have somehow managed to first make the GUI show up (but it was smaller than what I set the size to within the code and not showing any components) then magically (after adding pack() and setlocationrelativeto(null)) it does not pop up at all. I am using Netbeans (if that helps), in Main it gives me a tooltip that my GUI is "never used" so it runs and outputs "Finished building" rather than continuing to run and showing the GUI. I have provided 2 sets of code (1) main method and (2) GUI class. Please let me know if I'm being confusing as of course it makes sense in my head but may be communicated badly. I have not included the complete code but if it is necessary please let me know and I will do so.
package logTime;
public class LogInTime {
public static void main(String[] args) {
try{
LogAppFrame app = new LogAppFrame(); //IDE gives tooltip that app is unused
}
catch(Exception e){
System.err.println("\n\nError Occurred: "); //am going to print message later
}
}
}
The actual GUI code - does not include imports or actionlisteners:
public void LogAppFrame(){
frame = new JFrame("Time Log Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cl = new CardLayout();
frame.getContentPane().setLayout(cl);
//frame.setLayout(cl);
frame.setSize(new Dimension(375,385));
logNewFrame = new JPanel();
logNewFrame.setLayout(new GridLayout(5,1));
logNewFrame.setBorder(new EmptyBorder(20,20,20,20));
frame.getContentPane().add(logNewFrame, "logNewFrame");
historyFrame = new JPanel();
historyFrame.setLayout(new GridLayout(2,1)); //given 0 for rows to add numerous rows
historyFrame.setBorder(new EmptyBorder(20,20,20,20));
frame.getContentPane().add(historyFrame, "historyFrame");
.
.
.
//added lots of components but will not include code as there is no error within this portion of code - i used to have both Main and LogAppFrame class all together and my GUI worked and showed components but I felt it may be best practice not to do it this way and cardlayout wasnt working
.
.
.
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Adding SSCE below:
package logTime;
import java.awt.CardLayout;
import java.awt.Dimension;
import java.awt.event.*;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class LogAppFrame{
private static JFrame frame;
private static CardLayout cl;
//menu option components
/**
* Help option: How To Use/Read Me - explains how to use it 8 Hour Day -
* shows the arrival and leave time based on lunch type
*/
/**
* Log New Date option: shows screen to input new values into date
*/
/**
* View Past Dates option: shows all past dates since forever - may add
* month tabs later
*/
/**
* Edit Past Date option: doesnt exist yet but will be added to View Past
* menu option as side button to edit any old date
*/
private static JMenuBar menuBar = new JMenuBar();
private static JMenu help;
private static JMenuItem logNewDate;
private static JMenuItem viewPastDates;
private static JMenuItem workDay;
private static JMenuItem about;
//Log New Date components
/**
* 4 labels, 1 button, 1 calendar, 2 dropdowns, 2 textfields, 5x2 gridlayout
*/
private static JLabel dateToday;
private static JLabel timeInToday;
private static JLabel timeOutToday;
private static JLabel lunchTypeToday;
private static JLabel timeColon1;
private static JLabel timeColon2;
private static JButton saveButton;
private static JComboBox month;
private static JComboBox day;
private static JComboBox year;
private static JComboBox amPm1;
private static JComboBox amPm2;
private static JComboBox hrTimeIn;
private static JComboBox hrTimeOut;
private static JComboBox minTimeIn;
private static JComboBox minTimeOut;
private static JPanel dateTodayPanel;
private static JPanel timeInPanel;
private static JPanel timeOutPanel;
private static JPanel lunchTypePanel;
private static JPanel saveButtonPanel;
private static JComboBox lunchType;
//View Past Dates components
/**
* 4x*infinitiy* gridlayout or have a flowlayout, 4 labels
*/
private static JLabel pastDates;
private static JLabel pastTimeIns;
private static JLabel pastTimeOuts;
private static JLabel pastLunchTypes;
private static JPanel headers; //holds header labels
private static JPanel oldLogs; //will hold all past log panels
//Frames to hold the logNew and viewOld views
private static JPanel logNewFrame;
private static JPanel historyFrame;
public void LogAppFrame(){
frame = new JFrame("Time Log Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cl = new CardLayout();
frame.getContentPane().setLayout(cl);
//frame.setLayout(cl);
frame.setSize(new Dimension(375,385));
logNewFrame = new JPanel();
logNewFrame.setLayout(new GridLayout(5,1));
logNewFrame.setBorder(new EmptyBorder(20,20,20,20));
frame.getContentPane().add(logNewFrame, "logNewFrame");
historyFrame = new JPanel();
historyFrame.setLayout(new GridLayout(2,1)); //given 0 for rows to add numerous rows
historyFrame.setBorder(new EmptyBorder(20,20,20,20));
frame.getContentPane().add(historyFrame, "historyFrame");
//Menu components
menuBar = new JMenuBar();
help = new JMenu("Help");
logNewDate = new JMenuItem("Log New Date");
viewPastDates = new JMenuItem("View Past Dates");
workDay = new JMenuItem("8 Hour Day");
about = new JMenuItem("How To ...");
help.add(workDay);
help.add(about);
menuBar.add(logNewDate);
menuBar.add(viewPastDates);
menuBar.add(help);
frame.setJMenuBar(menuBar);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

You have written void before the thing that ought to be a constructor. So it is mistaken as a method by the compiler which never gets called. Unfortunately the compiler generates a no-op constructor for you in such a case. Just remove the void keyword.
And by the way, remove all the nasty static keywords from the fields. That hurts.

If you want to write simple gui applications you should check WindowBuilder. It's drag and drop gui for java that actually works.

Related

JTextField disappears on some pages when being static, while appearing on others

While working on a program, I made some of my fields static i.e. a JTextField for a E-Number. But now this field behaves not as expected, on some of my pages it appears, on some others it disappears.
Since I am not very experienced working with a lot of statics, there might be a concept I am not understanding.
I have created a very simplified but working example of my program (MCVE) if you want to test it.
It shows my overview page at first - the E-Number JTextField is missing.
If you click on the search button, it shows the tracking page - with the E-Number JTextField present.
Both pages contain the same workNumberPanel and I cant find a difference, that would explain the behaviour.
So why is the E-Number JTextField present on the overview page and missing on the tracking page? Any help / explanation is appreciated!
MainProgram.java
import java.awt.CardLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import net.miginfocom.swing.MigLayout;
public class MainProgram extends JFrame {
private static final long serialVersionUID = 1L;
public static JPanel centerPanel = new JPanel();
public static CardLayout contentCardsLayout = new CardLayout();
OverviewPage overviewPage = new OverviewPage();
TrackingPage trackingPage = new TrackingPage();
public void initialize() {
createCenterPanel();
}
private void createCenterPanel() {
centerPanel.setLayout(contentCardsLayout);
overviewPage.setName("overviewPage");
trackingPage.setName("trackingPage");
centerPanel.add(overviewPage, "overviewPage");
centerPanel.add(trackingPage, "trackingPage");
add(centerPanel, "growx, wrap");
}
public MainProgram() {
setBounds(300, 50, 1200, 900);
setLayout(new MigLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
MainProgram window = new MainProgram();
window.setVisible(true);
window.initialize();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
OverviewPage.java
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
public class OverviewPage extends JPanel {
WorkNumberPanel workNumberPanel = new WorkNumberPanel();
private static final long serialVersionUID = 1L;
public OverviewPage() {
setLayout(new MigLayout());
add(workNumberPanel, "wrap, growx");
}
}
TrackingPage.java
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
public class TrackingPage extends JPanel {
private static final long serialVersionUID = 1L;
WorkNumberPanel equipmentNumberPanel = new WorkNumberPanel();
public TrackingPage(){
setLayout(new MigLayout("", "grow, fill"));
add(equipmentNumberPanel, "wrap, growx");
}
}
WorkNumberPanel.java
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;
import net.miginfocom.swing.MigLayout;
public class WorkNumberPanel extends JPanel {
private static final long serialVersionUID = 1L;
private static final Integer TEXTFIELD_LENGTH = 20;
JPanel mainWorkNumberPanel = new JPanel();
JLabel lblWorkNumber = new JLabel("E-Nr: ");
JLabel lblN_Number = new JLabel("N-Nr.: ");
JLabel lblSNumber = new JLabel("W-Nr.: ");
public static JTextField txtWorkNumber = new JTextField(TEXTFIELD_LENGTH);
JTextField txtNNumber = new JTextField(TEXTFIELD_LENGTH);
JTextField txtSNumber = new JTextField(TEXTFIELD_LENGTH);
JButton btnSearchEntry = new JButton("Search");
public WorkNumberPanel() {
createEquipmentNumberPanel();
btnSearchEntry.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
MainProgram.contentCardsLayout.show(MainProgram.centerPanel, "trackingPage");
}
});
}
private void createEquipmentNumberPanel() {
setLayout(new MigLayout());
mainWorkNumberPanel.setLayout(new MigLayout("", "[][grow, fill][][grow, fill][][grow, fill][]"));
mainWorkNumberPanel.add(lblWorkNumber);
mainWorkNumberPanel.add(txtWorkNumber);
mainWorkNumberPanel.add(lblN_Number);
mainWorkNumberPanel.add(txtNNumber);
mainWorkNumberPanel.add(lblSNumber);
mainWorkNumberPanel.add(txtSNumber);
mainWorkNumberPanel.add(btnSearchEntry);
add(mainWorkNumberPanel, "push, span, growx");
}
}
Probably because when you create your "pages" with this code
OverviewPage overviewPage = new OverviewPage();
TrackingPage trackingPage = new TrackingPage();
the TrackingPage will be the last one to execute the following line
mainWorkNumberPanel.add(txtWorkNumber);
in private void createEquipmentNumberPanel(), and hence that Panel will "own" the JTextField. It only makes sense that a UI component can only be at one place at any given time, otherwise things would get very strange :)
Your statement
Both pages contain the same workNumberPanel and I cant find a difference, that would explain the behaviour.
is simply not true. You are creating a new instance of WorkNumberPanel in both OverViewPage and TrackingPage when you execute the following line
WorkNumberPanel equipmentNumberPanel = new WorkNumberPanel();
So my recommendation is that you find another way of implementing what you want without using a static JTextField (or any other UI component for that matter).
Here you instantiate a OverviewPage, then a TrackingPage .
OverviewPage overviewPage = new OverviewPage();
TrackingPage trackingPage = new TrackingPage();
Both of these classes instantiate a WorkNumberPanel .
WorkNumberPanel add the static JTextField (txtWorkNumber) to their display panel (mainWorkNumberPanel).
A single Component can't be added to several Container objects.
This is what happens to your textfield, since it is static and not an instance variable.
The last addition will win, so the textfield will appear in TrackingPage only, and not in OverviewPage anymore .
Just don't make it static.
First off you need to understand what a static field is. A static field is not related to a particular instance of an object. The field is related to the class itself.
There's quite a good explanation here and here.
Now with regards to your case. A JComponent can only be added to one panel at a time. Adding it to another will remove it from the first.
In your code you are creating multiple instances of 'WorkingNumberPanel'. When you do this you add the text fields to the panel, including the static text field txtWorkNumber. Since the field txtWorkNumber is static you are adding the same object to multiple components, which as I mentioned above will remove it from anywhere it was previously added.
One possible way of solving this would be to store the value from txtWorkNumber in a static variable and create a new instance (non-static) text field to add to the panel.

How can I get my labels into the inner frame I have created? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have been given an assignment whereby I need to create a tool that analyses a field of text and then outputs a couple of statistics about said body of text via a button click. I seem to have most of the basic framework up but am struggling with getting my two labels that are averageLength and totalWords inside my JPanel and also on getting said JPanel below where I enter my body of text. Any help would be much appreciated. Code is here:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TextStatisticsPanel extends JPanel
{
//Field for block of text
private JTextArea userText;
//Button to calculate Statistics
private JButton stats;
//Label for where statistics are shown and statistics
private JLabel averageLength, totalWords;
public TextStatisticsPanel(){
//creating the area for user text with wrapped text
userText = new JTextArea();
userText.setWrapStyleWord(true);
userText.setLineWrap(true);
//create button
stats = new JButton("Update Text Statistics");
//Listener for button
stats.addActionListener(new ButtonListener());
//Tilted border creater
JPanel statPanel = new JPanel();
statPanel.setBorder(BorderFactory.createTitledBorder("Text Statistics"));
statPanel.setOpaque(false);
//Create Scroller
JScrollPane scroller = new JScrollPane(userText);
scroller.setPreferredSize(new Dimension (350, 400));
scroller.setBorder(BorderFactory.createTitledBorder ("Enter the text below"));
//Add the statistics labels
averageLength = new JLabel("The average length of the words: ");
totalWords = new JLabel("The total number of words: ");
//add GUI
add(statPanel);
add(scroller);
add(averageLength);
add(totalWords);
setBackground(new java.awt.Color(202, 225, 255));
setPreferredSize(new Dimension (400, 600));
add(stats);
}
// When button is pressed do :
private class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent event)
{
if (event.getSource() == stats){
//Call statUpdate Method
statUpdate();
}
}
// Create statUpdate Method
private void statUpdate()
{
//Grab text user inputed
String text = userText.getText();
//Split the text by each space to find the number of words
String[] words = text.split(" ");
//Calculation for average
float average = (text.length() - words.length)/words.length;
//
averageLength.setText(String.valueOf(average));
totalWords.setText(String.valueOf(words.length));
System.out.println(averageLength);
System.out.println(totalWords);
}
}
}
OK so as to try and use MCVE, this is part of the relevent code however I am still unable to work out the root of the problem.
The code for my second panel is :
JPanel statPanel = new JPanel();
statPanel.setBorder(BorderFactory.createTitledBorder("Text Statistics"));
statPanel.setOpaque(false);
SO as per my understanding this is me creating a second panel among my app. The problem however is that this is being placed in a seemingly random location and is not wrapping around the two labels I wish to be inside this panel and I am unsure how to fix this problem.
The main class code:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.JFrame;
public class TextStatistics {
public static void main(String[] args) {
JFrame frame = new JFrame("Text Statistics Tool");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TextStatisticsPanel panel = new TextStatisticsPanel();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
Providing a visual example to show the code I believe is the problem and the problem I am encountering
Problem Visualised
Here's the GUI I put together.
These are the major changes I made.
I put the JFrame code in a Runnable, so I could start the Swing application with a call to the SwingUtilities invokeLater method. The invokeLater method ensures that the Swing components are created and updated on the Event Dispatch thread. Oracle and I require that everyone starts their Swing applications on the Event Dispatch thread.
I defined several new JPanels in your TextStatisticsPanel class and used two Swing layout managers, BorderLayout and BoxLayout. Study the link in the previous sentence. By study, I mean spend at least two to three weeks of 8 hour days absorbing all of the ins and outs of the Swing layout managers.
I added JTextFields to hold the calculated values. That's what JTextFields are for.
I fixed the integer division in your statUpdate method.
Here's the code. I put everything together in one file so it would be easier to upload. You should put the classes in separate files.
package com.ggl.testing;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class TextStatistics {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Text Statistics Tool");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TextStatisticsPanel panel = new TextStatistics().new TextStatisticsPanel();
frame.add(panel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(runnable);
}
public class TextStatisticsPanel extends JPanel {
private static final long serialVersionUID = 9049744714586970558L;
// Field for block of text
private JTextArea userText;
// Button to calculate Statistics
private JButton stats;
// Label for where statistics are shown and statistics
private JLabel averageLength, totalWords;
private JTextField averageLengthField, totalWordsField;
public TextStatisticsPanel() {
// creating the area for user text with wrapped text
userText = new JTextArea();
userText.setWrapStyleWord(true);
userText.setLineWrap(true);
// create button
stats = new JButton("Update Text Statistics");
stats.setAlignmentX(JButton.CENTER_ALIGNMENT);
// Listener for button
stats.addActionListener(new ButtonListener());
// Tilted border creater
JPanel statPanel = new JPanel();
statPanel.setBorder(BorderFactory
.createTitledBorder("Text Statistics"));
statPanel.setLayout(new BoxLayout(statPanel, BoxLayout.PAGE_AXIS));
statPanel.setOpaque(false);
// Create Scroller
JScrollPane scroller = new JScrollPane(userText);
scroller.setPreferredSize(new Dimension(350, 400));
scroller.setBorder(BorderFactory
.createTitledBorder("Enter the text below"));
// Add the statistics labels
averageLength = new JLabel("The average length of the words: ");
averageLength.setOpaque(false);
averageLengthField = new JTextField(10);
averageLengthField.setEditable(false);
averageLengthField.setOpaque(false);
totalWords = new JLabel("The total number of words: ");
totalWords.setOpaque(false);
totalWordsField = new JTextField(10);
totalWordsField.setEditable(false);
totalWordsField.setOpaque(false);
// add GUI
setLayout(new BorderLayout());
statPanel.add(stats);
statPanel.add(Box.createVerticalStrut(10));
JPanel lengthPanel = new JPanel();
lengthPanel.setOpaque(false);
lengthPanel.add(averageLength);
lengthPanel.add(averageLengthField);
statPanel.add(lengthPanel);
statPanel.add(Box.createVerticalStrut(10));
JPanel wordsPanel = new JPanel();
wordsPanel.setOpaque(false);
wordsPanel.add(totalWords);
wordsPanel.add(totalWordsField);
statPanel.add(wordsPanel);
add(statPanel, BorderLayout.SOUTH);
add(scroller, BorderLayout.CENTER);
setBackground(new java.awt.Color(202, 225, 255));
}
// When button is pressed do :
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == stats) {
// Call statUpdate Method
statUpdate();
}
}
// Create statUpdate Method
private void statUpdate() {
// Grab text user inputed
String text = userText.getText();
// Split the text by each space to find the number of words
String[] words = text.split(" ");
// Calculation for average
float average = ((float) text.length() - words.length)
/ words.length;
//
averageLengthField.setText(String.valueOf(average));
totalWordsField.setText(String.valueOf(words.length));
}
}
}
}

Adding Extensions of JPanel to JFrame

I have a class that contains the main GUI window that my program will display
/**
* GUI program to run a coffee/bagel shoppe
* #author Nick Gilbert
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CoffeeShop extends JPanel {
private final int WINDOW_WIDTH = 400; // Window width
private final int WINDOW_HEIGHT = 300; // Window height
private JFrame mainFrame;
public CoffeeShop()
{
//Setting up mainframe configurations
mainFrame = new JFrame();
mainFrame.setTitle("Order Entry Screen!");
mainFrame.setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setLayout(new BorderLayout());
//Piecing together GUI window
mainFrame.add(new TitleRegister(), BorderLayout.NORTH);
mainFrame.setVisible(true);
}
public static void main(String[] args) {
new CoffeeShop();
}
}
As you can see, I'm trying to add to mainFrame a JPanel that is actually a class I wrote which extends JPanel
/**
* Sets title at top of register
* #author Nick Gilbert
*/
import javax.swing.*;
import java.awt.*;
import java.awt.Event.*;
public class TitleRegister extends JPanel {
private JPanel titlePanel;
private JLabel titleLabel;
public TitleRegister() {
titlePanel = new JPanel();
titleLabel = new JLabel("Order Entry Screen", SwingConstants.CENTER);
titlePanel.add(titleLabel);
titlePanel.setVisible(true);
}
}
Yet when I do this the instance of TitleRegister does not show up. I have setVisible set to true for everything so it should be showing up.
You've not actually added anything to the TitleRegister pane...
Without knowing more, you could simply getaway with...
public class TitleRegister extends JPanel {
private JLabel titleLabel;
public TitleRegister() {
titleLabel = new JLabel("Order Entry Screen", SwingConstants.CENTER);
add(titleLabel);
}
}
In fact, you could simply get away with adding the JLabel to the mainFrame.
Notes:
There's no need to CoffeeShop to extend JPanel, you're not adding anything to, your constructor builds a JFrame and adds the UI to that...
Rely on pack over setSize, it will produce a more reliable output, ensuring that the content area has the space it needs to be properly displayed.
Make sure you are creating and modifying your UI's only from the context of the Event Dispatching Thread. See Initial Threads for more details...

Blank JFrame and No JPanel appeared but already added

Can anyone help me? Whenever I ran the codes below, it always returns a blank frame, I don't know where I did wrong. Can you guys help me debug this? I already added the components to the panel, and the panel to the frame, but still it returns a blank output.
Here is the output I'm getting:
While this is what is required.
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.ButtonGroup;
import javax.swing.BorderFactory;
import javax.swing.UIManager;
import javax.swing.BoxLayout;
import java.awt.GridLayout;
import java.awt.EventQueue;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JRadioButton;
/**
*
* #author Chareux
*/
//Declaring Variables
public class TestUI {
private JFrame frm_main;
private JPanel sr_pnl;
private JLabel sr_lbl;
private JLabel sr_lbl2;
private JLabel ret_optn_lbl;
private JLabel ret_rsn_lbl;
private ButtonGroup ret_ops;
private JTextField sr_txtnum;
private JTextField sr_ret_txtrsn;
private JButton sr_start;
private JRadioButton ret_optn_rdbn_y;
private JRadioButton ret_optn_rdbn_n;
public TestUI(){
start();
}
public void start(){
//Creating the JFrame
frm_main = new JFrame("Service Desk SR Tool");
frm_main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm_main.setSize(500,450);
frm_main.setLocationRelativeTo(null);
frm_main.setResizable(false);
frm_main.setVisible(true);
// the Panel
sr_pnl = new JPanel();
//Components
sr_lbl = new JLabel("SERVICE DESK SR TIMER!");
sr_lbl2 = new JLabel("SR number: ");
sr_txtnum = new JTextField("Enter SR number here..",20);
ret_optn_lbl = new JLabel("Returning Ticket?");
ret_optn_rdbn_y = new JRadioButton("Yes");
ret_optn_rdbn_n = new JRadioButton("No");
ret_rsn_lbl = new JLabel("Reason: ");
sr_ret_txtrsn = new JTextField("Enter Reason number here..",20);
sr_start = new JButton("START!");
//adding the Components to the panel
sr_pnl.add(sr_lbl);
sr_pnl.add(sr_lbl2);
sr_pnl.add(sr_txtnum);
sr_pnl.add(ret_optn_lbl);
sr_pnl.add(ret_optn_rdbn_y);
sr_pnl.add(ret_optn_rdbn_n);
sr_pnl.add(ret_rsn_lbl);
sr_pnl.add(sr_ret_txtrsn);
sr_pnl.add(sr_start);
frm_main.add(sr_pnl,BorderLayout.CENTER);
//ButtonGroup for the radio button
ret_ops = new ButtonGroup();
ret_ops.add(ret_optn_rdbn_y);
ret_ops.add(ret_optn_rdbn_n);
}
public static void main(String[] args) {
new TestUI();
}
}
I'd recommend to use a nested or compound layout for this task. See further tips in comments in the source.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class SRTool {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
// the GUI as seen by the user (without frame)
JPanel gui = new JPanel(new GridLayout(0,1,6,6));
gui.setBorder(new EmptyBorder(2, 3, 2, 3));
// show the BG
gui.setBackground(Color.CYAN);
// center the label text
gui.add(new JLabel(
"Service Desk SR Tool", SwingConstants.CENTER));
// create a lyout that can center multiple components
FlowLayout layout = new FlowLayout(FlowLayout.CENTER,5,5);
JPanel srPanel = new JPanel(layout);
gui.add(srPanel);
srPanel.add(new JLabel("SR:"));
srPanel.add(new JTextField(8));
JPanel returnTicketPanel = new JPanel(layout);
gui.add(returnTicketPanel);
returnTicketPanel.add(new JLabel("Returning Ticket?"));
returnTicketPanel.add(new JCheckBox());
JPanel reasonPanel = new JPanel(layout);
gui.add(reasonPanel);
reasonPanel.add(new JLabel("Reason:"));
reasonPanel.add(new JTextField(14));
JPanel buttonPanel = new JPanel(layout);
gui.add(buttonPanel);
buttonPanel.add(new JButton("Start!"));
JFrame f = new JFrame("Demo");
f.add(gui);
// Ensures JVM closes after frame(s) closed and
// all non-daemon threads are finished
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// See https://stackoverflow.com/a/7143398/418556 for demo.
f.setLocationByPlatform(true);
// ensures the frame is the minimum size it needs to be
// in order display the components within it
f.pack();
// should be done last, to avoid flickering, moving,
// resizing artifacts.
f.setVisible(true);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}
Java GUIs might have to work on a number of platforms, on different screen resolutions & using different PLAFs. As such they are not conducive to exact placement of components. To organize the components for a robust GUI, instead use layout managers, or combinations of them1, along with layout padding & borders for white space2.
Add frm_main.validate() in the end of start()
public void start(){
/*
...
Same As Above
...
*/
frm_main.add(sr_pnl,BorderLayout.CENTER);
//ButtonGroup for the radio button
ret_ops = new ButtonGroup();
ret_ops.add(ret_optn_rdbn_y);
ret_ops.add(ret_optn_rdbn_n);
frm_main.validate(); // Add this line ******
}

how can i program this ui box

in what way can this be programmed.
a UI box that displays random number between min and max value for 2 seconds then shows blank for 2 seconds then shows another random numer for 2 seconds then shows blank for 10 seonds and then repeats the cycle infitely until form closed. Font of the text to be configurable.
any help at all will be appreciated.
UPDATE after feedback
this is my progress so far. simple jpanel. now how do i add random number and timer
import javax.swing.JFrame;
import javax.swing.JPanel;
public class RandomSlide {
public static void main(String[]args)
{
//Create a JPanel
JPanel panel=new JPanel();
//Create a JFrame that we will use to add the JPanel
JFrame frame=new JFrame("Create a JPanel");
//ADD JPanel INTO JFrame
frame.add(panel);
//Set default close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set JFrame size to :
//WIDTH : 400 pixels
//HEIGHT : 400 pixels
frame.setSize(400,400);
//Make JFrame visible. So we can see it
frame.setVisible(true);
}
}
You have multiple languages in your tags, so I'm unsure what to repond with.
For java you'd make a JPanel with the appropriate UI elements and build a Timer instance to shoot off scheduled events every 2 seconds to update the value.
In VBA for Excel you'd have to do the same with a Form and Timer Control, however you may encounter more issues in Excel/VBA than in java.
Update 16/04/2010
You can actually sub-class the JPanel to clean up the code.
class RandomDialog extends JFrame
{
private Timer _timer;
private JPanel _container;
public RandomDialog()
{
_timer = new Timer();
_container = new JPanel();
// Etc...
}
}
From here you can instantiate your children and register an event on the timer to call a function on your class which generates the random number and displays it to a JLabel.
Then you can just call your dialog in your driver like so:
public static void main(string [] args)
{
RandomDialog rand = new RandomDialog();
rand.show();
}
Here is some code that will get you rolling.
Note that you could just extend a JLabel instead of JPanel. I used JPanel based on your question. Also, note that you may use timer.setDelay() API to change the timing. Also, you could stop the timer by a stop() call.
package answer;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
public class RandomPanel extends JPanel implements ActionListener {
private static final int TWO_SECONDS=2000;
private static final int MAX=99999;
private static final int MIN=0;
private Timer timer = new javax.swing.Timer(TWO_SECONDS, this);
private JLabel msgLabel;
Random generator = new Random();
public RandomPanel(Font f){
msgLabel = new JLabel();
msgLabel.setFont(f);
msgLabel.setText(rand());
add(msgLabel);
}
#Override
public void actionPerformed(ActionEvent e) {
msgLabel.setText(msgLabel.getText().equals("")?rand():"");
}
private String rand() {
//generate random beteween MIN & MAX
return Integer.toString((int) (MIN + Math.random() * ( MAX - MIN) + 0.5));
}
public void start(){
timer.start();
}
/**
* Rudimentary test
* #param args
*/
public static void main(String[] args) {
JFrame frame = new JFrame();
RandomPanel randomPanel = new RandomPanel(new Font("Serif", Font.BOLD, 50));
frame.getContentPane().add(randomPanel);
frame.setSize(400,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
randomPanel.start();
}
}

Categories