How to across JTextField to next JTextField by hit Enter - java

When select check box to set enable(false) on second text field and hit enter need to focus at third text field
if not select any check box then hit ENTER it can be focus on text field as flow.
I should add any code or how can I make it work
My GUI:
private void chk1ActionPerformed(java.awt.event.ActionEvent evt) {
// Set action perform for check box:
if(chk1.isSelected()){
p1.setEnabled(false);
} else{
p1.setEnabled(true);
}
}
private void chk2ActionPerformed(java.awt.event.ActionEvent evt) {
// Set action perform for check box:
if(chk2.isSelected()){
p2.setEnabled(false);
} else{
p2.setEnabled(true);
}
}
private void chk3ActionPerformed(java.awt.event.ActionEvent evt) {
// Set action perform for check box:
if(chk3.isSelected()){
p3.setEnabled(false);
} else{
p3.setEnabled(true);
}
}
private void p_numKeyPressed(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
if(evt.getKeyCode()==KeyEvent.VK_ENTER){
p1.requestFocus();
}
}
private void p1KeyPressed(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
if(evt.getKeyCode()==KeyEvent.VK_ENTER){
p2.requestFocus();
}
}
private void p2KeyPressed(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
if(evt.getKeyCode()==KeyEvent.VK_ENTER){
p3.requestFocus();
}
}

