GUI not appearing - java

I have a Main class that has a public static void main(String[] args) {}. I also have a class called appGUI. I have been trying to get the GUI to load when i run the Main class, but nothing occurs, not even any errors... :(
Here is the Main class:
public class Main {
/**
* #param args
*/
public static void main(String[] args) throws Exception {
appGUI gui = new appGUI();
}
}
And here is the appGUI class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
* Created by JFormDesigner on Wed Apr 03 19:24:35 BST 2013
*/
/**
* #author Hrach Ghapantsyan
*/
public class appGUI extends JFrame {
public appGUI() {
initComponents();
}
private void loginButtonActionPerformed(ActionEvent e) {
// TODO add your code here
}
private void initComponents() {
// JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents
// Generated using JFormDesigner Evaluation license - Hrach Ghapantsyan
loginPasswordField = new JPasswordField();
loginUsernameField = new JTextField();
usernameLabel = new JLabel();
passwordLabel = new JLabel();
loginButton = new JButton();
titleLabel = new JLabel();
//======== this ========
setTitle("Experimental X | Administrator Login");
Container contentPane = getContentPane();
contentPane.setLayout(null);
contentPane.add(loginPasswordField);
loginPasswordField.setBounds(80, 65, 100, loginPasswordField.getPreferredSize().height);
contentPane.add(loginUsernameField);
loginUsernameField.setBounds(80, 35, 100, loginUsernameField.getPreferredSize().height);
//---- usernameLabel ----
usernameLabel.setText("Username:");
contentPane.add(usernameLabel);
usernameLabel.setBounds(20, 40, 55, usernameLabel.getPreferredSize().height);
//---- passwordLabel ----
passwordLabel.setText("Password:");
contentPane.add(passwordLabel);
passwordLabel.setBounds(20, 70, 55, passwordLabel.getPreferredSize().height);
//---- loginButton ----
loginButton.setText("Login");
loginButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
loginButtonActionPerformed(e);
}
});
contentPane.add(loginButton);
loginButton.setBounds(80, 95, 100, loginButton.getPreferredSize().height);
//---- titleLabel ----
titleLabel.setText("Experimental X | Administrator Login");
contentPane.add(titleLabel);
titleLabel.setBounds(45, 10, 190, titleLabel.getPreferredSize().height);
{ // compute preferred size
Dimension preferredSize = new Dimension();
for(int i = 0; i < contentPane.getComponentCount(); i++) {
Rectangle bounds = contentPane.getComponent(i).getBounds();
preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
}
Insets insets = contentPane.getInsets();
preferredSize.width += insets.right;
preferredSize.height += insets.bottom;
contentPane.setMinimumSize(preferredSize);
contentPane.setPreferredSize(preferredSize);
}
setSize(270, 170);
setLocationRelativeTo(getOwner());
// JFormDesigner - End of component initialization //GEN-END:initComponents
}
// JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables
// Generated using JFormDesigner Evaluation license - Hrach Ghapantsyan
private JPasswordField loginPasswordField;
private JTextField loginUsernameField;
private JLabel usernameLabel;
private JLabel passwordLabel;
private JButton loginButton;
private JLabel titleLabel;
// JFormDesigner - End of variables declaration //GEN-END:variables
}
I have tried running the main class on Eclipse and netbeans, but it runs and then stops after a few seconds. I do not get any errors. Do any of you here have any suggestions? Thanks.

You haven't called JFrame#setVisible:
gui.setVisible(true);
Some notes:
Avoid using null layout. Always use a layout manager
Don't use the setXXXSize methods. Override getPreferredSize method to determine component sizes
Rather than extending a JFrame, you typically want to create one and use directly.
Consider creating the JFrame in the EDT by using initial threads

Make sure you call setVisible(true) on the GUI.

public class appGUI extends JFrame {
setVisible(true);
// ----
}
place this code to make visible.

Just add:
this.setVisible(true);

Related

Setting the height of a JTextFrame

