I have been googling an sherthing for an solution to this problem a lot but can't find any answer how to fix this. My problem is that when i start a new jframe from an actionevent from pressing a button the class white the JFrame opens but then the programs starts to freeze and the pop up windows stays blank.
Her is the cod i apologize if there is some bad programing or some words in swedish:
The start upp class:
import java.util.ArrayList;
public class maineClassen {
ArrayList<infoClass> Infon = new ArrayList<>();
public static void main (String [] args)
{
referenser referens = new referenser();
Startskärmen ss = new Startskärmen(referens);
}
}
The "startskärm" the first screen to com to:
public class Startskärmen extends JFrame implements ActionListener {
referenser referens;
ArrayList<infoClass> Infon;
JButton öppna = new JButton("open");
JButton ny = new JButton("create new");
JButton radera = new JButton("erase");
JScrollPane pane = new JScrollPane();
DefaultListModel mod = new DefaultListModel();
JList list = new JList(mod);
JScrollPane sp = new JScrollPane(list);
JLabel texten = new JLabel("pre-alpha 0.1");
public Startskärmen(referenser re)
{
//references should be sent by itself or received
referens = re;
Infon = referens.getInfoReferens();
//build up the window
JPanel labelPanel = new JPanel();
labelPanel.setLayout(new BoxLayout(labelPanel, BoxLayout.LINE_AXIS));
labelPanel.setBorder(BorderFactory.createEmptyBorder(10,10,0,10));
labelPanel.add(texten);
JPanel scrollPanel = new JPanel();
scrollPanel.setLayout(new BoxLayout(scrollPanel, BoxLayout.LINE_AXIS));
scrollPanel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
scrollPanel.add(sp);// man kan ocksä sätta in --> pane <--
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
buttonPanel.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
buttonPanel.add(Box.createHorizontalGlue());
buttonPanel.add(öppna);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(ny);
buttonPanel.add(Box.createRigidArea(new Dimension(10, 0)));
buttonPanel.add(radera);
Container contentPane = getContentPane();
contentPane.add(labelPanel,BorderLayout.NORTH);
contentPane.add(scrollPanel, BorderLayout.CENTER);
contentPane.add(buttonPanel, BorderLayout.PAGE_END);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setSize(500, 500);
//adda action listener
ny.addActionListener(this);
öppna.addActionListener(this);
radera.addActionListener(this);
//skapaNyIC();
}
infoClass hh;
public void skapaNyIC()
{
Infon.add(new infoClass());
Infon.get(Infon.size() -1).referenser(Infon); //Infon.get(Infon.size() -1)
mod.addElement(Infon.get(Infon.size() -1).getName());
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == ny)
{
skapaNyIC();
}
else if(e.getSource() == öppna)
{
JOptionPane.showMessageDialog(texten,"This function doesn't exist yet");
}
else if(e.getSource() == radera)
{
JOptionPane.showMessageDialog(texten, "This function doesn't exist yet");
}
}
}
The class where the information will be stored and that creates the window (class) that will show the info:
public class infoClass {
ArrayList<infoClass> Infon;
private infoClass ic;
private String namn = "inget namn existerar";
private String infoOmInfo = null;
private int X_Rutor = 3;
private int Y_Rutor = 3;
private String[] information = new String[X_Rutor + Y_Rutor];
//info om dessa värden
public infoClass()
{
}
public void referenser(infoClass Tic)
{
ic = Tic;
infonGrafiskt ig = new infonGrafiskt(ic);
}
public void referenser(ArrayList<infoClass> Tic)
{
ic = Tic.get((Tic.size() - 1 ));
System.out.println("inna");
infonGrafiskt ig = new infonGrafiskt(ic);
ig.setVisible(true);
System.out.println("efter");
}
public String namnPåInfon()
{
return namn;
}
//namnen
public String getName()
{
return namn;
}
public void setNamn(String n)
{
namn = n;
}
//xkordinaterna
public int getX_Rutor()
{
return X_Rutor;
}
public void setX_Rutor(int n)
{
X_Rutor = n;
}
//y kordinaterna
public int getY_Rutor()
{
return Y_Rutor;
}
public void setY_Rutor(int n)
{
Y_Rutor = n;
}
//informationen
public String[] getInformationen()
{
return information;
}
public void setInformationen(String[] n)
{
information = n;
}
//infoOmInfo
public String getinfoOmInfo()
{
return infoOmInfo;
}
public void setinfoOmInfo(String n)
{
infoOmInfo = n;
}
}
The class that will show the info created by the window a bow:
public class infonGrafiskt extends JFrame implements ActionListener{
infoClass ic;
infonGrafiskt ig;
//tillrutnätet
JPanel panel = new JPanel(new SpringLayout());
boolean pausa = true;
//sakerna till desigen grund inställningar GI = grund inställningar
JButton GIklarKnapp = new JButton("Spara och gå vidare");
JTextField GInamn = new JTextField();
JLabel GINamnText = new JLabel("Namn:");
JTextField GIxRutor = new JTextField();
JLabel GIxRutorText = new JLabel("Antal rutor i X-led:");
JTextField GIyRutor = new JTextField();
JLabel GIyRutorText = new JLabel("Antal rutor i Y-led:");
JLabel GIInfo = new JLabel("Grund Inställningar");
// de olika framm:arna
JFrame GIframe = new JFrame("SpringGrid");
JFrame frame = new JFrame("SpringGrid");
//info om denna infon som finns här
JTextArea textArea = new JTextArea();
JScrollPane infoOmClasen = new JScrollPane(textArea); //hadde text area förut
JLabel infoRutan = new JLabel("Informatin om denna resuldatdatabank:");
//namnet på informationsdatabanken
JLabel namnetPåInfot = new JLabel("Namnet på denna resuldatdatabas.");
JButton ändraNamn = new JButton("Ändra namn");
JButton sparaAllt = new JButton("Spara allt");
public infonGrafiskt(infoClass Tic)
{
//få startinfo
namnOchRutor();
ic = Tic;
//skapar om rutan
JPanel p1 = new JPanel();
p1.setLayout(new BoxLayout(p1, BoxLayout.PAGE_AXIS));
p1.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
namnetPåInfot.setFont(new Font("Dialog",1,22));
p1.add(namnetPåInfot);
//pausa programet tills grundinställningarna är instälda
int m =1;
try {
while(m ==1)
{
Thread.sleep(100);
if(pausa == false)
m =2;
}
} catch(InterruptedException e) {
}
//Create the panel and populate it. skapar den så alla kommer åt den
//JPanel panel = new JPanel(new SpringLayout());
for (int i = 0; i < ic.getX_Rutor()*ic.getY_Rutor(); i++) {
JTextField textField = new JTextField(Integer.toString(i));
panel.add(textField);
}
//Lay out the panel.
SpringUtilities.makeGrid(panel,
ic.getY_Rutor(), ic.getX_Rutor(), //rows, cols
5, 5, //initialX, initialY
5, 5);//xPad, yPad
//set up the window.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//p1.add(ändraNamn);
JPanel p2 = new JPanel();
p2.setLayout(new BoxLayout(p2, BoxLayout.PAGE_AXIS));
p2.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
p2.add(infoRutan);
infoOmClasen.setPreferredSize(new Dimension(0,100));
p2.add(infoOmClasen);
JPanel p3 = new JPanel();
p3.setLayout(new FlowLayout());
p3.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
p3.setLayout(new BoxLayout(p3, BoxLayout.LINE_AXIS));
p3.add(ändraNamn);
p3.add(sparaAllt);
//Set up the content pane.
panel.setOpaque(true); //content panes must be opaque
frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.PAGE_AXIS));
frame.add(p1);
frame.add(p2);
frame.add(panel);//frame.setContentPane(panel);
frame.add(p3);
//Display the window.
frame.pack();
sparaAllt.addActionListener(this);
ändraNamn.addActionListener(this);
}
private void namnOchRutor()
{
System.out.println("inna 2");
//sättigång action listner
GIklarKnapp.addActionListener(this);
frame.setVisible(false);
//frameStart.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GIframe.setLayout(new BoxLayout(GIframe.getContentPane(), BoxLayout.PAGE_AXIS));
JPanel GIP0 = new JPanel();
GIP0.setLayout(new BoxLayout(GIP0,BoxLayout.LINE_AXIS));
GIP0.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
GIP0.add(GIInfo);
GIInfo.setFont(new Font("Dialog",1,22));
JPanel GIP1 = new JPanel();
GIP1.setLayout(new BoxLayout(GIP1,BoxLayout.LINE_AXIS));
GIP1.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
GIP1.add(GINamnText);
GIP1.add(Box.createRigidArea(new Dimension(10, 0)));
GIP1.add(GInamn);
JPanel GIP2 = new JPanel();
GIP2.setLayout(new BoxLayout(GIP2,BoxLayout.LINE_AXIS));
GIP2.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
GIP2.add(GIxRutorText);
GIP2.add(Box.createRigidArea(new Dimension(10, 0)));
GIP2.add(GIxRutor);
JPanel GIP3 = new JPanel();
GIP3.setLayout(new BoxLayout(GIP3,BoxLayout.LINE_AXIS));
GIP3.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
GIP3.add(GIyRutorText);
GIP3.add(Box.createRigidArea(new Dimension(10, 0)));
GIP3.add(GIyRutor);
JPanel GIP4 = new JPanel();
GIP4.setLayout(new BoxLayout(GIP4,BoxLayout.LINE_AXIS));
GIP4.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
GIP4.add(GIklarKnapp);
System.out.println("inna 3");
//lägga till sakerna gurund instllnings framen
GIframe.add(GIP0);
GIframe.add(GIP1);
GIframe.add(GIP2);
GIframe.add(GIP3);
GIframe.add(GIP4);
//desigen
System.out.println("inna 4");
GIframe.pack();
GIframe.setVisible(true);
System.out.println("inna5");
}
/*public static void main (String [] args)
{
infoClass i = new infoClass();
infonGrafiskt ig = new infonGrafiskt(i);
}*/
public void referenserna( infonGrafiskt Tig)
{
ig = Tig;
}
private void skrivTillbaka()
{
String[] tillfäligString = ic.getInformationen();
Component[] children = panel.getComponents();
for (int i=0;i<children.length;i++){
if (children[i] instanceof JTextField){
((JTextField)children[i]).setText(tillfäligString[i]);
System.out.println(tillfäligString[i]);
}
}
namnetPåInfot.setText(ic.getName());
textArea.setText(ic.getinfoOmInfo());
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == GIklarKnapp)
{
//skicka x och y antal ett och så
ic.setNamn(GInamn.getText());
ic.setX_Rutor(Integer.parseInt(GIxRutor.getText()));
ic.setY_Rutor(Integer.parseInt( GIyRutor.getText()));
namnetPåInfot.setText(ic.getName());
pausa = false;
GIframe.setVisible(false);
frame.setVisible(true);
}
if(e.getSource() == sparaAllt)
{
String[] tillfäligString = ic.getInformationen();
Component[] children = panel.getComponents();
for (int i=0;i<children.length;i++){
if (children[i] instanceof JTextField){
tillfäligString[i] = ((JTextField)children[i]).getText();
System.out.println(tillfäligString[i]);
}
}
ic.setInformationen(tillfäligString);
ic.setNamn(namnetPåInfot.getText());
ic.setinfoOmInfo(textArea.getText());
}
if(e.getSource() == ändraNamn)
{
skrivTillbaka();
}
}
}
so my problem now is that i can't create a new "infoclass" that will show the info in the "infoGrafikst" class. with the code:
Infon.add(new infoClass());
Infon.get(Infon.size() -1).referenser(Infon); //Infon.get(Infon.size() -1)
mod.addElement(Infon.get(Infon.size() -1).getName());
that am triggered by an button click.
Sorry for all the cod, but didn't know how to show my problem in another way.
Thanks a lot. I did find out that it was this code
int m =1;
try {
while(m ==1) {
Thread.sleep(100);
if(pausa == false)
m =2;
}
} catch(InterruptedException e) {
}
that made it not work...
Well I haven't gone through your code may be beacuse I am too lazy to read pages of code.Well i think the new window you are creating must be interfering with EDT.
Well i have done a short example which may help you, and its smooth:
import java.awt.event.ActionEvent;
import javax.swing.*;
public class FrameLaunch {
void inti(){
final JFrame f=new JFrame();
final JFrame f2=new JFrame();
final JTextArea ja=new JTextArea();
JButton b =new JButton("press for a new JFrame");
f2.add(b);
f2.pack();
f2.setVisible(true);
b.addActionListener(new java.awt.event.ActionListener()
{
public void actionPerformed(ActionEvent e) {
f2.setVisible(false);
f.setSize(200,200);
ja.setText("THIS IS NOT FROZEN");
f.add(ja);
f.setVisible(true);
f.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
}
});
}
public static void main(String[] args)
{
FrameLaunch frame = new FrameLaunch();
frame.inti();
}
}
Related
I am trying to write code for an application I'm making, I have my main frame with 6 buttons on them. When I push one of my buttons, it is meant to bring up a frame that has a tabbed layout set up.
I have the tabbed frame coded correctly and when I set each frame as visible they will appear to screen but they don't appear when the button is pushed.
I have action listeners connected to the buttons and the frames I want to connect with them as well as constructors but for some reason I can't get my code to work correctly.
I have added my driver and my first two forms I'm trying to connect to each other.
public class SimpsonsDriver {
//#param args the command line arguments
public static void main(String[] args) {
// TODO code application logic here
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame simpsonFrame = new JFrame("The Simpson");
JFrame homerFrame = new JFrame ("Homer Simpson");
JFrame margeFrame = new JFrame ("Marge Simpson");
JFrame bartFrame = new JFrame ("Bart Simpson");
JFrame lisaFrame = new JFrame("Lisa Simpson");
JFrame maggieFrame = new JFrame("Maggie Simpson");
SimpsonForm simpsonForm = new SimpsonForm(simpsonFrame, homerFrame, margeFrame, bartFrame,
lisaFrame, maggieFrame);
HomerForm homerForm = new HomerForm(homerFrame, simpsonFrame);
MargeForm margeForm = new MargeForm(margeFrame, simpsonFrame);
BartForm bartForm = new BartForm(bartFrame, simpsonFrame);
LisaForm lisaForm = new LisaForm(lisaFrame, simpsonFrame);
MaggieForm maggieForm = new MaggieForm(maggieFrame, simpsonFrame);
}
}
public class SimpsonForm implements ActionListener{
JFrame simpsonFrame, homerFrame, margeFrame, bartFrame, lisaFrame, maggieFrame;//instance variables
JButton homerBtn, margeBtn, bartBtn, lisaBtn, maggieBtn, closeBtn; //instance variables
public SimpsonForm(JFrame simpsonFrame, JFrame homerFrame, JFrame margeFrame, JFrame bartFrame, JFrame lisaFrame, JFrame maggieFrame) {
this.simpsonFrame = simpsonFrame;
this.homerFrame = homerFrame;
this.margeFrame = margeFrame;
this.bartFrame = bartFrame;
this.lisaFrame = lisaFrame;
this.maggieFrame = maggieFrame;
simpsonFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
createPanel();
}//end constructor method SimpsonForm
private void createPanel(){
homerBtn = new JButton ("Homer");
margeBtn = new JButton ("Marge");
bartBtn = new JButton ("Bart");
lisaBtn = new JButton ("Lisa");
maggieBtn = new JButton ("Maggie");
closeBtn = new JButton ("Close");
FlowLayout flow = new FlowLayout();
JPanel p1 = new JPanel();
p1.setLayout(flow);
JPanel p2 = new JPanel();
p2.setLayout(flow);
ImageIcon img = new ImageIcon(this.getClass().getResource("simpsons.png"));
JLabel imgLabel = new JLabel();
imgLabel.setIcon(img);
imgLabel.setBounds(10, 10, img.getIconWidth(), img.getIconHeight());
p1.add(imgLabel);
p2.add(homerBtn);
homerBtn.addActionListener(this);
p2.add(margeBtn);
margeBtn.addActionListener(this);
p2.add(bartBtn);
bartBtn.addActionListener(this);
p2.add(lisaBtn);
lisaBtn.addActionListener(this);
p2.add(maggieBtn);
maggieBtn.addActionListener(this);
p2.add(closeBtn);
closeBtn.addActionListener(this);
simpsonFrame.setLayout(new BorderLayout());
simpsonFrame.setResizable(false);
simpsonFrame.add(p1, BorderLayout.BEFORE_FIRST_LINE);
simpsonFrame.add(p2, BorderLayout.CENTER);
simpsonFrame.setSize(425, 425);
simpsonFrame.setLocationRelativeTo(null);
simpsonFrame.setVisible(true);
}//end method createPanel
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == homerBtn) {
homerFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == margeBtn) {
margeFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == bartBtn) {
bartFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == lisaBtn) {
lisaFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == maggieBtn) {
maggieFrame.setVisible(true);
simpsonFrame.setVisible(false);
}
else if(e.getSource() == closeBtn) {
System.exit(0);
}//end if
}//end event handler
}
public class HomerForm implements ActionListener{
JFrame simpsonFrame, homerFrame;
JButton closeBtn;
public HomerForm(JFrame simpsonFrame, JFrame homerFrame ) {
this.simpsonFrame = simpsonFrame;
this.homerFrame = homerFrame;
createPanel();
}
private void createPanel() {
homerFrame = new JFrame("Homer Simpson");
closeBtn = new JButton("Close");
closeBtn.setSize(200, 50);
ImageIcon ogImage = new ImageIcon(this.getClass().getResource("/homer1.png"));
JLabel ogLabel = new JLabel();
ogLabel.setIcon(ogImage);
JPanel p1 = new JPanel();
p1.add(ogLabel);
ImageIcon hwImage = new ImageIcon(this.getClass().getResource("/homer2.png"));
JLabel hwLabel = new JLabel();
hwLabel.setIcon(hwImage);
JPanel p2 = new JPanel();
p2.add(hwLabel);
ImageIcon cImage = new ImageIcon(this.getClass().getResource("/homer3.png"));
JLabel cLabel = new JLabel();
cLabel.setIcon(cImage);
JPanel p3 = new JPanel();
p3.add(cLabel);
JPanel p4 = new JPanel();
JTabbedPane tab = new JTabbedPane();
tab.setBounds(100, 100, 300, 300);
tab.add("Original", p1);
tab.add("HalfWay", p2);
tab.add("Current", p3);
tab.add("Close", p4);
p4.add(closeBtn);
closeBtn.setLayout(new BorderLayout());
closeBtn.addActionListener(this);
homerFrame.add(tab);
homerFrame.setResizable(false);
homerFrame.setSize(500, 500);
homerFrame.setLocationRelativeTo(null);
homerFrame.setVisible(false);
}
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == closeBtn) {
homerFrame.setVisible(false);
simpsonFrame.setVisible(true);
}//end if
else
{
System.exit(0);
}
}
}
When i run it, i get this image. simpsonsFrame
this is what happens when i click the homer button i then have to max it to see a blank screen.homerFrame.
when i set the homerFrame to visible, it displays what i what to appear if the button was pushed.it shows homerFrame then it shows the simpsonFrame.homersetVisible true
I need to arrange my buttons in a specific order but whatever modification I do it only changes the size of the buttons not the placement.
Sorry if this is a easy question, this is my first Java class and I am having trouble understanding how to arrange stuff and event handling.
public class SwingCalculator extends JFrame {
private JButton jbtReset;
private JButton jbtAdd;
private JButton jbtSubtract;
private double TEMP;
private double SolveTEMP;
private JTextField jtfResult;
Boolean addBool = false;
Boolean subBool = false;
String display = "";
public SwingCalculator()
{
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(4, 3));
p1.add(jbtReset = new JButton("Reset"));
JPanel p2 = new JPanel();
p2.setLayout(new FlowLayout());
p2.add(jtfResult = new JTextField(10));
jtfResult.setEditable(true);
JPanel p3 = new JPanel();
p3.setLayout(new GridLayout(5, 1));
p3.add(jbtAdd = new JButton("+"));
p3.add(jbtSubtract = new JButton("-"));
JPanel p = new JPanel();
p.setLayout(new GridLayout());
p.add(p2);
p.add(p1);
p.add(p3);
add(p);
jbtAdd.addActionListener(new ListenToAdd());
jbtSubtract.addActionListener(new ListenToSubtract());
jbtReset.addActionListener(new ListenToReset());
} //JavaCaluclator()
class ListenToReset implements ActionListener {
public void actionPerformed(ActionEvent e) {
//display = jtfResult.getText();
jtfResult.setText("");
addBool = false;
subBool = false;
TEMP = 0;
SolveTEMP = 0;
}
}
class ListenToAdd implements ActionListener {
public void actionPerformed(ActionEvent e) {
TEMP = Double.parseDouble(jtfResult.getText());
jtfResult.setText("");
addBool = true;
SolveTEMP = SolveTEMP + TEMP;
jtfResult.setText( Double.toString(SolveTEMP));
addBool = false;
subBool = false;
}
}
class ListenToSubtract implements ActionListener {
public void actionPerformed(ActionEvent e) {
TEMP = Double.parseDouble(jtfResult.getText());
jtfResult.setText("");
subBool = true;
SolveTEMP = SolveTEMP - TEMP;
jtfResult.setText( Double.toString(SolveTEMP));
addBool = false;
subBool = false;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
SwingCalculator calc = new SwingCalculator();
calc.pack();
calc.setLocationRelativeTo(null);
calc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
calc.setVisible(true);
}
} //JavaCalculator
My result:
Expected result:
You can use GridBagLayout with various options.
Eg:
GridBagLayout grid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(grid);
//add TF
gbc.gridx=1;
gbc.gridy=0;
this.add(new JTextField(10),gbc);
gbc.gridx=0;
gbc.gridy=1;
this.add(new JButton("+"),gbc);
gbc.gridx=1;
this.add(new JButton("-"),gbc);
gbc.gridx=2;
this.add(new JButton("Reset"),gbc);
//also for another display (first TF will be on the same x as - Button)
//(and maybe you want TF to cover the space for all 3 Button +,-,Reset)
//you could add 2 panels one over other (x=0 : y=0,y=1), place TF on P1 and all Buttons on P2
I made a JFrame with JTextField, JPanel and a button in which the user inputs a value and after clicking the button, it will generate multiple labels based on the users input, but the JLabel doesnt appear. am i doing it wrong?
this is the coding for the button.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String s = jTextField1.getText();
int noSub = Integer.valueOf(s);
addData(noSub);
}
and this is the method to add JLabel.
public void addData(int a){
jPanel1.removeAll();
int num = a;
JLabel jLabel[] = new JLabel[num];
for(int i=0;i<num;i++){
jLabel[i]=new JLabel();
jLabel[i] = new JLabel("Label "+i);
jPanel1.add(jLabel[i]);
jPanel1.revalidate();
jPanel1.repaint();
}
jPanel1.updateUI();
}
Made a simple working example here:
public class Sample extends JFrame{
private JTextField inputField;
private JPanel outputPanel;
private Sample() {
JPanel mainPanel = new JPanel(new BorderLayout());
JPanel form = new JPanel(new GridBagLayout());
inputField = new JTextField(3);
JButton submitBtn = new JButton("Enter");
form.add(inputField);
form.add(submitBtn);
mainPanel.add(form, BorderLayout.NORTH);
outputPanel = new JPanel();
mainPanel.add(outputPanel);
submitBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String text = inputField.getText();
int noSub = Integer.valueOf(text);
addData(noSub);
}
void addData(int data){
outputPanel.removeAll();
JLabel jLabel[] = new JLabel[data];
for(int i=0;i<data;i++){
jLabel[i] = new JLabel("Label "+i);
outputPanel.add(jLabel[i]);
}
outputPanel.revalidate();
outputPanel.repaint();
// No need to call outputPanel.updateUI()
}
});
setSize(400,500);
add(mainPanel);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Sample();
}
}
I need to make GUI which saves the user's input using a linked list and let him/her "browse" through the saved data. I made a simpler version of the code which I included below. My problem is how to "update" the buttons in the browse card after the user entered and saved a text.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class sampleDemo extends JPanel {
NodeSample newNode = new NodeSample();
SampleSave s = new SampleSave();
public static final String CARD_ADD = "Card Add";
public static final String CARD_BROWSE = "Card Browse";
public static CardLayout cardLayout = new CardLayout();
public static JPanel card = new JPanel(cardLayout);
public static sampleDemo sd = new sampleDemo();
public sampleDemo() {
WindowAdd wina = new WindowAdd();
card.add(wina, CARD_ADD);
WindowBrowse winb = new WindowBrowse();
card.add(winb, CARD_BROWSE);
setLayout(new BorderLayout());
add(card, BorderLayout.PAGE_END);
}
public static void createAndShowGUI() {
JPanel buttonPanel = new JPanel();
JButton addButton = new JButton("Add");
JButton browseButton = new JButton("Browse");
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
cardLayout.show(card, "Card Add");
}
});
browseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
cardLayout.show(card, "Card Browse");
}
});
buttonPanel.add(addButton);
buttonPanel.add(browseButton);
JFrame frame = new JFrame("Sample Demo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(buttonPanel, BorderLayout.PAGE_END);
frame.getContentPane().add(sd);
frame.setSize(300, 200);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
class WindowAdd extends JPanel {
public ActionListener action;
public WindowAdd() {
init();
}
public void init() {
JTextField textField = new JTextField(10);
NodeSample newNode = new NodeSample();
JPanel content = new JPanel(new FlowLayout());
JButton saveButton = new JButton("Save");
saveButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newNode.textContent = textField.getText();
s.insert(newNode);
}
});
content.add(textField);
content.add(saveButton);
textField.setText(null);
add(content);
}
}
class WindowBrowse extends JPanel {
public WindowBrowse() {
init();
}
public void init() {
setLayout(new GridLayout(1, 3));
JButton a = new JButton();
JButton b = new JButton();
JButton c = new JButton();
try {
a = new JButton(s.head.textContent);
b = new JButton(s.head.next.textContent);
c = new JButton(s.head.next.next.textContent);
}catch (NullPointerException e) {
//
}
add(a);
add(b);
add(c);
}
}
class NodeSample {
String textContent;
NodeSample next;
}
class SampleSave {
NodeSample head;
NodeSample tail;
public void insert(NodeSample add) {
if(head == null){
head = add;
tail = add;
}else {
add.next = head;
head = add;
}
}
}
}
In order to change the text on a JButton use something similar to this in your action listener
btn.setText(textfield.getText());
This will change the text of whatever button to the text entered in the textfield
I have a problem with a JList. When I select an item, it resizes itself. How can I set the JList to a fixed size?
Here is a screenshot before I selected anything
and this is after
Here is my code:
public class AgendaView extends JFrame {
private JLabel firstNameLabel, lastNameLabel, adressLabel, phoneNumberLabel, extraInfoLabel;
private Button editButton, addButton, deleteButton, showButton;
private JPanel labels, gui, buttons;
private DefaultListModel model;
private JList list;
private JMenuBar menuBar;
private JMenu menu;
private JMenuItem newItem, saveItem, saveAsItem, exitItem, openItem;
private Agenda agenda;
private JScrollPane scrollPane;
public AgendaView() {
super("***Agenda View***");
menuBar = new JMenuBar();
menu = new JMenu("Menu");
menu.add(new JSeparator());
newItem = new JMenuItem("New");
saveItem = new JMenuItem("Save");
saveItem.setEnabled(false);
saveAsItem = new JMenuItem("Save as..");
saveAsItem.setEnabled(false);
exitItem = new JMenuItem("Exit");
openItem = new JMenuItem("Open");
saveItem.add(new JSeparator());
exitItem.add(new JSeparator());
menu.add(newItem);
menu.add(openItem);
menu.add(saveItem);
menu.add(saveAsItem);
menu.add(exitItem);
gui = new JPanel(new BorderLayout(2, 2));
gui.setBorder(new TitledBorder("Owner"));
labels = new JPanel(new GridLayout(0, 1, 1, 1));
labels.setBorder(new TitledBorder("Contact "));
buttons = new JPanel(new GridLayout(1, 0, 1, 1));
editButton = new Button("Edit");
addButton = new Button("Add");
deleteButton = new Button("Delete");
showButton = new Button("Show");
editButton.setEnabled(false);
addButton.setEnabled(false);
deleteButton.setEnabled(false);
showButton.setEnabled(false);
buttons.add(showButton);
buttons.add(editButton);
buttons.add(addButton);
buttons.add(deleteButton);
firstNameLabel = new JLabel("First name: ");
lastNameLabel = new JLabel("Last name: ");
adressLabel = new JLabel("Adress: ");
phoneNumberLabel = new JLabel("Phone number: ");
extraInfoLabel = new JLabel("Extra info: ");
labels.add(firstNameLabel);
labels.add(lastNameLabel);
labels.add(adressLabel);
labels.add(phoneNumberLabel);
labels.add(extraInfoLabel);
model = new DefaultListModel();
list = new JList(model);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setVisibleRowCount(-1);
list.addListSelectionListener(
new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent lse) {
String name = list.getSelectedValue().toString();
String[] split = name.split(" ");
Contact contact = agenda.searchContactbyName(split[0], split[1]);
firstNameLabel.setText("First name: " + contact.getFirstName());
lastNameLabel.setText("Last name: " + contact.getLastName());
adressLabel.setText("Adress: " + contact.getAdress());
phoneNumberLabel.setText("Phone number: " + contact.getPhoneNumber());
if (contact.getType().compareTo("Acquaintance") == 0) {
extraInfoLabel.setText("Occupation: " + contact.getExtraInfo());
} else if (contact.getType().compareTo("Colleague") == 0) {
extraInfoLabel.setText("Email: " + contact.getExtraInfo());
} else if (contact.getType().compareTo("Friend") == 0) {
extraInfoLabel.setText("Birthdate: " + contact.getExtraInfo());
} else {
extraInfoLabel.setVisible(false);
}
}
});
scrollPane = new JScrollPane(list);
gui.add(labels, BorderLayout.CENTER);
gui.add(scrollPane, BorderLayout.WEST);
gui.add(buttons, BorderLayout.SOUTH);
add(gui);
menuBar.add(menu);
setJMenuBar(menuBar);
Here is where I display the GUI:
public class JavaLab3_pb1Java {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
Agenda agenda = new Agenda();
AgendaView agendaView = new AgendaView();
agendaView.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
agendaView.setSize(500, 300);
agendaView.pack();
agendaView.setVisible(true);
}
}
You need to call pack() on your JFrame after adding all components and before calling setVisible(true) on it. This will tell the GUI's layout managers to manage their layouts, and will resize the GUI to the preferred size as specified by the components and the layouts.
Edit
Never call setSize(...) on anything. Better to override getPreferredSize(). For example, my sscce:
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
public class AgendaView extends JFrame {
private static final int PREF_W = 500;
private static final int PREF_H = 300;
private JLabel firstNameLabel, lastNameLabel, adressLabel, phoneNumberLabel,
extraInfoLabel;
private JButton editButton, addButton, deleteButton, showButton;
private JPanel labels, gui, buttons;
private DefaultListModel<String> model;
private JList<String> list;
private JScrollPane scrollPane;
public AgendaView() {
super("***Agenda View***");
gui = new JPanel(new BorderLayout(2, 2));
gui.setBorder(new TitledBorder("Owner"));
labels = new JPanel(new GridLayout(0, 1, 1, 1));
labels.setBorder(new TitledBorder("Contact "));
buttons = new JPanel(new GridLayout(1, 0, 1, 1));
editButton = new JButton("Edit");
addButton = new JButton("Add");
deleteButton = new JButton("Delete");
showButton = new JButton("Show");
editButton.setEnabled(false);
addButton.setEnabled(false);
deleteButton.setEnabled(false);
showButton.setEnabled(false);
buttons.add(showButton);
buttons.add(editButton);
buttons.add(addButton);
buttons.add(deleteButton);
firstNameLabel = new JLabel("First name: ");
lastNameLabel = new JLabel("Last name: ");
adressLabel = new JLabel("Adress: ");
phoneNumberLabel = new JLabel("Phone number: ");
extraInfoLabel = new JLabel("Extra info: ");
labels.add(firstNameLabel);
labels.add(lastNameLabel);
labels.add(adressLabel);
labels.add(phoneNumberLabel);
labels.add(extraInfoLabel);
model = new DefaultListModel<String>();
list = new JList<String>(model);
String[] eles = { "Ciprian Aftode", "Andrei Batinas", "Bogdan Fichitiu",
"Valentin Pascau" };
for (String ele : eles) {
model.addElement(ele);
}
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// list.setVisibleRowCount(-1);
list.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent lse) {
firstNameLabel.setText("First name: first name");
lastNameLabel.setText("Last name: last name");
adressLabel.setText("Address: Address");
phoneNumberLabel.setText("Phone number: PhoneNumber");
extraInfoLabel.setText("Occupation: ExtraInfo");
}
});
int ebGap = 8;
list.setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
scrollPane = new JScrollPane(list);
gui.add(labels, BorderLayout.CENTER);
gui.add(scrollPane, BorderLayout.WEST);
gui.add(buttons, BorderLayout.SOUTH);
add(gui);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
AgendaView frame = new AgendaView();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}