I think what you are looking for is the Focus Subsystem. This is responsible for the order in which components are getting focus when you press a focus traversal key. For example you can define what is the order of the components to get focus, and also add the check to transfer focus only to enabled components. What you also seem to want to do is to add the ENTER key as a focus traversal key (ie when pressing it, the focus will be transfered to another component - according to the current focus traversal policy). All this can be done via the focus subsystem.
The following code seems to do what you are asking, by utilizing the focus subsystem:
import java.awt.Component;
import java.awt.Container;
import java.awt.DefaultFocusTraversalPolicy;
import java.awt.GridLayout;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
public class FocusHopSystem {
public static class AbsoluteFocusTraversalPolicy extends DefaultFocusTraversalPolicy {
private final Component[] comps;
public AbsoluteFocusTraversalPolicy(final Component... comps) {
this.comps = comps.clone();
}
private int indexOf(final Component comp) {
for (int i = 0; i < comps.length; ++i)
if (comps[i] == comp)
return i;
return -1;
}
#Override
public Component getComponentAfter(final Container aContainer, final Component aComponent) {
final int aIndex = indexOf(aComponent);
if (aIndex < 0)
return null;
for (int i = 1; i < comps.length; ++i) {
final Component after = comps[(aIndex + i) % comps.length];
if (after != null && after.isDisplayable() && after.isVisible() && after.isEnabled())
return after;
}
return null;
}
#Override
public Component getComponentBefore(final Container aContainer, final Component aComponent) {
final int aIndex = indexOf(aComponent);
if (aIndex < 0)
return null;
for (int i = 1; i < comps.length; ++i) {
final Component before = comps[(aIndex - i + comps.length) % comps.length];
if (before != null && before.isDisplayable() && before.isVisible() && before.isEnabled())
return before;
}
return null;
}
#Override
public Component getFirstComponent(final Container aContainer) {
for (int i = 0; i < comps.length; ++i) {
final Component first = comps[i];
if (first != null && first.isDisplayable() && first.isVisible() && first.isEnabled())
return first;
}
return null;
}
#Override
public Component getLastComponent(final Container aContainer) {
for (int i = comps.length - 1; i >= 0; --i) {
final Component last = comps[i];
if (last != null && last.isDisplayable() && last.isVisible() && last.isEnabled())
return last;
}
return null;
}
#Override
public Component getDefaultComponent(final Container aContainer) {
return getFirstComponent(aContainer);
}
}
private static void createAndShowGUI() {
final String text = "0";
final int width = 12;
final JTextField tf1 = new JTextField(text, width),
tf2 = new JTextField(text, width),
tf3 = new JTextField(text, width),
tf4 = new JTextField(text, width);
final JCheckBox ck2 = new JCheckBox("jTextField2", true),
ck3 = new JCheckBox("jTextField3", true),
ck4 = new JCheckBox("jTextField4", true);
final JButton save = new JButton("Save");
ck2.addActionListener(e -> tf2.setEnabled(ck2.isSelected()));
ck3.addActionListener(e -> tf3.setEnabled(ck3.isSelected()));
ck4.addActionListener(e -> tf4.setEnabled(ck4.isSelected()));
final JPanel frameContents = new JPanel(new GridLayout(0, 5, 5, 5));
//First row:
frameContents.add(new JPanel());
frameContents.add(ck2);
frameContents.add(ck3);
frameContents.add(ck4);
frameContents.add(new JPanel());
//Second row:
frameContents.add(tf1);
frameContents.add(tf2);
frameContents.add(tf3);
frameContents.add(tf4);
frameContents.add(save);
//Make the other components unfocusable:
for (final Component comp: new Component[]{ck2, ck3, ck4, save})
comp.setFocusable(false);
//Make frameContents the focus cycle root:
frameContents.setFocusCycleRoot(true);
//Install our FocusTraversalPolicy to the cycle root:
frameContents.setFocusTraversalPolicy(new AbsoluteFocusTraversalPolicy(tf1, tf2, tf3, tf4));
//Add KeyEvent.VK_ENTER key to the focus traversal keys of the frameContents:
final Set forwardKeys = frameContents.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS);
final Set newForwardKeys = new HashSet(forwardKeys);
newForwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0));
frameContents.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, newForwardKeys);
final JFrame frame = new JFrame("Focus traversal test.");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(frameContents);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
//Start focus on the first text field:
tf1.requestFocusInWindow();
}
public static void main(final String[] args) {
SwingUtilities.invokeLater(FocusHopSystem::createAndShowGUI);
}
}
In the above example, I am adding the key ENTER as an alternative focus traversal key, aside from TAB.
Edit 1: It's even simpler...
As I found out, it's even simpler than the first sample code, and that's because the default focus traversal policy does what you are asking, ie allows only focusable-and-enabled components to gain focus and in the desired order. So we only need to make the unneeded components to non-focusable (ie the check-boxes and the button) and leave enabled the text-fields. Just add/set the ENTER key as a focus traversal key and you are good to go:
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.KeyboardFocusManager;
import java.awt.event.KeyEvent;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
public class FocusHopSystem2 {
private static void createAndShowGUI() {
final String text = "0";
final int width = 12;
final JTextField tf1 = new JTextField(text, width),
tf2 = new JTextField(text, width),
tf3 = new JTextField(text, width),
tf4 = new JTextField(text, width);
final JCheckBox ck2 = new JCheckBox("jTextField2", true),
ck3 = new JCheckBox("jTextField3", true),
ck4 = new JCheckBox("jTextField4", true);
final JButton save = new JButton("Save");
ck2.addActionListener(e -> tf2.setEnabled(ck2.isSelected()));
ck3.addActionListener(e -> tf3.setEnabled(ck3.isSelected()));
ck4.addActionListener(e -> tf4.setEnabled(ck4.isSelected()));
final JPanel frameContents = new JPanel(new GridLayout(0, 5, 5, 5));
//First row:
frameContents.add(new JPanel());
frameContents.add(ck2);
frameContents.add(ck3);
frameContents.add(ck4);
frameContents.add(new JPanel());
//Second row:
frameContents.add(tf1);
frameContents.add(tf2);
frameContents.add(tf3);
frameContents.add(tf4);
frameContents.add(save);
//Make the other components unfocusable:
for (final Component comp: new Component[]{ck2, ck3, ck4, save})
comp.setFocusable(false);
//Make frameContents the focus cycle root:
frameContents.setFocusCycleRoot(true);
////Install the DefaultFocusTraversalPolicy to the cycle root:
//frameContents.setFocusTraversalPolicy(new DefaultFocusTraversalPolicy()); //This is not necessary in this case.
//Add KeyEvent.VK_ENTER key to the focus traversal keys of the frameContents:
final Set forwardKeys = frameContents.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS);
final Set newForwardKeys = new HashSet(forwardKeys);
newForwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0));
frameContents.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, newForwardKeys);
final JFrame frame = new JFrame("Focus traversal test.");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(frameContents);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
//Start focus on the first text field:
tf1.requestFocusInWindow();
}
public static void main(final String[] args) {
SwingUtilities.invokeLater(FocusHopSystem2::createAndShowGUI);
}
}
You may also read The AWT Focus Subsystem.

This is the way the Tab key works by default. When you press Tab focus will move to the next enabled component.
If you want to duplicate this functionality for the Enter key then first you can create a custom Action
Action transfer = new AbstractAction()
{
#Override
public void actionPerformed(ActionEvent e)
{
Component c = (Component)e.getSource();
c.transferFocus();
}
};
By default the "Enter" key will invoke the ActionListener added to the text field. So, now you can add this Action to specific text fields:
...
textField1.addActionListener( transfer );
textField2.addActionListener( transfer );
Or you can replace the default Enter Action of all the text fields by adding your custom Action to the ActionMap:
...
ActionMap am = (ActionMap)UIManager.get("TextField.actionMap");
am.put("notify-field-accept", transfer);