The following class creates a form (Jpanel) tasked with acquiring multiples Strings from the user and do something with them. It it functionally working, but it bugs me that the height of the JTextFields (a component that allows for the modification of one line of text) is automatically adjusted and can became extravagantly big.
I have tried the method setBounds(), but:
I do not want to calculate the position or width of the JTextField, just its height; and
It does not limit the height of the JTextField!
Any suggestion, please?
public class MultiplesStrings extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1106317992372206473L;
/** The greater {#link JPanel}. */
private JPanel contentPane;
private JPanel[] interaction;
private JLabel[] text;
private JTextField[] insertText;
/** The {#link JButton} that submits the form information. */
JButton button;
#SuppressWarnings("unused")
private Consumer<MultiplesStrings> instructions;
// =========================================================
// TODO | Constructor
/**
* Create the frame.
*/
public MultiplesStrings(String title, String[] messages,
int x, int y, int width, int height,
Consumer<MultiplesStrings> instructions) {
// ===== MAIN FRAME DEFINITION =====
this.setTitle(title);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(x, y, width, height);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(10, 10, 10, 10));
setContentPane(contentPane);
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS));
// contentPane.setBackground(Colours.newColor("DDDDDD"));
// ===== INTERACTION FRAME DEFINITION =====
this.interaction = new JPanel[messages.length];
this.text = new JLabel[messages.length];
this.insertText = new JTextField[messages.length];
for(int i=0 ; i<messages.length ; i++)
{
interaction[i] = new JPanel();
interaction[i].setLayout(new BoxLayout(interaction[i], BoxLayout.LINE_AXIS));
interaction[i].setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
interaction[i].add(Box.createHorizontalGlue());
// ===== TEXT =====
text[i] = new JLabel(messages[i]);
text[i].setAlignmentY(RIGHT_ALIGNMENT);
// text.setBounds(0, imageResolution + margin, Width, buttonHeight);
interaction[i].add(text[i]);
// ===== INSERT TEXT FIELD =====
insertText[i] = new JTextField();
// this.insertTextField.setBounds(Width + margin, imageResolution + margin, moveWidth, buttonHeight);
insertText[i].setColumns(10);
interaction[i].add(insertText[i]);
this.add(interaction[i]);
}
// ===== SUBMIT BUTTON DEFINITION =====
this.button = new JButton("Submit");
// Button behavior
MultiplesStrings support = this;
button.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) { }
} );
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
instructions.accept(support);
// support.setVisible(false);
}
} );
this.getRootPane().setDefaultButton(button);
this.add(button);
}
// =========================================================
// TODO | Input-output manipulation
/** Acquires all {#link String}s written by the user in the {#link JTextField}s used for {#code interactions}. */
public String[] acquireInputs() {
String[] output = new String[interaction.length];
for(int i=0 ; i<output.length ; i++)
output[i] = insertText[i].getText();
return output;
}
// =========================================================
// TODO | Main
public static final int width = 300;
public static final int height = 500;
private static String[] input;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() { public void run() {
try {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double screenWidth = screenSize.getWidth();
double screenHeight = screenSize.getHeight();
// Creates a centered form
MultiplesStrings ms = new MultiplesStrings("Test",
new String[] { "Insert first string: ", "Insert second string: ", "Insert third string: "},
(int) (screenWidth-width)/2, (int) (screenHeight-height)/2, width, height,
(MultiplesStrings obj) ->
{
input = obj.acquireInputs();
for(int i=0 ; i<input.length ; i++)
System.out.println("The " + i + "-th input is: " + input[i]);
}
);
ms.setVisible(true);
} catch (Exception e) { e.printStackTrace(); }
}
});
}
}
This is because BoxLayout uses the whole space of the container. With other words, it stretches all components to take the advantage of the total available space (since you use PAGE_AXIS, it refers to available height).
One of the solutions is to use a BorderLayout as an outside container and add this BoxLayout-ed panel inside at, with BorderLayout.PAGE_START constraints. PAGE_START constraints refers as "Hey you BoxLayout, there is no available space for you". Take a look at this example:
public class BoxLayoutSample extends JFrame {
public BoxLayoutSample() {
super("");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
contentPane.add(new JTextField(15));
contentPane.add(new JTextField(15));
setLocationByPlatform(true);
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new BoxLayoutSample().setVisible(true));
}
}
It gives us:
This is what you have by now.
But if you use an outside BorderLayout-ed panel:
public class BoxLayoutSample extends JFrame {
public BoxLayoutSample() {
super("");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = getContentPane(); //This is the outer panel
contentPane.setLayout(new BorderLayout());
JPanel boxLayoutPanel = new JPanel(); //This is the nested panel
boxLayoutPanel.setLayout(new BoxLayout(boxLayoutPanel, BoxLayout.Y_AXIS));
//Components to nested panel
boxLayoutPanel.add(new JTextField(15));
boxLayoutPanel.add(new JTextField(15));
//PAGE_START to wrap it on the top
contentPane.add(boxLayoutPanel, BorderLayout.PAGE_START);
setLocationByPlatform(true);
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new BoxLayoutSample().setVisible(true));
}
}
You get:
Also, calling setBounds method to a component will be ignored if it contains a layout. In order to see setBounds effect you must container.setLayout(null) since the layout is responsible for the component's bounds. However, THIS IS NOT RECOMMENDED. INSTEAD USE LAYOUT MANAGERS. Let them work for you.

