I'm having an issue that I've been trying to solve all day. I have two panels inside a frame and in one panel I've added components. The components, however, seem to have an equal hierarchy value as the panel and as such treat the Frame as the parent instead, ignoring where the panels are located. Basically the components are added to one panel but display on top of both across the whole frame. (Unfortunately I can't post a picture at this time, please up vote the question to allow me to if needed). What is causing this and how can I fix it?
The relevant code:
JFrame arranFrame = new JFrame("Edit Arrangement");
arranFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel grid = new JPanel();
JPanel tools = new JPanel();
grid.setSize(700, 600);
tools.setSize(200, 600);
JLabel widthLabel = new JLabel("Width");
JLabel depthLabel = new JLabel("Depth");
JLabel columnLabel = new JLabel("Columns");
final JTextField rowWidthInput = new JTextField(30);
final JTextField rowsInput = new JTextField(30);
final JTextField columnInput = new JTextField(30);
rowWidthInput.setSize(40, 30);
rowsInput.setSize(40, 30);
columnInput.setSize(40, 30);
rowWidthInput.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
chartWidth = Integer.parseInt(rowWidthInput.getText());
}
});
rowsInput.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
chartRows = Integer.parseInt(rowsInput.getText());
}
});
columnInput.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
chartColumns = Integer.parseInt(columnInput.getText());
}
});
//Enter button for grid modifying creation and setup
JButton enterButton = new JButton("Enter");
enterButton.setSize(180, 50);
enterButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
chartWidth = Integer.parseInt(rowWidthInput.getText());
chartRows = Integer.parseInt(rowsInput.getText());
chartColumns = Integer.parseInt(columnInput.getText());
}
});
//Save Arrangement button creation and setup
JButton saveButton = new JButton("Save Arrangement");
saveButton.setSize(180, 50);
saveButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
SaveArrangement(userDocuments + "\\TSA Seating Chart\\Arrangements\\Period" + period + ".txt");
}
});
tools.setBackground(Color.RED); //Temp for visualization where the panes are
tools.add(widthLabel);
tools.add(rowWidthInput);
tools.add(depthLabel);
tools.add(rowsInput);
tools.add(columnLabel);
tools.add(columnInput);
tools.add(enterButton);
tools.add(saveButton);
arranFrame.getContentPane().add(grid);
arranFrame.getContentPane().add(tools);
//Finalize the GUI
arranFrame.pack(); //Pack all the content together
arranFrame.setSize(900, 600); //Set the size of the window
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
arranFrame.setLocation(dim.width/2-arranFrame.getSize().width/2, dim.height/2-arranFrame.getSize().height/2);
arranFrame.setVisible(true); //Display the seatingFrame
Related
So this code specifically says that there should be three rows and one column for JPanel selectPanel, however, when I run it I get this result and just can't figure out what I'm doing wrong. Most of this code is not relevant to the problem I think. The beginning is where I make the panel that is giving me issues (selectPanel) and the end is where that panel is added to the JFrame (roiguide).
Result of Code:
JPanel selectPanel = new JPanel();
selectPanel.setLayout(new GridLayout(3,1,0,0));
selectPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
imp.getWindow().toFront();
IJ.setTool(Toolbar.RECTANGLE);
referenceButton = new JButton("Add reference region");
referenceButton.setEnabled(true);
referenceButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
refDefine();
}
});
refLabel = new JLabel(" ("+printformat.format(rno)+"/1)");
selectPanel.add(referenceButton);
selectPanel.add(refLabel);
backgroundButton = new JButton("Add background region");
backgroundButton.setEnabled(true);
backgroundButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
brDefine();
}
});
backgroundLabel = new JLabel(" ("+printformat.format(bno)+"/"+printformat.format(spotno)+")");
selectPanel.add(backgroundButton);
selectPanel.add(backgroundLabel);
spotButton = new JButton("Add spot");
spotButton.setEnabled(true);
spotButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
spotDefine();
}
});
spotLabel = new JLabel(" ("+printformat.format(sno)+"/"+printformat.format(spotno)+")");
selectPanel.add(spotButton);
selectPanel.add(spotLabel);
JPanel editPanel = new JPanel();
selectPanel.setLayout(new GridLayout(2,1,20,20));
selectPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
jComboBox1 = new JComboBox();
editPanel.add(jComboBox1);
JButton editButton = new JButton("Edit ROIs");
editButton.setEnabled(true);
editButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String item = (String) jComboBox1.getSelectedItem();
Roi roi = overlay.get(overlay.getIndex(item));
}
});
editPanel.add(editButton);
// Create the buttonPanel, which has the "Cancel" and "OK" buttons
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1,2,20,20));
buttonPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
JButton cancelButton = new JButton("Cancel");
cancelButton.setEnabled(true);
cancelButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
didCancel = true;
roiguide.dispose();
overlay.clear();
}
});
buttonPanel.add(cancelButton);
JButton okButton = new JButton("OK");
okButton.setEnabled(true);
okButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(current!=roino){
IJ.error("ROI Manager","Please select " + roino + " regions of interest.");
}else{
canContinue=true;
roiguide.dispose();
}
}
});
buttonPanel.add(okButton);
// Create and populate the JFrame
roiguide = new JFrame("Add regions of interest:");
roiguide.getContentPane().add(selectPanel, BorderLayout.NORTH);
roiguide.getContentPane().add(editPanel, BorderLayout.WEST);
roiguide.getContentPane().add(buttonPanel, BorderLayout.EAST);
roiguide.pack();
roiguide.setLocation(400,400);
roiguide.setVisible(true);
roiguide.setResizable(false);
the addition of a new feature broke the display
Then you know what you changed so you should know where to start looking:
This looks suspicious:
JPanel editPanel = new JPanel();
selectPanel.setLayout(new GridLayout(2,1,20,20));
I created a GUI using java swing and in a specific situation, the JButton is unresponsive and I have to click it twice. On the click, it takes the info in the textArea and sends it to a TextParser class to be parsed. If I type more stuff in the area after, and click the evaluateButton, it doesn't respond and I have to click it again to work. Does anyone know if this is a known bug or how I can fix this?
The code for the class is as follows.
/**
* Add the components to the GUI.
* #param pane - the pane for the GUI
*/
public static void addComponentsToPane(Container pane) {
pane.setLayout(new BorderLayout());
JPanel instructionsPanel = new JPanel();
JLabel instructions = new JLabel("Enter the email text below");
instructionsPanel.setBackground(Color.LIGHT_GRAY);
instructionsPanel.add(instructions);
pane.add(instructionsPanel, BorderLayout.NORTH);
JPanel textAreaPanel = new JPanel();
textAreaPanel.setBackground(Color.LIGHT_GRAY);
final JTextArea textArea = new JTextArea();
textArea.setBackground(Color.WHITE);
textArea.setMinimumSize(new Dimension(400,350));
textArea.setMaximumSize(new Dimension(400,350));
textArea.setPreferredSize(new Dimension(400,350));
textArea.setLineWrap(true);
Border border = BorderFactory.createLineBorder(Color.BLACK);
textArea.setBorder(border);
textArea.setMinimumSize(new Dimension(500, 200));
textArea.setFont(new Font("Serif", Font.PLAIN, 16));
textAreaPanel.add(textArea);
pane.add(textAreaPanel, BorderLayout.CENTER);
JPanel scoringPanel = new JPanel();
JButton evaluateButton = new JButton("Evaluate Email");
final JLabel scoreLabel = new JLabel("");
JButton uploadFileBtn = new JButton("Upload File");
JButton importTermsBtn = new JButton("Import Terms");
scoringPanel.add(evaluateButton);
scoringPanel.add(uploadFileBtn);
scoringPanel.add(importTermsBtn);
scoringPanel.add(scoreLabel);
pane.add(scoringPanel, BorderLayout.SOUTH);
evaluateButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
try {
String email = textArea.getText();
TextParser textParser = new TextParser(email);
double score = textParser.parse();
scoreLabel.setText(score+"");
} catch (Exception ex) {
System.out.println(ex);
}
}
});
uploadFileBtn.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
scoreLabel.setText("Feature not yet available.");
}
});
importTermsBtn.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
DatabaseInput d = new DatabaseInput();
d.main(null);
}
});
}
/**
* Create the GUI and show it.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("EmailGUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setLocationRelativeTo(null);
frame.setPreferredSize(new Dimension(500,500));
frame.setTitle("Email Text Input");
frame.setResizable(true);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame.setSize(screenSize.width, screenSize.height);
//Set up the content pane.
addComponentsToPane(frame.getContentPane());
//Display the window.
frame.pack();
frame.setVisible(true);
}
My main method just calls createAndShowGUI(). I am new to StackOverflow so if I need to give more or less information in my post please let me know!
As Reimeus and Jason C said in the comments, I should have been using ActionListener which works perfectly.
I have tried to make an app that it will open a menu with buttons [ insert search for example]. When a click a button an other iframe will be open for each button. But when it comes to click second time the button insert, iframe was crashed.
Even if after the insert, I click search, the iframe was crashed again.
The main frame:
public Exercise(){
frame1= new JFrame();
frame1.setSize(400, 100);
panel1 = new JPanel();
panel1.setVisible(true);
in= new JButton("insert");
in.setSize(50, 10);
in.setLocation(100, 100);
panel1.add(in);
s = new JButton("search");
s.setSize(50, 10);
s.setLocation(200, 200);
panel1.add(s);
s.setVisible(true);
frame1.add(panel1);
frame1.setVisible(true);
in.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
insert();
});
s.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
search()
});
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
The search function:
public void search(){
frame3= new JFrame();
frame3.setSize(300, 300);
panel3 = new JPanel();
panel3.setLayout( null );
/* and other textfields and labels */
JButton go= new JButton("go");
go.setSize(100, 100);
go.setBounds(10, 200,200,20);
panel3.add(go);
frame3.add(panel3);
frame3.setVisible(true);
go.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
////// .... ////
frame3.setVisible(false)
/* I have already tried:
frame3.dispose().
frame3.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);*/
});
}
The insert function
public void insert(){
frame2= new JFrame();
frame2.setSize(300, 300);
panel2 = new JPanel();
panel2.setLayout( null );
/* and other labels and textfields */
JButton save= new JButton("save");
save.setSize(100, 100);
save.setBounds(10, 200,200,20);
panel2.add(save);
frame2.add(panel2);
frame2.setVisible(true);
save.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
////// .... ////
frame2.setVisible(false)
});
}
What can I do?
Thank you in advance
It's not a good practice to create a new frame each time a button is pressed: you do that with search() and insert(). So the bset you can do is keep one frame for frame 2, one for frame 3 etc and make them visible/invisible as needed.
That is create the frames outside the functions search() insert() - maybe in the constructor.
I'm currently following a java tutorial on how to create a guessing game GUI App. At one point in the instructions however, it says to Set the keyboard focus to the field; I don't know what this means or how to do it. Any clarification would be greatly appreciated.
here's the exact instruction: Focus the user's attention on thePlayer field:
Set the keyboard focus to the field.
here's my code so far:
public class GOM extends JFrame implements ActionListener, KeyListener
{
Container content = this.getContentPane();
//top
JTextField theGuess = new JTextField(10);
JLabel bankroll = new JLabel("");
//bottom
JButton newplayer = new JButton("New Player");
JButton newnumber = new JButton("New Number");
JTextField thePlayer = new JTextField(20);
//center
JTextArea theoutput = new JTextArea("");
//invisible
String playerName;
int theNumber;
int numTries;
int numGames;
double amtRemaining;
Random randomizer()
{
Random rnd = new Random();
return rnd;
}
JScrollPane scrollArea = new JScrollPane(theoutput);
public GOM()
{
this.setVisible(true);
this.setSize(500,400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Guess O'Matic");
//top panel
JPanel p1 = new JPanel();
p1.add(theGuess);
p1.add(bankroll);
p1.add(new JLabel("Make Your Guess"));
content.add(p1, BorderLayout.NORTH);
//bottom panel
JPanel p2 = new JPanel();
p2.add(newplayer);
p2.add(newnumber);
p2.add(thePlayer);
content.add(p2, BorderLayout.SOUTH);
// finishing touches
content.add(new JLabel(" "), BorderLayout.WEST);
content.add(new JLabel(" "), BorderLayout.EAST);
content.add(scrollArea, BorderLayout.CENTER);
newplayer.addActionListener(this);
newnumber.addActionListener(this);
thePlayer.addKeyListener(this);
theGuess.addKeyListener(this);
newPlayer();
}
public void newPlayer()
{
theoutput.setText(playerName);
theoutput.setEnabled(false);
theGuess.setEnabled(false);
newnumber.setEnabled(false);
newplayer.setEnabled(false);
theGuess.setBackground(Color.WHITE);
thePlayer.setEnabled(true);
thePlayer.setText(playerName);
thePlayer.setBackground(Color.YELLOW);
}
#Override
public void actionPerformed(ActionEvent e)
{
}
#Override
public void keyTyped(KeyEvent e)
{
}
#Override
public void keyPressed(KeyEvent e)
{
}
#Override
public void keyReleased(KeyEvent e)
{
}
}
If you have a GUI with several JTextFields and possibly other text components, the keyboard focus can only be on one of those fields at a time. In other words, if you type, only one of the fields can display the caret and then will usually display the typed in text. When a Swing GUI is displayed then the GUI must decide which text component should have focus, and it uses its focus traversal policy to decide this. The default policy usually will put the focus into the first text field created. You can change this by calling requestFocusInWindow() on the text component that you want to hold the focus.
This questions has been asked a few times but mine is a little different. I created a small application and in the view I added a few JPanels to a JFrame. I then try to add actionListeners in the controller which is where the problem happened.
The code below gives me the following error:
The method addActionListener(new ActionListener(){})
is undefined for the type JPanel
The view class
public class MainMenuGUI {
JTabbedPane tabbedPane = new JTabbedPane();
JPanel findUserPanel;
JPanel deleteUserPanel;
JPanel addUserPanel;
JFrame frame = new JFrame();
JPanel tabbedPanel = new JPanel();
//Controller class for tabbedPanel
ControllerTabbedPane listen = new ControllerTabbedPane(this);
//Controller class for findUserPanel
FindUserPanelController findUserController = new FindUserPanelController(findUserPanel);
public MainMenuGUI() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
findUserPanel = createFindUserPanel();
deleteUserPanel = createDeleteUserPanel();
addUserPanel = createAddUserPanel();
tabbedPane.addTab("Find User", findUserPanel);
tabbedPane.addTab("Delete User", deleteUserPanel);
tabbedPane.addTab("Add User", addUserPanel);
tabbedPanel.add(tabbedPane);
frame.add(tabbedPanel);
frame.pack();
// opens frame in the center of the screen
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
JPanel createFindUserPanel() {
findUserPanel = new JPanel();
findUserPanel.setPreferredSize(new Dimension(300, 300));
findUserPanel.setLayout(new GridLayout(5, 7));
JLabel firstlbl = new JLabel("First Name");
JLabel lastlbl = new JLabel("Last Name");
JLabel addresslbl = new JLabel("Address");
JLabel agelbl = new JLabel("Age");
JTextField firstNametxt = new JTextField(15);
JTextField lastNametxt = new JTextField(15);
JTextField addresstxt = new JTextField(30);
JTextField age = new JTextField(3);
JButton btn = new JButton("Submit");
JScrollPane window = new JScrollPane();
window.setViewportBorder(new LineBorder(Color.RED));
window.setPreferredSize(new Dimension(150, 150));
findUserPanel.add(firstlbl);
findUserPanel.add(firstNametxt);
findUserPanel.add(lastlbl);
findUserPanel.add(lastNametxt);
findUserPanel.add(addresslbl);
findUserPanel.add(addresstxt);
findUserPanel.add(agelbl);
findUserPanel.add(age);
findUserPanel.add(window, BorderLayout.CENTER);
findUserPanel.add(btn);
return findUserPanel;
}
Controller Class
public class ControllerTabbedPane {
MainMenuGUI mainMenuGUI;
int currentTabbedIndex = 0;
ControllerTabbedPane(MainMenuGUI mainMenuGUI){
this.mainMenuGUI = mainMenuGUI;
addTabbedPaneListeners();
}
private void addTabbedPaneListeners() {
mainMenuGUI.tabbedPane.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent ce) {
currentTabbedIndex = mainMenuGUI.tabbedPane.getSelectedIndex();
System.out.println("Current tab is:" + currentTabbedIndex);
}
});
}
/*ERROR saying The method addActionListener(new ActionListener(){})
is undefined for the type JPanel*/
private void findPanelListeners() {
mainMenuGUI.findUserPanel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
});
}
This is the way to achieve your request:
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JButton bt1 = new JButton();
JButton bt2 = new JButton();
panel1.add(bt1);
panel2.add(bt2);
bt1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Bt1 on panel1 pressed");
}
});
bt2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Bt2 on panel2 pressed");
}
});
You can modify variables or other objects into the listeners to store which panel was "pressed".
I think its not possible to add addActionListner() to JPanel
Instead
You can use,
JPanel p1=new JPanel();
p1.addMouseListener(this);
And override
public void mouseClicked(MouseEvent me)
{
int x=me.getX();
int y=me.getY();
System.out.println(x+","+y);
//By using x AND y you can identify the panel
}
NB: extends MouseAdapter