Related

Trying to use 1 action listener for multiple buttons

So I am trying to code a jeopardy game, but the catch is that I am only trying to assign my buttons to 1 action listener so that all buttons function on their own yet work from 1 action listener.
I've tried a lot, nothing works!
package jep;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
public class jep implements ActionListener{
public JButton[][] t = new JButton[6][6];
public static void main(String[] args) {
new jep();
}
static int n = 100;
public jep() {
JFrame frame = new JFrame("Jeopardy");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1920,1080);
frame.setLayout(new GridLayout(6, 5));
frame.setVisible(true);
for (int r = 0; r < 6; r++) {
for (int c = 0; c < 5; c++) {
String vakue = String.valueOf(n);
t[r][c] = new JButton(vakue);
t[r][c].setBackground(Color.BLUE);
t[r][c].setForeground(Color.YELLOW);
t[r][c].addActionListener(this);
frame.add(t[r][c]);
}
n = n +300;
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
I am trying to get it so that i can click multiple buttons using only 1 action listener but all i can get is a grid
Here is the corrected code with print to console on button press. Please, check the comments in the code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Jep implements ActionListener { // class name has to start with a capital letter
int i = 6;
int j = 5;
public JButton[][] t = new JButton[i][j];
public static void main(String[] args) {
new Jep();
}
static int n = 100;
public Jep() {
JFrame frame = new JFrame("Jeopardy");
JPanel[][] panelHolder = new JPanel[i][j]; // use panels to add you buttons, check this for details:
// https://stackoverflow.com/questions/2510159/can-i-add-a-component-to-a-specific-grid-cell-when-a-gridlayout-is-used
frame.setLayout(new GridLayout(i, j));
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1920, 1080);
frame.setVisible(true);
for (int r = 0; r < 6; r++) {
for (int c = 0; c < 5; c++) {
String vakue = String.valueOf(n);
t[r][c] = new JButton(vakue);
t[r][c].setBackground(Color.BLUE);
t[r][c].setForeground(Color.BLACK);
t[r][c].addActionListener(this);
panelHolder[r][c] = new JPanel();
panelHolder[r][c].add(t[r][c]);
frame.add(panelHolder[r][c]);
n = n + 300;
}
}
}
#Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("press, value = " + arg0.getActionCommand()); // here is a simple system out log statement
}
}
Output(when you press several buttons):
press, value = 100
press, value = 400
press, value = 700
press, value = 1000
press, value = 1300
press, value = 1600
App Winodow:
Hope this will help.
You can use AbstractButton (superclass of JButton).setActionCommand, and then in your listener using action command you can figure out your row and column
Instead of creating a 6 x 6 array of JButtons, you ought to use JTable, set the renderer to render your cells values as buttons (or something else) and as recommended here add a listSelectionListener to the tablemodel to get the row and the column values on click. As recommended here: Get position of Click JTable while using Cell renderer
Learning JTable and how to use renders etc can take a little time. But I assume that for this question you are in a learning environment anyway, that this is not something being done for business, or? So I would recommend you take the time to learn JTable. You will end up being much happier with your final product I promise you.

problems with swing timer