Scrollbar JTextarea not working

For some reason my scrollbar is appearing but it is not working. What is suppose to happen is using the scrollbar to scroll through the text of the textarea. Can somebody please explain why this isnt working?
import java.io.*;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class App extends JFrame{
private JPanel paneel;
public App(){
paneel = new AppPaneel();
setContentPane(paneel);
}
public static void main(String args[]){
JFrame frame = new App();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setTitle("Auto Clicker");
frame.setVisible(true);
}
}
class AppPaneel extends JPanel{
private JTextField delayField, xLocation, yLocation;
private JTextArea listArea;
private JButton addButton, saveButton, runButton;
private JScrollPane scroll;
public AppPaneel(){
setLayout(null);
delayField = new JTextField();
delayField.setBounds(10, 10, 85, 25);
delayField.setText("delay in ms");
xLocation = new JTextField();
xLocation.setBounds(105, 10, 85, 25);
xLocation.setText("X position");
yLocation = new JTextField();
yLocation.setBounds(200, 10, 85, 25);
yLocation.setText("Y position");
addButton = new JButton("Add");
addButton.setBounds(295, 10, 75, 24);
addButton.addActionListener(new AddHandler());
listArea = new JTextArea();
listArea.setBounds(10, 45, 360, 180);
scroll = new JScrollPane(listArea);
scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scroll.setBounds(370, 45, 20, 180);
saveButton = new JButton("Save");
saveButton.setBounds(10, 230, 85, 24);
runButton = new JButton("Run (F1)");
runButton.setBounds(105, 230, 85, 24);
runButton.addActionListener(new RunHandler());
add(delayField);
add(xLocation);
add(yLocation);
add(addButton);
add(listArea);
add(saveButton);
add(runButton);
add(scroll);
}
class AddHandler implements ActionListener{
public void actionPerformed(ActionEvent a){
listArea.setText(listArea.getText() + delayField.getText() + ", " + xLocation.getText() + ", " + yLocation.getText() + ", " + "click;" + "\n");
}
}
class RunHandler implements ActionListener{
private Robot bot;
private String text;
int foo = Integer.parseInt("1234");
public void actionPerformed(ActionEvent b) {
try{
text = listArea.getText();
bot = new Robot();
for(String line : text.split("\\n")){
int delay = Integer.parseInt((line.substring(0, 4)));
int xpos = Integer.parseInt((line.substring(6, 10)));
int ypos = Integer.parseInt((line.substring(12, 16)));
bot.mouseMove(xpos, ypos);
Thread.sleep(delay);
bot.mousePress(InputEvent.BUTTON1_MASK);
bot.mouseRelease(InputEvent.BUTTON1_MASK);
}
}
catch (AWTException | InterruptedException e){
e.printStackTrace();
}
}
}
}
Don't use null layouts and setBounds as it is messing up your program. We tell folks time and time again not to do this for a reason -- by setting the JTextArea's bound you constrain its size so it won't grow when it needs to. The solution, as always -- learn and use the layout managers. Set the JTextArea's column and row properties but not its bounds, its size, or its preferred size.
Next don't do this: Thread.sleep(delay); in your Swing application as it will put the entire application to sleep. Use a Swing Timer instead for any delays. The tutorials can help you use this.
For a non-functional layout example:
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.*;
#SuppressWarnings("serial")
public class App2 extends JPanel {
private static final int GAP = 5;
private JTextField textField1 = new JTextField(GAP);
private JTextField textField2 = new JTextField(GAP);
private JTextField textField3 = new JTextField(GAP);
private JTextArea textArea = new JTextArea(15, 30);
public App2() {
JPanel topPanel = new JPanel(new GridLayout(1, 0, GAP, GAP));
topPanel.add(textField1);
topPanel.add(textField2);
topPanel.add(textField3);
topPanel.add(new JButton("Add"));
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JPanel bottomPanel = new JPanel(new GridLayout(1, 0, GAP, GAP));
bottomPanel.add(new JButton("Save"));
bottomPanel.add(new JButton("Run (F1)"));
bottomPanel.add(new JLabel(""));
bottomPanel.add(new JLabel(""));
setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
setLayout(new BorderLayout(GAP, GAP));
add(topPanel, BorderLayout.PAGE_START);
add(scrollPane, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Auto Clicker");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new App2());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Your whole approach is wrong. You should not be using a null layout. For example:
scroll.setBounds(370, 45, 20, 180);
you are setting the width to 20. Well how to you expect the text area to display in 20 pixels? This is the problem with using setBounds(...), the random numbers you use have no meaning. Let a layout manager do its job. Also:
add(listArea);
The problem is that a component can only have a single parent. You originally created the JScrollPane with the text area which is correct.
But then you add the text area directly to the frame which removes it from the scroll pane so the scroll panel will no longer function.
Get rid of that statement and just add the scroll pane to the frame.
However, I don't recommend you use this as your final solution. I just wanted to mention the current problems so you hopefully understand the benefits of using layout managers and so that you don't try to share components again.
The proper solution is to use layout managers as has been suggested by the "Community Wiki". Then the layout manager will determine the size and location of each component so you don't need to worry about calculating your pixel values correctly.

Compiler Warning class uses unchecked or unsafe operations

My code is currently working fine, but whenever i compile, i get the Warning
C:\Users\etc\etc\FinalProject\AddItem.java uses unchecked or unsafe operations. Recompile with -Xlint:unchecked for details.
Should I do something about it, and if so, what? if my debugging is right, it appears to be caused by the content pane properties.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Canvas;
import javax.swing.JFrame;
import java.awt.Dimension;
import java.io.*;
class AddItem extends JFrame implements ActionListener
{
//text
private static JLabel TechforTeachingTitle;
private static JLabel TechforTeachingSubTitle;
//images
private static JLabel Logo;
//buttons
private JButton submitButton;
private static final int BUTTON_WIDTH = 100;
private static final int BUTTON_HEIGHT = 30;
//variables
public static void main(String[] args)
{
AddItem ProjectFrame = new AddItem();
ProjectFrame.setVisible(true); // Display the frame
//for combobox
//new AddItem().setVisible(true);
}
public AddItem ( )
{
//font properties
Font TitleFont = new Font("Serif", Font.BOLD, 80);
Font subFont = new Font("Serif", Font.BOLD, 40);
// set the frame properties
setDefaultCloseOperation(EXIT_ON_CLOSE);
setTitle("Inventory system");
setSize(900, 700);
setLocationRelativeTo(null);
setResizable(true);
// set the content pane properties
Container contentPane = getContentPane();
contentPane.setLayout(null);
contentPane.setBackground(Color.decode("#FDF3E7"));
//set text properties
TechforTeachingTitle = new JLabel();
TechforTeachingTitle.setText("Tech For Teaching");
TechforTeachingTitle.setBounds(200, 30, 900, 95);
TechforTeachingTitle.setForeground(Color.decode("#8f8f8f"));
TechforTeachingTitle.setFont(TitleFont);
contentPane.add(TechforTeachingTitle);
TechforTeachingSubTitle = new JLabel();
TechforTeachingSubTitle.setText("Add an item");
TechforTeachingSubTitle.setBounds(400, 90, 900, 95); //left, top, length, height
TechforTeachingSubTitle.setForeground(Color.decode("#799177")); //7E8F7C (slightly less green)
TechforTeachingSubTitle.setFont(subFont);
contentPane.add(TechforTeachingSubTitle);
//set image properties
Logo = new JLabel(new ImageIcon("SmallLogo.png"));
Logo.setBounds(10,20,179,178); // //left, top, width, height
contentPane.add(Logo);
Logo.setVisible(true);
Logo.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e) {
setVisible(false);
FinalProject FP = new FinalProject();
FP.setVisible(true);
}
});
//set button properties
//for combobox
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//setLayout(null); //ONLY PROBLEM WITH THIS IS GETTING THE SCREEN TO APPEAR AT CORRECT SIZE
String[] values = {"Computer", "Monitor", "Keyboard"};
final JComboBox b = new JComboBox(values);
b.setEditable(true);
add(b);
b.setBounds(300, 300, 100, 50); //this works
add(b);
submitButton = new JButton("Submit");
submitButton.setBounds(700,600, BUTTON_WIDTH, BUTTON_HEIGHT);
submitButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String item=b.getSelectedItem().toString();
}
});
contentPane.add(submitButton);
//pack(); //not quite sure what this is for, but it makes the window tiny, so i commented it out
setLocationRelativeTo(null); //positions window center on screen
}
public void actionPerformed(ActionEvent event) // Actions
{
JButton clickedButton = (JButton) event.getSource();
String buttonText = clickedButton.getText();
}
}
you get the warning here I think:
final JComboBox b = new JComboBox(values);
to avoid this you have the following possibilities:
add SupressWarning above the JComboBox
#SuppressWarnings("unchecked")
final JComboBox b = new JComboBox(values);
or add SupressWarning above your method
#SuppressWarnings("rawtypes")
public AddItem ( )
or my favourite add the generic:
final JComboBox<Object> b = new JComboBox<Object>(values);

