I want to add JMenuItem without closing JMenu. A menu contains a JTextField, When I press enter in text field, it added a menu Item. My problem is the size of added menu item is too small.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JMenuItem;
import javax.swing.JTextField;
public class NewJFrame extends javax.swing.JFrame {
public NewJFrame() {
initComponents();
this.jMenu1.addSeparator();
final JTextField jTextField = new JTextField("Menu 1",20);
this.jMenu1.add(jTextField);
jTextField.addActionListener(new ActionListener( ){
#Override
public void actionPerformed(ActionEvent e) {
final JMenuItem jMenuItem = new JMenuItem(jTextField.getText());
jMenu1.add(jMenuItem);
jMenuItem.repaint();
jMenuItem.revalidate();
}
});
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 279, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
// End of variables declaration//GEN-END:variables
}
When I am pressing enter, menu add a menu item, but its width is too small.
How can I fix it?
You have to update the popupMenu of the jMenu1, calling:
jMenu1.getPopupMenu().pack();
instead of
jMenuItem.repaint();
jMenuItem.revalidate();
Instead of repainting it, close the menu and reopen it. Just tried it and it works great, it's as quick as repainting on the spot.
jMenu1.add(jMenuItem);
//jMenuItem.repaint();
//jMenuItem.revalidate();
MenuElement[] selectionPath = MenuSelectionManager.defaultManager().getSelectedPath();
MenuSelectionManager.defaultManager().clearSelectedPath();
MenuSelectionManager.defaultManager().setSelectedPath(selectionPath);
Related
I have a game that has a MainUI class, a GameClass and a SettingsClass. The game works fine except when I click "Restart" or "Help" which takes me to another JFrame and then returns back to the MainUI by a click of a button. But, when that happens, the MainUI class does not dispose of itself when it should. I believe it has to do with instantiating the MainUI class again when I leave and come back from settings but I'm but sure how to fix it.
This is the code I'm using to dispose of the MainUI frame and open a new JFrame:
private final JFrame mainFrame;
mainFrame.dispose(); //the mainFrame variable is passed in the constructor since it's trying to dispose of the MainUI
EndingPage endingPage = new EndingPage(); //open ending page
endingPage.setVisible(true);
This is an example of part of the code for one of the buttons in the settings class
restart.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
MainUI.started=false;
mainFrame.dispose();
TitlePage title = new TitlePage();
title.setVisible(true);
}
});
When one of those buttons are clicked, another JFrame is opened accordingly. To go back to the MainUI this is run:
this.dispose();
MainUI main = new MainUI();
main.setVisible(true);
For more clarification, the second code is run when the user clicks the settings button. Then, the last code is run to get back to the JFrame it already was at. When the user wins the first code is run. But the issue is sometimes the mainFrame.dispose(); in the first code does not work. Any help is appreciated! If you need to see other code please tell me! I'm stuck.
EDIT:
This is the MainUI (there is a timer because I want to delay before the action)
package stackoverflowcode;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class MainUI extends javax.swing.JFrame {
/**
* Creates new form MainUI
*/
public MainUI() {
initComponents();
GameClass game = new GameClass(this, end);
SettingsClass settings = new SettingsClass(restart, this);
Timer timer;
private javax.swing.JButton end;
private javax.swing.JButton restart;
ActionListener action = new ActionListener(){
#Override
public void actionPerformed(ActionEvent event)
{
game.openEnd();
}
};
timer= new Timer (1000,action);
timer.start();
settings.settings();
}
private void initComponents() {
restart = new javax.swing.JButton();
end = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
restart.setText("SETTINGS");
end.setText("END");
javax.swing.GroupLayout layout = new
javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(151, 151, 151)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(end)
.addComponent(restart))
.addContainerGap(168, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(120, 120, 120)
.addComponent(restart)
.addGap(48, 48, 48)
.addComponent(end)
.addContainerGap(86, Short.MAX_VALUE))
);
pack();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainUI().setVisible(true);
}
});
}
}
SettingsClass
package stackoverflowcode;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
public class SettingsClass {
JButton restart;
JFrame mainFrame;
public SettingsClass(JButton restart, JFrame mainFrame){
this.restart=restart;
this.mainFrame=mainFrame;
}
public void settings() {
restart.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
mainFrame.dispose();
TitlePage title = new TitlePage();
title.setVisible(true);
}
});
}
}
TitlePage
package stackoverflowcode;
public class TitlePage extends javax.swing.JFrame {
/**
* Creates new form TitlePage
*/
public TitlePage() {
initComponents();
private javax.swing.JButton Play;
}
private void initComponents() {
Play = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
Play.setText("PLAY");
Play.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
PlayActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new
javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(134, 134, 134)
.addComponent(Play)
.addContainerGap(209, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(129, 129, 129)
.addComponent(Play)
.addContainerGap(148, Short.MAX_VALUE))
);
pack();
}
private void PlayActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
this.dispose();
MainUI main = new MainUI();
main.setVisible(true);
}
public static void main(String args[]){
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new TitlePage().setVisible(true);
}
});
}
}
GameClass
package stackoverflowcode;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
public class GameClass {
private final JFrame mainFrame;
private final JButton endButton;
public GameClass(JFrame mainFrame, JButton endButton){
this.mainFrame=mainFrame;
this.endButton=endButton;
}
public void openEnd(){
endButton.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
mainFrame.dispose(); //the mainFrame variable is passed in the constructor since it's trying to dispose of the MainUI
TitlePage endingPage = new TitlePage(); //open title page
endingPage.setVisible(true);
}
});
}
}
I'm trying to make a game in Java, and I decided to use GIFs as animations in a JFrame. However, the program keeps showing past frames of the GIF, so the whole image looks like a mess.
This is what the GIF should look like in the program:
However, the GIF ends up looking like this (this is a screenshot of what appears on the JFrame):
And here is my code so far. I'm using NetBeans with Java 8.0.2.
package giftest;
public class MainWindow extends javax.swing.JFrame {
public MainWindow() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/giftest/Chespin2.gif"))); // NOI18N
jLabel1.setText("jLabel1");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(158, 158, 158)
.addComponent(jLabel1)
.addContainerGap(12, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(89, 89, 89)
.addComponent(jLabel1)
.addContainerGap(19, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainWindow().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JLabel jLabel1;
// End of variables declaration
}
// End of Program
The effect can be reproduced with these lines of code:
import javax.swing.*;
import java.net.*;
public class AnimatedGifTest {
AnimatedGifTest() throws MalformedURLException {
URL url = new URL(
"https://i.stack.imgur.com/y9O4G.gif");
ImageIcon ii = new ImageIcon(url);
JOptionPane.showMessageDialog(null, ii);
}
public static void main(String[] args) {
Runnable r = () -> {
try {
new AnimatedGifTest();
} catch (MalformedURLException ex) {
ex.printStackTrace();
}
};
SwingUtilities.invokeLater(r);
}
}
I'm using Java Swing, and I'm using jLabels and putting the GIF as the icon. Is there a way to fix this issue in NetBeans on Java 8.0.2? Thanks in advance!
I have my JFrame, and I want to attach to a button an ActionListener that triggers the JInternalFrame.
I do:
private void aboutMenuItemActionPerformed(java.awt.event.ActionEvent evt) {
AboutFrame about = new AboutFrame(); //jInternalFrame
this.add(about);
}
But it doesn't bring it to front. What did I miss?
You probable want to use a JDesktopPane, then set the content pane of your frame to the desktop pane
JDesktopPane desktop = new JDesktopPane(); //a specialized layered pane
createFrame(); //create first "window"
setContentPane(desktop);
Then you can do something like this
private void aboutMenuItemActionPerformed(java.awt.event.ActionEvent evt)
{
AboutFrame about = new AboutFrame(); <--- JInternalFrame
about.setVisible(true); //necessary as of 1.3 <--- set it visible
desktop.add(about); <--- add to desktop
try {
about.setSelected(true); <--- set it selected
} catch (java.beans.PropertyVetoException e) {}
}
See How to Us Internal Frames
UDATE
Run this example, I made on NetBeans GUI Builder also. It works fine, without the behavior yout're talking about.
public class NewJFrame extends javax.swing.JFrame {
public NewJFrame() {
initComponents();
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jDesktopPane1 = new javax.swing.JDesktopPane();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout jDesktopPane1Layout = new javax.swing.GroupLayout(jDesktopPane1);
jDesktopPane1.setLayout(jDesktopPane1Layout);
jDesktopPane1Layout.setHorizontalGroup(
jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 376, Short.MAX_VALUE)
);
jDesktopPane1Layout.setVerticalGroup(
jDesktopPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 302, Short.MAX_VALUE)
);
jMenu1.setText("File");
jMenuBar1.add(jMenu1);
jMenu2.setText("About");
jMenuItem1.setText("About");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu2.add(jMenuItem1);
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jDesktopPane1)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jDesktopPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
pack();
}// </editor-fold>
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
AboutFrame about = new AboutFrame();
about.setVisible(true);
jDesktopPane1.add(about);
try {
about.setSelected(true);
} catch (java.beans.PropertyVetoException e) {
}
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JDesktopPane jDesktopPane1;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
// End of variables declaration
}
AboutFrame.java
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JInternalFrame;
import javax.swing.JPanel;
public class AboutFrame extends JInternalFrame{
public AboutFrame() {
add(new Panel());
pack();
}
private class Panel extends JPanel {
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawString("About Screen", 100, 100);
}
public Dimension getPreferredSize(){
return new Dimension(300, 300);
}
}
}
Steps I took
Opened a new JFrame form
Dragged a JDesktopPane to the main frame and expanded it the size of the frame
Dragged a JMenuBar to the top of the frame
Dragged a JMenuItem to the JMenuBar
Added an event listener to the JMenuItem
Added the action code that i provided for you earlier. That's all I did, and it works fine.
EDIT
A different apprach would be instead of using an JInternalFrame for this. Use a modal JDialog. You can create it the same way you did the JInternalFrame , and show it the same way. This will guarantee you don't get this result. :)
I'm dynamically generating some text boxes and labels inside a JPanel but when I place that panel inside a JTabbedPane it's not generate inside its original location. it always go to somewhere else.
Code inside JFrame class constructor:
panel = jPanel1;
panel.setLayout(new FlowLayout());
add(panel, BorderLayout.LINE_START);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
Code inside a JButton:
JLabel lbl = new JLabel();
lbl.setText("Label");
panel.add(lbl);
JTextField txt = new JTextField(12);
txt.setText("Text field");
panel.add(txt);
panel.revalidate();
validate();
The button is use to generate text boxes and labels dynamically. jPanel1 is a panel placed inside a frame. its works perfectly with directly placed inside a frame but after it is placed inside a tabbed pane it's messing around.
Is there a method to refresh panel and remove components inside it after generating components inside it?
here is the complete Jframe class:
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author sajithru
*/
public class DynamicTextboxes extends javax.swing.JFrame {
/**
* Creates new form DynamicTextboxes
*/
private JPanel panel;
public DynamicTextboxes() {
initComponents();
panel = jPanel1;
panel.setLayout(new FlowLayout());
add(panel, BorderLayout.LINE_START);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jButton1 = new javax.swing.JButton();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 206, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 258, Short.MAX_VALUE)
);
jTabbedPane1.addTab("tab1", jPanel1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(190, 190, 190)
.addComponent(jButton1)
.addContainerGap(216, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(16, 16, 16)
.addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 286, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1)
.addContainerGap(40, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JLabel lbl = new JLabel();
lbl.setText("Label");
panel.add(lbl);
JTextField txt = new JTextField(12);
txt.setText("Text field");
panel.add(txt);
panel.revalidate();
validate();
}
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(DynamicTextboxes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(DynamicTextboxes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(DynamicTextboxes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DynamicTextboxes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new DynamicTextboxes().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JPanel jPanel1;
private javax.swing.JTabbedPane jTabbedPane1;
// End of variables declaration
}
I suspect that you are using setBounds(), or something similar, to position components in a Container that has some (default) layout lying in wait for your call to revalidate(). Instead, invoke pack() on the enclosing Window before calling setVisible().
Addendum: I tried using pack() … but result is still the same.
Your layout is cutting off the new rows. The example below uses pack() to resize the enclosing Window. This related example illustrates revalidate() and repaint(). Also consider using a JScrollPane, seen here.
import java.awt.BorderLayout;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* #see https://stackoverflow.com/a/17165034/230513
*/
public class DynamicTextboxes extends javax.swing.JFrame {
/**
* Creates new form DynamicTextboxes
*/
public DynamicTextboxes() {
initComponents();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private void initComponents() {
jButton1 = new javax.swing.JButton();
jTabbedPane1 = new javax.swing.JTabbedPane();
jPanel1 = new javax.swing.JPanel(new GridLayout(0, 1));
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jButton1.setText("jButton1");
jButton1.addActionListener(new java.awt.event.ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jPanel1.add(createPanel());
jTabbedPane1.addTab("tab1", jPanel1);
add(jTabbedPane1);
JPanel p = new JPanel();
p.add(jButton1);
add(p, BorderLayout.SOUTH);
pack();
setLocationByPlatform(true);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jPanel1.add(createPanel());
pack();
}
private JPanel createPanel() {
JPanel p = new JPanel();
JLabel lbl = new JLabel();
lbl.setText("Label");
p.add(lbl);
JTextField txt = new JTextField(12);
txt.setText("Text field");
p.add(txt);
return p;
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new DynamicTextboxes().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JPanel jPanel1;
private javax.swing.JTabbedPane jTabbedPane1;
// End of variables declaration
}
I want to let JComboBox be aligned from right to left and to render text from right to left
I have set component orientation and also change the render as follows:
import java.awt.Component;
import java.awt.ComponentOrientation;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.SwingConstants;
public class NewJFrame extends javax.swing.JFrame {
/** Creates new form NewJFrame */
public NewJFrame() {
initComponents();
jComboBox1.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
jComboBox1.setRenderer(new DefaultListCellRenderer() {
public Component getListCellRendererComponent(JList jList, Object o,
int i, boolean b, boolean b1) {
JLabel rendrlbl = (JLabel) super.getListCellRendererComponent(jList, o, i, b, b1);
rendrlbl.setHorizontalAlignment(SwingConstants.RIGHT);
return rendrlbl;
}
});
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jComboBox1 = new javax.swing.JComboBox();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jComboBox1.setEditable(true);
jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(55, 55, 55)
.add(jComboBox1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 268, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap(77, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(37, 37, 37)
.add(jComboBox1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.addContainerGap(236, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
/**
* #param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JComboBox jComboBox1;
// End of variables declaration
}
As you may have seen in this screenshot the combobox and it's cursor is aligned to the left while the list is aligned to the right. How can I solve this?
it's cursor is aligned to the left while the list is aligned to the right. How can I solve this?
Sounds like you have an editable combo box. Therefore I guess you also need to change the orientation of the editor component:
ComboBoxEditor editor = comboBox.getEditor();
JTextField textField = (JTextField)editor.getEditorComponent();
textField.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);