I'm creating an speed reader so I'm using a swingx.Timer object to display the words at a given time.I set the time to 1sec for testing. I had the code working before but then after closing eclipse and coming back to it the code doesn't work anymore. The timer does not call the actionlistener thus not performing the action it is supposed to perform. Here is my code. I read other questions talking about timer being a daemon thread and ending with main. However I don't think this is the case in my code but I could be wrong. Can someone help me point out my error?
package reader;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTextPane;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JMenu;
import java.awt.event.*;
import java.io.IOException;
import java.sql.Time;
import javax.swing.Timer;
public class ReaderPad extends JPanel{
public JButton startBtn, stopBtn, resetBtn;
public JList speedMenu;
public JMenuBar topMenu;
public JTextPane textPad;
public JScrollPane scroll;
public Timer timer;//to control the speed of the reader
public int speed; //the speed set for the reader, i.e. 100 words per minute
public JLabel speedLabel;
public JTextField speedText;
int wordLength; //size of text
String[] lines; //a line of text composed of 10 words from the text entered
int wpm;
int i;//index of word set being used
public ReaderPad(){
this.setLayout(new BorderLayout());
i = 0;
speedLabel = new JLabel("words per minute");
speedText = new JTextField();
speedText.setColumns(3);
startBtn = new JButton("Start");
stopBtn = new JButton("Stop");
resetBtn = new JButton("Reset");
textPad = new JTextPane();
topMenu = new JMenuBar();
textPad.setEditable(true);
textPad.setFont(new Font("Serif", Font.PLAIN,25));
textPad.setText("welcome to speed reader. Use CTRL + c to paste your text\n"
+ "Press start to begin");
scroll = new JScrollPane(textPad);
//create top menu bar
topMenu.add(startBtn);
topMenu.add(stopBtn);
topMenu.add(resetBtn);
topMenu.add(speedLabel);
topMenu.add(speedText);
//topMenu.add(speedMenu);
this.add(topMenu, BorderLayout.NORTH);
this.add(scroll, BorderLayout.CENTER);
//set listeners for buttons
Actions listener = new Actions();
startBtn.addActionListener(listener);
stopBtn.addActionListener(listener);
resetBtn.addActionListener(listener);
}//end of constructor
public void setFontSize(String size){
Font font = textPad.getFont();
String s = font.getName();
textPad.setFont(new Font(s, Font.PLAIN, Integer.valueOf(size)));
}
public void setFontColor(String color){
}
//sets background color
public void setBackgroud(String color){
}
public void setSpeed(String speed){
//speed = speed.replace("X", "");//remove the times symbol
if(speed.isEmpty())//set default
this.speed = 100;
else
this.speed = Integer.valueOf(speed);
}
public int getSpeed(){
return this.speed;
}
public void startReader(){//words per minute
int speed = getSpeed();//wpm selected by the user
System.out.println("speed: " + speed);
String text = textPad.getText();
// System.out.println(text);
lines = text.split(" ");
wordLength = lines.length;//get the number of words in the text
System.out.println("length: "+ wordLength);
//System.out.println(wordLength.length);
if(text.isEmpty()){
textPad.setText("You didn't enter any text in the text area.\n"
+"Please enter some text to begin.");
}
else{//set timer
//calculate speed first: time = (speed chosen * number of workds in text) = (sec/words)*wordsize
//wpm = (1/speed)*wordLength*60*1000; //multiply by 60 secons
wpm = 1000;
System.out.println("wpm: "+ wpm);
TimerReader counter = new TimerReader();
timer = new Timer(1000, counter);
timer.start();
System.out.println(timer.isRunning());
}
}
public void stopReader(){
}
//listener class
public class Actions implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
String source = e.getActionCommand();//read the button asking for the request
if(source.equals("Reset")){
textPad.setText("");
if(timer.isRunning())
timer.stop();
}
else if(source.equals("Start")){
//first read the speed selected and set the speed
setSpeed(speedText.getText());
startReader();
}
else if (source.equals("Stop"))
i = 0;
timer.stop();
}
}
public class TimerReader implements ActionListener{
#Override
public void actionPerformed(ActionEvent e){
//once the timer is called the textpad starts displaying the words
String s = lines[i];
i++;
textPad.setText(s);
System.out.println(i);
System.out.println(e.getActionCommand());
System.out.print(textPad.getText());
}
}//end of inner class
}//end of ReaderPad class
Remove timer.stop() from the end of Actions actionPerformed method...
public class Actions implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String source = e.getActionCommand();//read the button asking for the request
if (source.equals("Reset")) {
textPad.setText("");
if (timer.isRunning()) {
timer.stop();
}
} else if (source.equals("Start")) {
//first read the speed selected and set the speed
setSpeed(speedText.getText());
startReader();
} else if (source.equals("Stop")) {
i = 0;
}
// This is stopping the timer AFTER it was already started
//timer.stop();
}
}

Buttons do not appear in my GUI when opening a new window in a new class