Area Calculator not working and not sure why

This is the source code for my calculator that i am building in eclipse windowbuilder, i am trying to make two textFields read input and output the area for a simple rectangle, i can type the numbers into the boxes however the numbers do not compute and i am at a loss as to what i could be doing wrong, please critique my code and let me know why it isn't working. Thank you
*Edit, i have removed and changed a few things and now the Answer box displays 0.0 and nothing else
import java.awt.EventQueue;
public class GUI {
private JFrame frame;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI window = new GUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 694, 499);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
tabbedPane.addTab("New tab", null, panel, null);
panel.setLayout(null);
JLabel lblInputBase = new JLabel("Input Base");
lblInputBase.setBounds(0, 0, 57, 39);
panel.add(lblInputBase);
textField = new JTextField();
textField.setBounds(0, 28, 86, 20);
panel.add(textField);
textField.setColumns(10);
double value = Double.parseDouble(textField.getText());
JLabel lblInputHeight = new JLabel("Input Height");
lblInputHeight.setBounds(0, 212, 68, 20);
panel.add(lblInputHeight);
textField_1 = new JTextField();
textField_1.setBounds(0, 230, 86, 20);
panel.add(textField_1);
textField_1.setColumns(10);
double value_1 = Double.parseDouble(textField_1.getText());
double Area = value*value_1;
String finalArea = Double.toString(Area);
JLabel lblArea = new JLabel("Area:");
lblArea.setBounds(244, 119, 75, 68);
panel.add(lblArea);
textField_2 = new JTextField();
textField_2.setBounds(273, 143, 86, 20);
panel.add(textField_2);
textField_2.setColumns(10);
textField_2.setEditable(false);
textField_2.setText(finalArea);
}
}
Your code is really confusing, but here are some problems that I found:
double value = Double.parseDouble(textField.getText());
This is being run before the user has any chance to even look at the gui. textField.getText() will return an empty string here, and the parseDouble method will always throw a NumberFormatException when the program is run, as it does not consider an empty string to be a valid number format.
double Area = Double.parseDouble(value)*Double.parseDouble(value_1);
Here, the variable value is already a double and does not need to be parsed, and the variable value_1 doesn't exist.
Where you meant to assign an actionListener to textField_1, you assigned a second one to textField.
Overall, it seems that all your calculation logic is being run in your initialize() method, and this means that it is only being run once. You'll want your math to be run whenever one of the text fields is updated.
Your field names are horribly confusing. Your textField variable names should give some indication of their function, like areaTextField, baseTextField, heightTextField.
Here is a modification of your code that seems to function as you intended yours to function. Note the addition of a calculate() method that is called by the action listeners that will find the area and display it, or display NaN (Not a Number) if either of the input fields are not valid numbers. All of your GUI code is retained as is, excepting the renaming of the text field variables.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
public class GUI {
private JFrame frame;
private JTextField baseTextField;
private JTextField heightTextField;
private JTextField areaTextField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI window = new GUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GUI() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 694, 499);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
tabbedPane.addTab("New tab", null, panel, null);
panel.setLayout(null);
JLabel lblInputBase = new JLabel("Input Base");
lblInputBase.setBounds(0, 0, 57, 39);
panel.add(lblInputBase);
baseTextField = new JTextField();
baseTextField.setBounds(0, 28, 86, 20);
panel.add(baseTextField);
baseTextField.setColumns(20);
baseTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
calculate();
}
});
JLabel lblInputHeight = new JLabel("Input Height");
lblInputHeight.setBounds(0, 212, 68, 20);
panel.add(lblInputHeight);
heightTextField = new JTextField();
heightTextField.setBounds(0, 230, 86, 20);
panel.add(heightTextField);
heightTextField.setColumns(20);
heightTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
calculate();
}
});
JLabel lblArea = new JLabel("Area:");
lblArea.setBounds(244, 119, 75, 68);
panel.add(lblArea);
areaTextField = new JTextField();
areaTextField.setBounds(273, 143, 86, 20);
panel.add(areaTextField);
areaTextField.setColumns(20);
areaTextField.setEditable(false);
}
private void calculate() {
try {
double base = Double.parseDouble(baseTextField.getText());
double height = Double.parseDouble(heightTextField.getText());
double area = base * height;
areaTextField.setText(String.format("%.4f", area));
} catch (NumberFormatException e) {
areaTextField.setText("NaN");
}
}
}
Note that you need to hit the enter key in one of the two fields to update the area field. That is what it takes to trigger the ActionListener for a JTextField.

