What I don't like about my code below is:
getters are needed for every JButton on each page
the actionPerformed method can quickly become bloated with if-else statements
So, is there a better way to control all GUI actions from a single class?
If I define an actionPerformed method within each respective page (JPanel), each page will need access to instances of the page(s) switched to, and I am trying to avoid using the Singleton pattern for each page...
Here is the code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
*
* #author Ian A. Campbell
*
*/
public class Controller implements ActionListener {
/**
* instance variables:
*/
private Frame frame;
private OptionPage firstPage;
private FirstOptionPage firstOption;
private SecondOptionPage secondOption;
/**
*
*/
public Controller() {
// instantiating the frame here:
this.frame = new Frame();
/*
* instantiating all pages here:
*
* NOTE: passing "this" because this class
* handles the events from these pages
*/
this.firstPage = new OptionPage(this);
this.firstOption = new FirstOptionPage(this);
this.secondOption = new SecondOptionPage(this);
}
/**
*
*/
public void start() {
this.frame.add(this.firstPage); // adding the first page
// NOTE: these lines prevent blank loading and flickering pages!
this.frame.validate();
this.frame.repaint();
this.frame.setVisible(true);
}
/**
*
* #return the JFrame instantiated from the class Frame
*/
public Frame getFrame() {
return this.frame;
}
#Override
public void actionPerformed(ActionEvent e) {
// the "first option" button from the OptionPage:
if (e.getSource() == this.firstPage.getFirstButton()) {
this.frame.getContentPane().removeAll();
this.frame.getContentPane().add(this.firstOption);
// the "second option" button from the OptionPage:
} else if (e.getSource() == this.firstPage.getSecondButton()) {
this.frame.getContentPane().removeAll();
this.frame.getContentPane().add(this.secondOption);
}
// NOTE: these lines prevent blank loading and flickering pages!
this.frame.validate();
this.frame.repaint();
this.frame.setVisible(true);
}
} // end of Controller
Use a Card Layout. Card Layout Actions adds some extra features that you might find helpful.
You could use card layout, or you could get creative and remove elements. For instance:
panel.remove((JButton)myButton1)); // Remove all of the elements...
panel.add((JButton)myButton2)); // Add the new elements
Of course I wouldn't deal with the java built in GUI at all, IMO the layout designs are horrific. I would much rather use something like "A New Look and Feel" -- http://www.javootoo.com/.
Related
I cannot figure out why the following command does not work when the program calls the command. I dont have a very good background in Java, but as I understand it, the command should execute the print line statement when i press the button on the joystick that calls the command. Im not sure whether the problem may be that the command needs a Action listener or button listener somewhere, or whether I need to somehow relate the command to the same console. There should only be one recognized console it can print to, which i know works from other print line statements in the original program... right?
Here is the library which may help
THE PROGRAM:
/*--------------------------------------------------------------------------
--*/
/* Copyright (c) 2017-2018 FIRST. All Rights Reserved.
*/
/* Open Source Software - may be modified and shared by FRC teams. The code
*/
/* must be accompanied by the FIRST BSD license file in the root directory
of */
/* the project.
*/
/*--------------------------------------------------------------------------
--*/
package org.usfirst.frc.team5621.robot;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.Spark;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj.buttons.Button;
import edu.wpi.first.wpilibj.buttons.JoystickButton;
import edu.wpi.first.wpilibj.command.Command;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.drive.DifferentialDrive;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class Robot extends IterativeRobot {
private DifferentialDrive m_robotDrive
= new DifferentialDrive(new Spark(0), new Spark(1));
static Joystick m_stick = new Joystick(1);
private Timer m_timer = new Timer();
static Subsystem ExampleSubsystem;
Command ExampleCommand;
Command CompressCommand;
Command DecompressCommand;
Command OpenClawCommand;
Command CloseClawCommand;
Command CompressorToggleCommand;
public static class OI {
//Create Joystick and Buttons
static Joystick m_stick = new Joystick(1);
static Button button1 = new JoystickButton(m_stick, 1);
static Button button2 = new JoystickButton(m_stick, 2);
static Button button3 = new JoystickButton(m_stick, 3);
static Button button4 = new JoystickButton(m_stick, 4);
static Button button5 = new JoystickButton(m_stick, 5);
static Button button6 = new JoystickButton(m_stick, 6);
static Button button7 = new JoystickButton(m_stick, 7);
static Button button8 = new JoystickButton(m_stick, 8);
public OI() {
// Define Commands for Joystick Buttons
OI.button1.whileHeld(new CompressorToggleCommand());
OI.button2.whileHeld(new CompressCommand());
OI.button3.whileHeld(new DecompressCommand());
OI.button4.whileHeld(new OpenClawCommand());
OI.button5.whileHeld(new CloseClawCommand());
OI.button6.whileHeld(new ExampleCommand());
OI.button7.whileHeld(new ExampleCommand());
OI.button8.whileHeld(new ExampleCommand());
}
}
public class Compressor {
Compressor c = new Compressor();
}
public class Solenoid {
Solenoid exampleSolenoid = new Solenoid();
}
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
#Override
public void robotInit() {
}
/**
* This function is run once each time the robot enters autonomous mode.
*/
#Override
public void autonomousInit() {
m_timer.reset();
m_timer.start();
}
/**
* This function is called periodically during autonomous.
*/
#Override
public void autonomousPeriodic() {
// Drive for 2 seconds
if (m_timer.get() < 2.0) {
m_robotDrive.arcadeDrive(0.5, 0.0); // drive forwards half speed
} else {
m_robotDrive.stopMotor(); // stop robot
}
}
/**
* This function is called once each time the robot enters teleoperated mode.
*/
#Override
public void teleopInit() {
System.out.println("TeleOperated Mode Enabled");
}
/**
* This function is called periodically during teleoperated mode.
*/
#Override
public void teleopPeriodic() {
m_robotDrive.arcadeDrive(m_stick.getY(), m_stick.getX());
}
/**
* This function is called periodically during test mode.
*/
#Override
public void testPeriodic() {
}
}
THE COMMAND
/*----------------------------------------------------------------------------*/
/* Copyright (c) 2017-2018 FIRST. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package org.usfirst.frc.team5621.robot;
import edu.wpi.first.wpilibj.command.Command;
/**
* An example command. You can replace me with your own command.
*/
public class CompressCommand extends Command {
public CompressCommand() {
}
// Called just before this Command runs the first time
#Override
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
#Override
protected void execute() {
System.out.println("Compressing...");
exampleSolenoid.set(true);
}
// Make this return true when this Command no longer needs to run execute()
#Override
protected boolean isFinished() {
return false;
}
}
First off, I'd like to say that it's nice to see a fellow FRC programmer on Stack Overflow. Pertaining to your question, your problem may lie in the fact that you are declaring multiple public classes in the same file. This is very bad practice in Java programming. The problem you are looking to solve is here:
public OI() {
// Define Commands for Joystick Buttons
OI.button1.whileHeld(new CompressorToggleCommand());
OI.button2.whileHeld(new CompressCommand());
OI.button3.whileHeld(new DecompressCommand());
OI.button4.whileHeld(new OpenClawCommand());
OI.button5.whileHeld(new CloseClawCommand());
OI.button6.whileHeld(new ExampleCommand());
OI.button7.whileHeld(new ExampleCommand());
OI.button8.whileHeld(new ExampleCommand());
}
Once again, it is bad practice to have nested public classes, but what is really causing your problem is that you set the Button-On-Press actions for each button in the constructor of your OI class, but you never actually make an OI object, therefore the constructor is never called, and the code is never run. In your robotInit function, make an new OI object:
void robotInit() {
OI myOI = new OI();
}
Also remove the OI tag from your statements inside of the OI class. It is not needed. So that this:
OI.button1.whileHeld(new CompressorToggleCommand());
Becomes this:
button1.whileHeld(new CompressorToggleCommand());
I would also recommend moving all of your object initializations to robotInit. I would suggest making all of your many nested classes each in their own file, and be sure to make objects of all of these classes in your main Robot class. I would also suggest reading up on some basic Object Oriented Programming concepts such as how constructors work, as well as how to use classes and objects in Java. Also maybe read up on the FRC functions you are using in the FRC API Reference
I have a Java Application, I am wanting to format a button as either Active or Inactive (Also possibly a hover method).
The code as I would like to implement it:
//Home Tab - Active by default
home = new TabButton();
home.setSize(new Dimension(tabWidth, tabHeight));
home.setFont(getLauncherFont(34));
home.setForeground(Color.white);
home.setText("HOME");
home.setBounds(160, 0, tabWidth, tabHeight);
home.setActive(); --> This Method is what I would like to create
I already have a class to create a JButton for the tab:
package com.anarcist.minemodloaderv1.skin.components;
import java.awt.Color;
import javax.swing.JButton;
/**
*
* #author anarcist
*/
public class TabButton extends JButton {
public TabButton() {
this.setBorderPainted(false);
this.setFocusPainted(false);
this.setContentAreaFilled(true);
this.setBackground(Color.blue);
}
}
I have researched abstract classes. But my TabButton class already extends JButton.
I would like a method like this:
public void setActive(){
this.setBackground(Color.red);
//Any other changes a want to make regularly
}
That can simply be implemented like this home.setActive();
My Question I suppose is: Is it easy enough to implement what I am looking for, or will I have to got the long way and set all attributes manually every time?
What you've described in the post can be done like this:
package com.anarcist.minemodloaderv1.skin.components;
import java.awt.Color;
import javax.swing.JButton;
/**
*
* #author anarcist
*/
public class TabButton extends JButton {
public TabButton() {// initialize
this.setBorderPainted(false);
this.setFocusPainted(false);
this.setContentAreaFilled(true);
this.setBackground(Color.blue);
}
// add your own methods or override JButton methods
public void setActive(){
//Add code
//example: setEnabled(true);
}
}
I have a panel where the user will search for a customer by entering a surname or ID. I want to implement some kind of table that displays each row of SQL query results. What's the best way to do this? The first thing that comes to my mind would be to use a multi-dimensional array and a JTextArea. What do you think?
Have you looked into a JTable?
Edit: This is my first time replying so I guess I'll notice when I do something wrong. I have recently created something similar to what you are aiming for, so this piece of code might set you on your way:
String[][] results = null;
if(query != null){
results = domeinController.Search(query);
} else {
results = domeinController.ReturnAllAccounts();
txtSearch.setText("");
}
TableModel table = new DefaultTableModel(results, new String[] {d("LBL_SERVICE"), d("LBL_ACC_NAME"), d("LBL_PASSWORD"), d("LBL_EMAIL")});
tblResults = new JTable(){
public boolean isCellEditable(int roxIndex, int colIndex){
return false;
}
};
jScrollPane1.setViewportView(tblResults);
tblResults.setModel(table);
tblResults.setAutoCreateRowSorter(true);
tblResults.setBounds(55, 145, 423, 228);
tblResults.getTableHeader().setAutoscrolls(true);
tblResults.getTableHeader().setReorderingAllowed(false);
tblResults.getTableHeader().setResizingAllowed(false);
tblResults.setShowVerticalLines(false);
tblResults.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent evt) {
tblResultsMousePressed(evt);
}
});
Basically you create a tableModel with a 2D Array of data as your 1st parameter, and an array with headers for your 2nd parameter. After that you can specify behaviour to your table.
I highly recommend taking Glazed List into account.
It's a library which takes care of the most of the heavylifting related to presenting tabular data in a table with both filtering and sorting. It also provides a multithreading-safe datamodel. Using bare Swing and Java it's a lot lot harder to implement it all correctly.
Here is a nice tutorial provided. Once anybody starts writing CRUD GUIs, sooner or later all end up wanting so called "standard features" which all table oriented guis share in common. Why wasting time inventing it all and risking making a lot of mistakes, when you can build upon proven solutions. Especially, when it's so easy.
An example, displaying a XML based JTable:
import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
// a simple issues library
import ca.odell.issuezilla.*;
// glazed lists
import ca.odell.glazedlists.*;
import ca.odell.glazedlists.swing.*;
/**
* An IssueBrowser is a program for finding and viewing issues.
*
* #author <href="mailto:jesse#odel.on.ca">Jesse Wilson</a>
*/
public class IssuesBrowser {
/** event list that hosts the issues */
private EventList issuesEventList = new BasicEventList();
/**
* Create an IssueBrowser for the specified issues.
*/
public IssuesBrowser(Collection issues) {
issuesEventList.addAll(issues);
}
/**
* Display a frame for browsing issues.
*/
public void display() {
// create a panel with a table
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
EventListModel issuesListModel = new EventListModel(issuesEventList);
JList issuesJList = new JList(issuesListModel);
JScrollPane issuesListScrollPane = new JScrollPane(issuesJList);
panel.add(issuesListScrollPane, new GridBagConstraints(...));
// create a frame with that panel
JFrame frame = new JFrame("Issues");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(540, 380);
frame.getContentPane().add(panel);
frame.show();
}
/**
* Launch the IssuesBrowser from the commandline.
*/
public static void main(String[] args) {
if(args.length != 1) {
System.out.println("Usage: IssuesBrowser <file>");
return;
}
// load some issues
Collection issues = null;
try {
IssuezillaXMLParser parser = new IssuezillaXMLParser();
InputStream issuesInStream = new FileInputStream(args[0]);
issues = parser.loadIssues(issuesInStream, null);
issuesInStream.close();
} catch(IOException e) {
e.printStackTrace();
return;
}
// create the browser
IssuesBrowser browser = new IssuesBrowser(issues);
browser.display();
}
}
Consider you have the following code in a Timer:
It's main goal is to count down the seconds and to show it on GUI, which is Swing based.
The Timer is part of the game and is used for a decision of who is the winner by taking the user who reached a solution first.
Action updateClockAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
JLabel secLabel = m_GameApplet.GetJpanelStartNetGame().GetJlabelSeconds();
secLabel.setFont(new java.awt.Font("Lucida Handwriting", 1, 36));
secLabel.setForeground(Color.red);
secLabel.setText(Integer.toString(m_TimerSeconds));
if (m_TimerSeconds > 0) {
m_TimerSeconds--;
} else if (m_TimerSeconds == 0) {
m_Timer.stop();
m_GameApplet.GetJpanelStartNetGame().GetJlabelSeconds().setText("0");
m_GameApplet.GetJpanelStartNetGame().GetJbuttonFinish().setVisible(false);
//Checking whether time ended for both players and no solution was recieved
if (!m_WasGameDecisived) {
System.out.println("Tie - No one had a solution in the given time");
}
}
}
};
m_Timer = new Timer(1000, updateClockAction);
Now, I have two main packages in the client implementation
A.GUI - hold all the swing Jpanels etc.
B.LogicEngine
Now in LogicEngine I have a class that is called GameManager- that should manage and store information about the game.
My Current implementation in general is like this:
I have a JpanelMainGame which is on the GUI Package
JpanelMainGame contains JPanelGameBoard which has reference(or in other word contains) an instance of GameManger, which is on different package - The LogicEngine package.
So my questions are these:
Where does all of the timer definition code above should be placed?
A. In the JpanelMainGame? (JpanelMainGame should have a reference to it).
B. In GameManger as a part of a data of the game
In each solution you give, How should I access all the label info from within the anonymous inner class? As I can only access member from the outer class with command: OuterClass.this.member.
Any comments about current design.
Thank you very much
I repeat the answer I gave on another question:
I strongly discourage from organizing packages from an implementational point of view, like controllers, data, etc. I prefer grouping them by functionality, that is, feature1, feature2, etc. If a feature is reasonably complex and requires a large number of classes, then (and only then) I create subpackages like above, that is, feature1.controllers, feature1.data, etc.
Well not to answer questions with questions, but...
How often is Timer used?
Is Timer coded to be general use, or specific to a certain class?
If the Timer is general use, then I would say it belongs in the LogicEngine package tree somewhere. However, if Timer can only be used in a GUI element, then it belongs in the GUI package tree.
As a general rule of thumb (not to bang on the Agile drum too hard), you should only code what makes sense now but not be afraid to change it later.
Example: You are making an anonymous inner class of the type AbstractAction() in your code. This is just fine (although I shy away from anon classes) if the updateClockAction variable is used simply. But once your coding leads you to the need to cross the boundries of updateClockAction (via OuterClass.this.member) then I assert its time for a bit of refactoring: extract this inner class and make it a fully qualified class. This way, you can have the proper amount of control over the updateClockAction object's internal state (using the cstr, getters, etc)
EDIT: Added requested example
public class Testing {
private Timer timer; /* INIT this from somewhere.... */
public void myFunction() {
/* 60 Seconds */
long countDownTimeSEC = 60;
/* convert to Miliseconds */
long countDownTimeMS = 1000 * countDownTimeSEC;
/* Get ref to label */
JLabel label = m_GameApplet.GetJpanelStartNetGame().GetJlabelSeconds();
/* Set once */
label.setFont(new java.awt.Font("Lucida Handwriting", 1, 36));
label.setForeground(Color.red);
/* Set initial time */
label.setText(Long.toString(countDownTimeSEC));
/* Get ref to button */
JButton button = m_GameApplet.GetJpanelStartNetGame().GetJbuttonFinish();
/* Set up post Count Down list */
ArrayList<AbstractAction> actsWhenComplete = new ArrayList<AbstractAction>();
/* instantiate countdown object */
CountDownClockAction cdca = new CountDownClockAction(label, countDownTimeMS, actsWhenComplete);
this.timer = new Timer(1000, cdca);
/* Now that we have a timer, add the post Count Down action(s) to the post Count Down list */
actsWhenComplete.add(new CountDownFinishAction(label, button, this.timer));
/* Finally, kick off the timer */
this.timer.start();
}
public static class CountDownClockAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private final JLabel labelToUpdate;
private final long startMS;
private long currentMS;
private long timeMark;
private final ArrayList<AbstractAction> actionsToExeWhenComplete;
private boolean actionsExedFlag;
public CountDownClockAction(
final JLabel labelToUpdate,
final long startMS,
ArrayList<AbstractAction> actionsToExeWhenComplete
) {
super();
this.labelToUpdate = labelToUpdate;
this.startMS = startMS;
this.currentMS = startMS;
this.timeMark = 0;
this.actionsExedFlag = false;
this.actionsToExeWhenComplete = actionsToExeWhenComplete;
}
#Override
public void actionPerformed(final ActionEvent e) {
/* First time firing */
if (this.timeMark == 0)
this.timeMark = System.currentTimeMillis();
/* Although the Timer object was set to 1000ms intervals,
* the UpdateClockAction doesn't know this, nor should it
* since > or < 1000ms intervals could happen to do the fact that
* the JVM nor the OS have perfectly accurate timing, nor do they
* have instantaneous code execution properties.
* So, we should see what the *real* time diff is...
*/
long timeDelta = System.currentTimeMillis() - this.timeMark;
/* Allow for the label to be null */
if (this.labelToUpdate != null)
labelToUpdate.setText(Long.toString((long)(currentMS / 1000)));
if (currentMS > 0) {
currentMS -= timeDelta;
} else if (currentMS <= 0 && this.actionsExedFlag == false) {
/* Ensure actions only fired once */
this.actionsExedFlag = true;
/* Allow for the label to be null */
if (this.actionsToExeWhenComplete != null)
for (AbstractAction aa: this.actionsToExeWhenComplete)
aa.actionPerformed(e);
}
/* Finally, update timeMark for next calls */
this.timeMark = System.currentTimeMillis();
}
}
public static class CountDownFinishAction extends AbstractAction {
private final JLabel labelToUpdate;
private final JButton buttonToUpdate;
private final Timer timerToStop;
public CountDownFinishAction(
JLabel labelToUpdate,
JButton buttonToUpdate,
Timer timerToStop
) {
super();
this.labelToUpdate = labelToUpdate;
this.buttonToUpdate = buttonToUpdate;
this.timerToStop = timerToStop;
}
#Override
public void actionPerformed(final ActionEvent e) {
/* Perform actions, allowing for items to be null */
if (this.labelToUpdate != null)
this.labelToUpdate.setText("0");
if (this.buttonToUpdate != null)
this.buttonToUpdate.setVisible(false);
if (this.timerToStop != null)
this.timerToStop.stop();
}
}
}
K, so unlike with my last question, I've been proactive about trying to deal with this problem a number of times, and it's still not working.
Basically I'm trying implement a JTextField. I've added the action listener to it and the getters and setters for the text are working, but text that I'm enter isn't showing up in the textfield. I tried setting the text color to black and that didn't help. Honestly, I'm not sure what the issue is.
K here's the code.
import acm.program.*;
import java.awt.event.*;
import javax.swing.*;
public class NameSurfer extends Program implements NameSurferConstants {
//Change back to program after this
/* Method: init() */
/**
* This method has the responsibility for reading in the data base
* and initializing the interactors at the bottom of the window.
*/
public void init() {
// You fill this in, along with any helper methods //
createUI();
addActionListeners();
}
/* Method: actionPerformed(e) */
/**
* This class is responsible for detecting when the buttons are
* clicked, so you will have to define a method to respond to
* button actions.
*/
public void actionPerformed(ActionEvent e) {
// You fill this in //
if(e.getSource() == nameField || e.getSource() == graphName) {
drawNameGraph(nameField.getText());
} else if(e.getSource() == clearGraph) {
clearNameGraph();
}
}
/* Method: createUI() */
/**
* This method sets up and adds the interactors at the bottom of the window*/
private void createUI() {
nameField = new JTextField(25);
nameField.setColumns(25);
nameField.addActionListener(this);
graphName = new JButton("Graph");
clearGraph = new JButton("Clear");
graph=new NameSurferGraph();
add(new JLabel("Name"), SOUTH);
add(nameField, SOUTH);
add(graphName, SOUTH);
add(clearGraph, SOUTH);
add(graph);
//println(db.fileEntries.size());
}
/* Method: drawNameGraph(str) */
/** Draws the graph of the name entered in nameField
* */
private void drawNameGraph(String str) {
//println(str);
NameSurferEntry entered = db.findEntry(str);
if(entered != null) {
//println("Graph: " + entered.toString());
graph.addEntry(entered);
nameField.setText("str");
} else {
graph.badEntry(str);
}
//nameField.setText("");
}
/* Method: clearNameGraph() */
private void clearNameGraph() {
graph.clear();
}
private NameSurferDataBase db = new NameSurferDataBase(NAMES_DATA_FILE);
/**TextField where the names get entered*/
private JTextField nameField;
/**button to graph name popularity*/
private JButton graphName;
/**Clears graph*/
private JButton clearGraph;
private NameSurferGraph graph;
}
Also I'm going to try to explain my question better using images. Sorry if this don't work on your OS. Their .tiffs but I'll try to run them through image conversion later on. For some reason, stackoverflow isn't letting me post the images in question, so I'm going to try to do some links to them instead through some other site. Sorry for the inconvenience.
When I run the code, this is displayed.
See the image for that here.
Basically so far it works as expected.
The problem arises
here.
The getters and setters are working, but I'ld like to have the JTextField updated when the user enters the text, as opposed to not displaying anything that I've got entered in it.
Are you trying to do this?!?
JTextField text = new JTextField();
text.setText("ttttttttttttexxxt");
Quoting from the the Java 6 API on JTextField:
public JTextField()
Constructs a new TextField. A default model is created, the initial string is null, and the number of columns is set to 0.
(Emphasis added.)
If you are using a default constructor, then if you have not called setColumns(int), your JTextField has a column limit of 0 (regardless of the text field's width) and therefore will refuse all input from the user. I am inferring you are having trouble entering text as a user when the program is running, rather than trouble setting the text within the program and causing it to display?
Either use a form of the constructor that has a column limit, or use setColumns to specify a nonzero maximum after construction.
If this doesn't solve the issue, please provide a code sample, especially where you are constructing and initializing your JTextField.
The text is always defaulted to black so there no need to play with anything except setText.
There are a number of things you could be asking here so.
To set the text on load simply use setText at the top of your code.
public TestFrame() {
initComponents();
jTextField1.setText("Hello I am text in a box");
}
You can also have it respond to an event in the following way. Example is a button click.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//Text Box changes from default
jTextField1.setText("The button was pushed!!");
}
Notice that it is all the same, I feel like you are making it a little more complicated than it actually is.
Use a normal TextField instead of a JTextfield. According to this post that was the issue. I'm not a specialist, but I have encountered the exact same problem, and it seems to be linked to the usage of the ACM library.