I am making a vocabulary quiz program and when they click an option, a new window is supposed to pop up saying if they got it right or wrong. That works, but what doesn't show is the button in the window when it gives you the option to go back to the quiz, ruining the chance to continue onto the next question, or even worse, answering the current question.
Here is the main quiz code:
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.DataFormatter;
public class SAT extends JFrame implements ActionListener{
private JButton buttonA;
private JButton buttonB;
private JButton buttonC;
private JButton buttonD;
private JPanel panel1;
private JFrame frame1;
private JTextField Text1;
private JLabel label1;
public static final String POOP = "Words3.xls"; //everywhere that there is POOP is the excel sheet
public static String read1(int rowIndex, int colIndex, int a)
{
String value = new String();
HSSFWorkbook wb = null;
try {
wb = new HSSFWorkbook(new FileInputStream(POOP));
} catch (Exception e) {
e.printStackTrace();
}
String sheet2=null;//placeholder
if (a==1){sheet2="SAT";}//one of these for each sheet
if (a==2){sheet2="Test";}
if (a==3){sheet2="vwlvlHU1";}
HSSFSheet sheet = wb.getSheet(sheet2);
HSSFRow row=sheet.getRow(rowIndex-1);
HSSFCell cell=row.getCell(colIndex-1);
DataFormatter formatter = new DataFormatter();
value = formatter.formatCellValue(cell);
return value;
}
private static void saveWorkbook(HSSFWorkbook wb) throws IOException
{
FileOutputStream out = new FileOutputStream(POOP);
wb.write(out);
out.close();
}
public static int RNG1(int a) { //this RNG is used to find the word and random definitions
//RNG code:
int min=1;//1
int max=100;//number of flash cards, highest number, this is a placeholder
if (a==1){max=253;}//we will have one of these statements for each set
if (a==2){max=20;}
if (a==3){max=40;}
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min + 1;//the +1 is so it doesn't choose header, maybe remove
return randomNum;
}
public static int RNG2(int b) {//this RNG will be used to determine which button gets true definition
//RNG code:
int min=1;//1
int max=4;//number of options
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
//FIND THE WORD AND POS
int a=1;//tells methods to look in right set
int rowIndex=RNG1(a);//here is where a random word, pos, and def will be called for
int colIndex=1;//use colIndex=1 to show word
String WORD=read1(rowIndex,colIndex,a);//to pull word
//System.out.println("Word: "+WORD);
int colIndexPOS=2;//POS=part of speech/colIndexPOS=2 for part of speech
String POS=read1(rowIndex,colIndexPOS,a);
//System.out.println("Part of speech: "+POS);
int b=1;//placeholder
int location=RNG2(b);
//if location=1, put it in button 1 and have random definitions for other 3
//if location=2... same for 3 and 4
private String def(){
//TRUE DEFINITION:
int colIndexDEF=3;//DEF= definition/colIndexPOS=3 for definitions
String DEF=read1(rowIndex,colIndexDEF,a);
return DEF;
}
//FAKE DEFINITIONS:
//fake def 1:
private String rdef1(){//THIS BLOCK HAS AN ISSUE. SHOULD NOT BE DIVIDED BY CURLY BRACES BUT IT IS AN ERROR IF THEY ARE NOT THERE. MAYBE MAKE IT A METHOD?
int rowIndex1=0;//null value
int colIndexDEF=3;
String weirdo="WHY";
do{
rowIndex1=RNG1(a);
weirdo=read1(rowIndex1, colIndexPOS, a);
}while(rowIndex1==rowIndex || !weirdo.equals(POS));
String RANDDEF1=read1(rowIndex1, colIndexDEF, a);
return RANDDEF1;
}
//fake def 2:
private String rdef2(){//FIX DOWHILE
int rowIndex2=1;//null value
int colIndexDEF=3;
String POSsave1=null;
//do{
rowIndex2=RNG1(a);
POSsave1=read1(rowIndex2, colIndexPOS, a);
//}while(rowIndex2==rowIndex1 || rowIndex2==rowIndex || !POSsave1.equals(POS));
String RANDDEF2=read1(rowIndex2, colIndexDEF, a);
return RANDDEF2;
}
//fake def 3:
private String rdef3(){//FIX DOWHILE
int rowIndex3=1;//null value
int colIndexDEF=3;
String POSsave2=null;
//do{
rowIndex3=RNG1(a);
POSsave2=read1(rowIndex3, colIndexPOS, a);
//}while(rowIndex3==rowIndex || rowIndex3==rowIndex2 || rowIndex3==rowIndex1 || !POSsave2.equals(POS));
String RANDDEF3=read1(rowIndex3, colIndexDEF, a);
return RANDDEF3;
}
private void createButtonA() {
String definition=null;
if (location==1){
definition=def();
}
if (location==2){
definition=rdef1();
}
if (location==3){
definition=rdef2();
}
if (location==4){
definition=rdef3();
}
buttonA = new JButton(definition);
add(buttonA);
buttonA.setContentAreaFilled(false);
buttonA.addActionListener((ActionListener) this);//this allows an action to be performed when the button is pressed
buttonA.setForeground(Color.blue);
buttonA.setBounds(45,130,295,25);
}
private void createButtonB() {
String definitionB=null;
if (location==1){
definitionB=rdef1();
}
if (location==2){
definitionB=def();
}
if (location==3){
definitionB=rdef3();
}
if (location==4){
definitionB=rdef2();
}
buttonB = new JButton(definitionB);
add(buttonB);
buttonB.setContentAreaFilled(false);
buttonB.addActionListener((ActionListener) this);//this allows an action to be performed when the button is pressed
buttonB.setForeground(Color.blue);
buttonB.setBounds(45,95,295,25);
}
private void createButtonC() {
String definitionC=null;
if (location==1){
definitionC=rdef2();
}
if (location==2){
definitionC=rdef3();
}
if (location==3){
definitionC=def();
}
if (location==4){
definitionC=rdef1();
}
buttonC = new JButton(definitionC);
add(buttonC);
buttonC.setContentAreaFilled(false);
buttonC.addActionListener((ActionListener) this);//this allows an action to be performed when the button is pressed
buttonC.setForeground(Color.blue);
buttonC.setBounds(45,60,295,25);
}
private void createButtonD() {
String definitionD=null;
if (location==1){
definitionD=rdef3();
}
if (location==2){
definitionD=rdef2();
}
if (location==3){
definitionD=rdef1();
}
if (location==4){
definitionD=def();
}
buttonD = new JButton(definitionD);
add(buttonD);
buttonD.setContentAreaFilled(false);
buttonD.addActionListener((ActionListener) this);//this allows an action to be performed when the button is pressed
buttonD.setForeground(Color.blue);
buttonD.setBounds(45,25,295,25);
}
public static void main(String[] args) {
SAT frameTable = new SAT();
//frameTable.SAT(); //Creating Frame
frameTable.createButtonA(); //Creating Button 1
frameTable.createButtonB(); //Creating Button 2
frameTable.createButtonC();//Creating button 3
frameTable.createButtonD();//Creating button 3
}
public SAT() {//problem
Container window = getContentPane();
window.setLayout(new FlowLayout() ); //using the FlowLayout manager
setSize(400,250); //setting the size of the initial box
setVisible(true); //allows for manual size changing of the box
setTitle("FlaQuiZ"); //Title for the GUI
window.setBackground(Color.white);
setLocation(500,280);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Allows us to actually exit when we click the "X"
panel1 = new JPanel(new GridLayout());
add(new JLabel("Choose the option that best fits this word: "+WORD));
//add(new JLabel(""));
}
public void actionPerformed(ActionEvent i) {
if ( location==1 && i.getSource() == buttonA || location==2 && i.getSource()==buttonB || location==3 && i.getSource()==buttonC || location==4 && i.getSource()==buttonD) {
GRATS congrats =new GRATS();
congrats.setVisible(true);
dispose();
}
else{
NO bad =new NO();
bad.setVisible(true);
dispose();
}
}
}
And then here would be the code if they got it wrong, where the button should appear to give the option to go back:
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class NO extends JFrame implements ActionListener{
private JButton NOB;
private JPanel panel3;
public NO() {
Container window = getContentPane();
window.setLayout(new FlowLayout() ); //using the FlowLayout manager
setSize(275,160); //setting the size of the initial box
setVisible(true); //allows for manual size changing of the box
setTitle("Flaquiz"); //Title for the GUI
window.setBackground(Color.white);
setLocation(500,280);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Allows us to actually exit when we click the "X"
JPanel panel3 = new JPanel(new GridLayout());
add(new JLabel("Uh oh, you got it wrong!"));
//add(new JLabel(""));
}
public static void main(String[] args) {
NO bad = new NO();
//frameTable.SAT(); //Creating Frame
bad.createbuttonNOB(); //Creating Button 1
}
private void createbuttonNOB() {
NOB = new JButton("Go Back");
add(NOB);
NOB.setContentAreaFilled(false);
NOB.addActionListener((ActionListener) this);//this allows an action to be performed when the button is pressed
NOB.setForeground(Color.blue);
NOB.setBounds(45,45,45,45);
}
public void actionPerformed(ActionEvent i) {
if (i.getSource() == NOB ) {
SAT goback =new SAT();
goback.setVisible(true);
dispose();
}
}
}
I may be missing something, but it seems you add the button directly to the JFrame even though you have a JPanel occupying the whole frame. Why not add the button to the JPanel?
Side Note: In the NO constructor, SetVisible doesn't determine whether or not you can manually change size. That's controlled by things like SetMaximumSize, SetMinimumSize, and SetResizable.

repaint on the JFrames when the input arrives

Currently i am working on DEVSJAVA models and trying to make a GUI for those models.
In the below code i have written a displayphase class.In this class whenever a new input arrives it goes into the delext function and then reads the value of the varaible "result" and call the showstate function and then it should paint the result on the JFrame and again when another input arrives it should repaint on the JFrame.
But in the code what i have written makes all the panels print on the JFrame rather than repainting it. I know the error is in adding new panel everytime it goes into the showstate function. But i am unable to make it work.Could please help me out from this error.
package assignment2;
import java.awt.*;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import simView.*;
import genDevs.modeling.*;
import genDevs.simulation.*;
import GenCol.*;
import simView.*;
public class displayphase extends ViewableAtomic{//ViewableAtomic is used instead
//of atomic due to its
//graphics capability
protected entity job;
protected double cul,cll,hul,hll,temp,varout,output,a,b,c,d,g;
protected double processing_time,temperature,temp1,temp2;
protected boolean acStatus,heaterStatus;
protected String result;
**JFrame f=new JFrame();**
public displayphase(){
this("displayphase"
);
}
public displayphase(String name){
super(name);
addInport("in");
addOutport("out");
addInport("in1");
addOutport("out1");
addOutport("out2");
addOutport("out3");
addRealTestInput("in1",71);
addRealTestInput("in",75);
addTestInput("in",new job("job","coolair",72.5),1);
addTestInput("in",new job("job",true,false,60),0);
addRealTestInput("in",3,1);
// processing_time = Processing_time;
}
public void initialize(){
phase = "passive";
sigma = INFINITY;
a=0;b=0;c=0;d=0;g=0;
job = new entity("job");
super.initialize();
}
public void deltext(double e,message x)
{
Continue(e);
if (phaseIs("passive"))
for (int i=0; i< x.getLength();i++)
if (somethingOnPort(x,"in"))
{ job dummy;
entity ent = x.getValOnPort("in",i);
// doubleEnt tem = (doubleEnt) job;
dummy = (job) ent;
temp= dummy.getthetemperature();
result = dummy.getthestate();
heaterStatus = dummy.isHeaterStatus();
System.out.println("The phase in ac"+result);
temperature = temp;
holdIn("busy",processing_time);
}
if (phaseIs("passive"))
for (int i=0; i< x.getLength();i++)
if (somethingOnPort(x,"in1"))
{ job dummy;
entity ent = x.getValOnPort("in1",i);
// doubleEnt tem = (doubleEnt) job;
dummy = (job) ent;
temp= dummy.getthetemperature();
result = dummy.getthestate();
System.out.println("The phase in heater"+result);
heaterStatus = dummy.isHeaterStatus();
temperature=temp;
holdIn("busy",processing_time);
}
**showstate()**;
}
public void deltint( )
{
passivate();
}
public void deltcon(double e,message x)
{
/*deltint();
deltext(20,x);
*/}
public message out( )
{
return outputNameOnPort(result,"out");
}
**public void showstate(){
f.add(new MyPanel());
f.repaint();
f.pack();
f.setVisible(true);
}
class MyPanel extends JPanel {
public MyPanel() {
setBorder(BorderFactory.createLineBorder(Color.black));
}
public Dimension getPreferredSize() {
return new Dimension(250,200);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
String ac,ab;
if(result == "aboveHT" || result=="coolAir")
ac = "cooler on";
else
ac = "cooler off";
/* else if(result == "belowHT" || result == "passive" || result=="belowH")
ac = "cooler off";*/
if(result == "belowHt" )
ab = "Heater on";
else
ab="Heater off";
//String ac=String.valueOf(timesacon());
// JFrame f=new JFrame();
JLabel l=new JLabel("THE STATUS OF AC IS ",JLabel.CENTER);
JLabel p=new JLabel("THE STATUS OF HEATER IS",JLabel.CENTER);
/* p.setVerticalTextPosition(JLabel.BOTTOM);
p.setHorizontalTextPosition(JLabel.CENTER);*/
JTextField t=new JTextField("");
t.setSize(80, 40);
t.setText(ac);
Point p1=new Point(100, 100);
t.setLocation(100,100);
l.setLocation(80, 80);
JTextField v=new JTextField("");
v.setSize(80,40);
v.setText(ab);
Point p2=new Point(100,200);
v.setLocation(p2);
p.setLocation(80, 180);
this.add(l);
this.add(p);
this.add(t);
this.add(v);
this.setSize(500, 300);
// f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// f.pack();
this.setVisible(true);
}
}
}**
Do not modify that state of any component from within any paintXxx method. This will trigger a cascade of repaint events, which will continue to be called until you CPU is running hot and you program is unresponsive...
The paintXxx methods are used to provide the ability to perform custom painting of a component, not modify its state.
Instead, construct the basic UI in the constructor and provide some means by which the state of the fields can be changed, for example, via a updateState method...
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
class MyPanel extends JPanel {
private JTextField t;
private JTextField v;
public MyPanel() {
setBorder(BorderFactory.createLineBorder(Color.black));
JLabel l = new JLabel("THE STATUS OF AC IS ", JLabel.CENTER);
JLabel p = new JLabel("THE STATUS OF HEATER IS", JLabel.CENTER);
t = new JTextField("");
v = new JTextField("");
this.add(l);
this.add(p);
this.add(t);
this.add(v);
}
public void updateState(String result) {
String ac, ab;
if ("aboveHT".equals(result) || "coolAir".equals(result)) {
ac = "cooler on";
} else {
ac = "cooler off";
}
if ("belowHt".equals(result)) {
ab = "Heater on";
} else {
ab = "Heater off";
}
t.setText(ac);
v.setText(ab);
}
}
String comparison in Java is done via the String#equals method. Using == is simply comparing the object memory reference, which has a very low likelihood of ever being true
Without knowing more, I would create an instance of a JFrame, add MyPanel to it and simply call MyPanel#updateState when you need to change it's state.
Modern UI's are expected to be capable of running on a variety of platforms, even when running the same OS, there are differences in the way that fonts may be rendered, making any statically placed and sized components unusable. Instead you should make use of the layout manager API which has being designed to solve this problem with minimal work on your part.
See Laying out components within a container

JTree select node by clicking anywhere on the row

I have code taken from here that would allow selection of a JTree Row by clicking anywhere on the row. it works fine in single row selection mode. However, I am not sure how to modify it in order to handle multiple row selections. how do I distinguish the case when user is make a multiple selection(eg. by holding down the shift or control button while making a left mouse click on a row)?
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
#SuppressWarnings("serial")
public class NavTree extends JTree {
private boolean fWholeRowSelectionEnabled;
private MouseListener fRowSelectionListener;
final NavTree fThis;
public NavTree(TreeNode rootNode) {
super(rootNode);
fThis = this;
init();
}
public NavTree() {
fThis = this;
init();
}
private void init() {
//setCellRenderer(new NavTreeCellRenderer());
fRowSelectionListener = new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (SwingUtilities.isLeftMouseButton(e)) {
int closestRow = fThis.getClosestRowForLocation(
e.getX(), e.getY());
Rectangle closestRowBounds = fThis.getRowBounds(closestRow);
if(e.getY() >= closestRowBounds.getY() &&
e.getY() < closestRowBounds.getY() +
closestRowBounds.getHeight()) {
if(e.getX() > closestRowBounds.getX() &&
closestRow < fThis.getRowCount()){
fThis.setSelectionRow(closestRow);
}
} else
fThis.setSelectionRow(-1);
}
}
};
setWholeRowSelectionEnabled(true);
}
public void setWholeRowSelectionEnabled(boolean wholeRowSelectionEnabled) {
fWholeRowSelectionEnabled = wholeRowSelectionEnabled;
if (fWholeRowSelectionEnabled)
addMouseListener(fRowSelectionListener);
else
removeMouseListener(fRowSelectionListener);
}
public boolean isWholeRowSelectionEnabled() {
return fWholeRowSelectionEnabled;
}
public static void main(String[] args) {
JFrame frame = new JFrame();
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
root.add(new DefaultMutableTreeNode("Child 1"));
root.add(new DefaultMutableTreeNode("Child 2"));
root.add(new DefaultMutableTreeNode("Child 3"));
NavTree tree = new NavTree(root);
frame.add(tree);
frame.setSize(200, 300);
frame.setVisible(true);
}
}
Use the modifier key information of the MouseEvent. See MouseEvent#getModifiersEx for more information
PS: the listener registration contains a bug
public void setWholeRowSelectionEnabled(boolean wholeRowSelectionEnabled) {
fWholeRowSelectionEnabled = wholeRowSelectionEnabled;
if (fWholeRowSelectionEnabled)
addMouseListener(fRowSelectionListener);
else
removeMouseListener(fRowSelectionListener);
}
Setting the property wholeRowSelectionEnabled to true should register the listener only one time. Your code would add the listener again and again if the property is set to true multiple times. What I mean is that the property setter should be idempotent.
A quickfix could be to remove it first and add it if enabled
public void setWholeRowSelectionEnabled(boolean wholeRowSelectionEnabled) {
removeMouseListener(fRowSelectionListener);
fWholeRowSelectionEnabled = wholeRowSelectionEnabled;
if (fWholeRowSelectionEnabled)
addMouseListener(fRowSelectionListener);
}

Categories