JTextPane not updating after values changed

Code is underneath. Basically what I'm trying to do is I have display going on in my JPanel of a JTextPane. I have a button that edits the value of the string that's supposed to be displayed in the JTextPane. I can't figure out how to update the JTextPane however. I've tried revalidate(), validate(), repaint(), none of those seemed to work.
The code is complete, it should be able to run.
import java.awt.Canvas;
public class windowBuild extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private int health = 20;
private int energy = 4;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
windowBuild frame = new windowBuild();
frame.setVisible(true);
}
});
}
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
String which = e.getActionCommand();
if (which.equals("Claw")){
energy = energy-1;
System.out.println("Player one's dragon clawed the opponent. Dragon's energy is now at: "+ energy);}
else if (which.equals("Wait")){
System.out.println("Turn succesfully skipped");}
System.out.println(getEnergy());
}
}
public windowBuild() {
ButtonHandler bh;
System.out.println("Starting frame...");
bh = new ButtonHandler();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 800, 600);
contentPane = new JPanel();
contentPane.setBorder(new TitledBorder(null, "Dragon Duel",
TitledBorder.CENTER, TitledBorder.TOP, null, Color.CYAN));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnClaw = new JButton("Claw");
btnClaw.setBounds(288, 511, 109, 39);
contentPane.add(btnClaw);
btnClaw.addActionListener(bh);
if (energy == 0)
btnClaw.setEnabled(false);
JButton btnWait = new JButton("Wait");
btnWait.setBounds(645, 511, 109, 39);
contentPane.add(btnWait);
btnWait.addActionListener(bh);
StringBuilder sb = new StringBuilder();
String strB = Integer.toString(health);
sb.append("H: ").append(strB).append("/20");
String healthString = sb.toString();
JTextPane txtpnH_1 = new JTextPane();
txtpnH_1.setEditable(false);
txtpnH_1.setFont(new Font("Impact", Font.PLAIN, 30));
txtpnH_1.setText(healthString);
txtpnH_1.setBounds(134, 511, 109, 39);
contentPane.add(txtpnH_1);
String strR = Integer.toString(energy);
String energyString = "E: ";
energyString += strR;
energyString += "/4";
JTextPane txtpnH = new JTextPane();
txtpnH.setEditable(false);
txtpnH.setText(energyString);
txtpnH.setFont(new Font("Impact", Font.PLAIN, 30));
txtpnH.setBounds(39, 511, 85, 39);
contentPane.add(txtpnH);
}
}
Thanks so much!!
Take the time to read through the Code Conventions for the Java Programming Language
Make use of appropriate layout managers, see A Visual Guide to Layout Managers and Using Layout Managers for more details
For what it's worth, use JTextField instead JTextPane, you're gaining little to no benefit by using JTextPane for what you seem to be trying to achieve. In fact, you might actually be better of us just using JLabel, seen as you don't want them to be editable
Avoid overriding top level containers, like JFrame, instead start with something like JPanel, build your UI on it and then deploy it to what ever top level container you want.
The problem you have is a reference issue. In the constructor of your windowBuild, you are defining all your UI components. This means that there is no way you can reference them anywhere else from with your program. Instead, make those components you need to reference else where instance fields.
public class WindowBuild extends JFrame {
//...//
private JTextPane txtpnH_1;
private JTextPane txtpnH;
//...//
public WindowBuild() {
//...//
txtpnH_1 = new JTextPane();
//...//
txtpnH = new JTextPane();
//...//
}
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
String which = e.getActionCommand();
// Now you can use txtpnH_1.setText and txtpnH.setText
}
}

Categories