I have a panel which contains JList.
When i add this panel to west BorderLayout with one element everything is OK and i see one element in it but if i add new element or clear all element i see no effect.
Can any body suggest any solution?
JPanel class which contains JList
public class FtpPanel extends JPanel{
public JList ftpJList;
public DefaultListModel ftpListModel;
public FtpPanel(String[] list) {
this.setLayout(new BorderLayout());
this.setBorder(new EmptyBorder(20, 20, 20, 20));
this.ftpListModel = new DefaultListModel();
for(String s : list){
this.ftpListModel.addElement(s);
}
this.ftpJList = new JList(ftpListModel);
final JScrollPane wsp = new JScrollPane(this.ftpJList);
wsp.setBorder(new TitledBorder(new WebBorder(),"ftpsrv.itra.de"));
this.add(wsp, BorderLayout.CENTER);
}
}
FtpTabPanel to which FtpPanel will be added
public class FtpTabPanel extends JPanel{
public FtpPanel ftpPanel;
public FtpTabPanel() {
createComponents();
layoutComponents();
initializeComponents();
}
private void createComponents() {
ftpPanel = new FtpPanel(new String[]{"You aren't Connected"});
}
private void layoutComponents() {
setLayout(new BorderLayout());
add(ftpPanel, BorderLayout.WEST);
}
}
Add and remove from Jlist
addFileToJlist(listOfFtpFile ){
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if(listOfFtpFile !=null)
ftpTabPanel.ftpPanel.ftpListModel.clear();
ftpTabPanel.ftpPanel.updateUI();
for(String s : listOfFtpFile){
ftpTabPanel.ftpPanel.ftpListModel.addElement(s);
ftpTabPanel.ftpPanel.ftpWebList.validate();
ftpTabPanel.ftpPanel.updateUI();
}
ftpTabPanel.ftpPanel.ftpWebList.revalidate();
panel.updateUI();
}
});
}
Here is a simple working example (that is almost same as yours but without unnecessary updates):
public static void main ( String[] args )
{
JFrame frame = new JFrame ();
final DefaultListModel model = new DefaultListModel ();
JList list = new JList ( model );
frame.add ( new JScrollPane ( list ) );
list.addMouseListener ( new MouseAdapter ()
{
public void mousePressed ( MouseEvent e )
{
model.clear ();
Random random = new Random ();
int max = random.nextInt ( 10 );
for ( int i = 0; i <= max; i++ )
{
model.addElement ( "" + random.nextInt ( 100 ) );
}
}
} );
frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
frame.setSize ( 200, 400 );
frame.setLocationRelativeTo ( null );
frame.setVisible ( true );
}
And i don't really see any problems in your example (except unnecessary validation and updateUI calls). Seems that problem is somewhere else...
I had a similar problem recently. Solved it simply like this :
(Add elements to Jlist)
Jlist.setVisible(false);
Jlist.setVisible(true);
Only way it worked by me, don´t know why.
Related
I have made this simple text editor program but can't figure out how to change GUI component's properties while the program is running.
Suppose this is a part of my Text Editor's source code:
boolean wordwrap = false;
void mainFrame() {
frame = new JFrame("Text Editor");
textArea = new JTextArea(50,20);
textArea.setLineWrap(wordwrap);
and let's say I have an event source(JButton) added as Listener to change
textArea's .setLineWrap(boolean). Just like this:
public void actionPerformed(ActionEvent event) {
if(wordwrap) wordwrap = false;
else wordwrap = true;
textArea.setLineWrap(wordwrap);
frame.repaint();
}
But this code is not working!!. So, what is the correct way to update or edit a JAVA GUI component while the program is running ?
revalidate and validate()
will update the frame.
You do not need to use repaint().
Final Method:
public void actionPerformed(ActionEvent event) {
if(wordwrap) wordwrap = false;
else wordwrap = true;
textArea.setLineWrap(wordwrap);
frame.revalidate(); //is preferable but validate() also works.
}
You can either update the whole frame or just update the jComponent (insert TextArea instead of "frame".revalidate();)
Just FYI, after I got a chance to test it, it works fine without either the revalidate() or the repaint(). I suspect the problem was somewhere else in your code.
public class TestTextArea
{
private final static String testLine =
"This is some rather long line that I came up with for testing a textArea.";
public static void main(String[] args) {
SwingUtilities.invokeLater( new Runnable() {
public void run()
{
gui();
}
} );
}
private static void gui()
{
JFrame frame = new JFrame();
final JTextArea textArea = new JTextArea();
JPanel span = new JPanel();
JButton toggle = new JButton( "Switch line wrap" );
toggle.addActionListener( new ActionListener()
{
#Override
public void actionPerformed( ActionEvent e )
{
textArea.setLineWrap( !textArea.getLineWrap() );
}
} );
for( int i = 0; i < 10; i++ )
textArea.append( testLine + testLine + "\n" );
span.add( toggle );
frame.add( span, BorderLayout.SOUTH );
frame.add( textArea );
frame.pack();
frame.setSize( 500, 500 );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setLocationRelativeTo( null );
frame.setVisible( true );
}
}
I am having an issue with my horizontal scroll bar demo. I am trying to move a custom message panel using the scroll bar. I used an anonymous listener and override the adjustmentValueChanged() method like so,
public void adjustmentValueChanged(AdjustmentEvent e){
System.out.println(e.getAdjustmentType());
if( e.getAdjustmentType() == AdjustmentEvent.UNIT_INCREMENT ) {
panel.moveLeft();
}
}
I am trying to get the AdjustmentEvent using e.getAdjustmentType() so I can properly handle the adjustment of the message panel. However, it is not working. I used System.out.println() method to print the adjustment type on my screen to see what the problem is but what I am not understanding is that no matter what part of the scroll bar I press (whether it is the unit increment, unit decrement, block increment, etc..) the value returned is 5? I am not sure what the issue is can someone please help.
public class ScrollBarDemo extends JFrame {
private JScrollBar scrollHort = new JScrollBar(JScrollBar.HORIZONTAL);
private JScrollBar scrollVert = new JScrollBar(JScrollBar.VERTICAL);
private MessagePanel panel = new MessagePanel("Welcom to Java bitch");
public static void main(String[] args) {
ScrollBarDemo frame = new ScrollBarDemo();
frame.setTitle("ScrollBarDemo");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public ScrollBarDemo() {
setLayout(new BorderLayout());
add(panel, BorderLayout.CENTER);
add(scrollHort, BorderLayout.SOUTH);
add(scrollVert, BorderLayout.EAST);
scrollHort.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
System.out.println(e.getAdjustmentType());
if (e.getAdjustmentType() == AdjustmentEvent.UNIT_INCREMENT) {
panel.moveLeft();
}
}
});
}
}
Run the following sample, the method to use is getValue().
public class ScrollBarDemo extends JFrame {
public ScrollBarDemo() {
setLayout( new BorderLayout());
final JScrollBar scrollHort = new JScrollBar( JScrollBar.HORIZONTAL );
add( scrollHort, BorderLayout.SOUTH );
scrollHort.addAdjustmentListener( e -> System.out.println( e.getValue()));
setLocationRelativeTo(null);
setDefaultCloseOperation( EXIT_ON_CLOSE );
pack();
setVisible(true);
}
public static void main( String[] args ) {
new ScrollBarDemo();
}
}
Error:
error: cannot find symbol
What appears doesn't works:
If I write: "InvoerVakhandler extends boven" then the error disapears but then I get an endless loop and in the end the program crashes and says stack overflow error.
If I try to change the "}" symbol from class boven and place it in the end of the text then I even get more error messages.
Question: What do I have to change in my code to make it work?
Note:
I'm new to Java and I know there are more posts like this one but I just can't apply them to my code with my current limited understanding of Java.
If someone wants to know: I'm using JCreator.
What i'm trying to make: What I'm trying to make is fairly simple.
1) Fill in a name in the JTextField, press enter and the name should appear in the JTextArea. After the name is in the JTextArea the JTextField becomes empty so you can fill another name and so on there should appear a list of names in JTextArea. (this is what I'm now trying to make)
2) Push the button kiesWin to make the program choose a random person from the list.
3) Push the button resetL to reset the program so I can make a new list to choose a random winner from it.
Part of the code where the error appears: (from the class InvoerVakHandler)
String invoer = invoervak1.getText();
With my limited knowledge of java the problem could be litterly anywhere so in case I will post the whole code.
Whole code:
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
// Main method to make the frame
public class Loterij3 extends JFrame {
public static void main( String args[] ) {
JFrame frame = new Loterij3();
frame.setExtendedState( frame.MAXIMIZED_BOTH );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setTitle( "Klanten Register" );
frame.setContentPane( new Paneel() );
frame.setVisible( true );
}
}
class Paneel extends JPanel {
private boven Boven;
JTextArea textvak1;
JTextField textvak2;
OnthoudNaam onthoudNaam = new OnthoudNaam();
public Paneel() {
setLayout( new BorderLayout() ); // using border Layout.
setBackground( Color.LIGHT_GRAY );
textvak1 = new JTextArea();
add( new JScrollPane( textvak1 ) );
textvak1.setBackground( Color.WHITE );
textvak2 = new JTextField();
textvak2.setHorizontalAlignment(JTextField.CENTER);
textvak2.setEditable( false );
Boven = new boven();
add( Boven, BorderLayout.NORTH );
add( textvak1, BorderLayout.CENTER );
add( textvak2, BorderLayout.SOUTH );
}
public class boven extends Paneel {
JButton kiesWin, resetL;
JLabel label1;
JTextField invoervak1;
public boven() {
setBackground( Color.LIGHT_GRAY );
setLayout( new GridLayout( 1, 4, 100, 5 ) ); // using GridLayout.
Border border =
BorderFactory.createEmptyBorder( 10, 10, 10, 10 );
setBorder( border );
kiesWin = new JButton("Kies een Winnaar!");
kiesWin.addActionListener( new kies() );
resetL = new JButton("Reset alles");
resetL.addActionListener( new reset() );
label1 = new JLabel("Voer Persoon in en druk op enter: ", JLabel.RIGHT);
invoervak1 = new JTextField( 20 );
invoervak1.addActionListener( new InvoerVakHandler() );
add( label1 );
add( invoervak1 );
add( kiesWin );
add( resetL );
}
}
// de naam
class naam {
private String ingevoerdNaam;
public naam( String ingevoerdNaam) {
this.ingevoerdNaam = ingevoerdNaam;
}
public String getIngevoerdNaam() {
return ingevoerdNaam;
}
}
// Arraylist
class OnthoudNaam extends JPanel {
private ArrayList<naam> lijst;
public OnthoudNaam() {
lijst = new ArrayList<naam>();
}
public void voegNaamToe(naam x ) {
lijst.add(x);
}
public String toString() {
StringBuffer buffer = new StringBuffer();
for(naam x : lijst ) {
buffer.append( x );
buffer.append( "\n" );
}
return buffer.toString();
}
}
// this is the part where the code goes wrong
public class InvoerVakHandler implements ActionListener {
public void actionPerformed( ActionEvent e ) {
String invoer = invoervak1.getText();
naam naam = new naam( invoer );
onthoudNaam.voegNaamToe( naam );
textvak1.setText( onthoudNaam.toString() );
}
}
// kies
class kies implements ActionListener {
public void actionPerformed( ActionEvent e ) {
}
}
// reset
class reset implements ActionListener {
public void actionPerformed( ActionEvent e ) {
}
}
}
For everyone who is trying to help me: Thank you for all your help and patience in advance!
The line in question in in class: InvoerVakHandler
The variable is defined in class: boven
That is why it can't find it.
I think you can get the source of the event from the ActionEvent passed to the actionPerformed() method.
Note that normally we use an upper-case letter to begin the name of any class and lower case to begin methods and variables. (Constants are an exception.)
The variable invoervak1 is defined in the boven class and is not visible within InvoerVakHandler. Since InvoerVakHandler is registered exclusively with the invoervak1 component, you can use the source object of your ActionListener to obtain the reference to the JTextField:
JTextField textField = (JTextField) e.getSource();
String invoer = textField.getText();
Typically anonymous ActionListener implementations are used. This makes the intended source clear along with its associated functionality.
The error goes away with the answers from Reimeus. However your program will not run because you created a stackoverflow.
In the class Paneel you call
Boven = new boven();
However boven extends from your Paneel class. So Java needs to build a Paneel instance when building a Boven instance which will require a Paneel and so on.
Make boven extend from JPanel and your GUI starts and works.
However your output will look like this
Paneel$naam#3dee7a6c
This happens because your class "naam" did not overwritte the toString method and so Object.toString is called which produces a String based on the class name and hashCode of a Object.
So extend your naam class to this:
class naam {
private String ingevoerdNaam;
public naam( String ingevoerdNaam) {
this.ingevoerdNaam = ingevoerdNaam;
}
public String getIngevoerdNaam() {
return ingevoerdNaam;
}
public String toString() {
return ingevoerdNaam;
}
}
Hope this helps. And like mentioned already please stick to the Java Coding Conventions.
I have 6 JLabel and each is having a different instance of a mouselistener class attached. How to know which JLabel has been clicked ? These JLabel form a two dimentional array.
You use getSource to get a refrence to the object which is clicked on:
label1.addActionListener(new yourListener());
label2.addActionListener(new yourListener());
public class yourListener extends MouseAdapter{
public void mouseClicked(MouseEvent e){
JLabel labelReference=(JLabel)e.getSource();
labelReference.someMethod();
}
}
The easiest way I did something like that was, to use JButtons and make them look like JLabels by the using this syntax formatting.
jButton.setBorder( BorderFactory.createEmptyBorder( 2, 2, 2, 2 ) );
jButton.setBorderPainted( false );
jButton.setContentAreaFilled( false );
jButton.setFocusPainted( false );
jButton.setHorizontalAlignment( SwingConstants.LEFT );
Then, what you want to is add an ActionLister and a ActionCommand. For example
jButton.addActionListener( this );
jButton.setActionCommand( "label1" );
Then just handle the actionListners to do what you wanted for each label.
public void actionPerformed( ActionEvent arg0 )
{
String command = arg0.getActionCommand();
if( command.equalsIgnoreCase( "label1" ) )
{
//label1 code
}
}
As mentioned below this also has the added benefit of supporting both keyboard and mouse activities.
I put this together based on your description:
public static void main(String[] args) {
JFrame f = new JFrame();
f.setLayout(new FlowLayout());
for (int i = 0; i < 6; i++) {
JLabel l = new JLabel("Label " + (i + 1));
l.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
JLabel l = (JLabel) e.getSource(); // here
System.out.println(l.getText());
}
});
f.add(l);
}
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
I think the line marked // here is mostly what you need.
I need some help to be able to add element to a JList and how to select element whith event.
This is my JList:
DefaultListModel model = new DefaultListModel();
JList list = new JList(model);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
JScrollPane listScroller = new JScrollPane(list);
listScroller.setPreferredSize(new Dimension(430, 80));
This is part of my actionlistener that handle different buttons. It's here I want to use model.add("Name"); bot I get a red underline in Eclipse!?
public void actionPerformed(ActionEvent event){
// New customer
if(event.getSource() == buttonNewCustomer && statusButtonNewCustomer)
{
String name = textInputName.getText();
String number = textInputPersonalNumber.getText();
boolean checkCustomerExist = customHandler.findCustomer(name, number);
if(!checkCustomerExist) // If not true add new customer
{
customHandler.addCustomer(name, number); // Call method to add name
setTitle(title + "Kund: " + name); // Set new title
model.addElement(name);
}
}
}
Then I would preciate some help how I should select the element inside the JList? Should I use implements ActionListener to the class or a FrameHandler object? Thanks!
EDIT: My main problem that I can't solve is that the JList is inside the construcor and when I use model.add("name"); inside the constructor it works, but it's not working when I want to add something outside the constructor? I have read the tutorial several times, but can't find any help for this.
EDIT 2: The completet code. Probably some out of scope problem?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI4EX extends JFrame implements ActionListener{
private JButton buttonNewCustomer, buttonTerminate, buttonAddNewName, buttonAddNewSavingsAccount, buttonAddNewCreditAccount;
private JLabel textLabelName, textLabelPersonalNumber, textLabelNewName;
private JTextField textInputName, textInputPersonalNumber, textInputNewName;
private JPanel panelNewCustomer, panelQuit, panelNewAccount, panelChangeName, panelSelectCustomer;
private boolean statusButtonNewCustomer = true;
private boolean statusButton2 = true;
private boolean statusButtonAddNewName = true;
private String title = "Bank ";
// Create a customHandler object
CustomHandler customHandler = new CustomHandler();
// Main method to start program
public static void main(String[] args){
GUI4EX frame = new GUI4EX();
frame.setVisible(true);
frame.setDefaultCloseOperation(3);
}
// Cunstructor
public GUI4EX(){
// Create window
setTitle(title);
setSize(450,500);
setLocation(400,100);
setResizable(false);
// Set layout to boxlayout
Container container = getContentPane( );
setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
DefaultListModel model = new DefaultListModel();
JList list = new JList(model);
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
JScrollPane listScroller = new JScrollPane(list);
listScroller.setPreferredSize(new Dimension(430, 80));
model.addElement("test");
model.addElement("test");
model.addElement("test");
model.addElement("test");
model.addElement("test");
model.addElement("test");
// Create jpanels
panelNewCustomer = new JPanel();
panelQuit = new JPanel();
panelNewAccount = new JPanel();
panelChangeName = new JPanel();
panelSelectCustomer = new JPanel();
// Create and add components - buttons
buttonNewCustomer = new JButton("OK");
buttonTerminate = new JButton("Avsluta");
buttonAddNewName = new JButton("OK");
buttonAddNewSavingsAccount = new JButton("Sparkonto");
buttonAddNewCreditAccount = new JButton("Kreditkonto");
// Create and add components - labels
textLabelName = new JLabel("Namn");
textLabelPersonalNumber = new JLabel("Personnummer");
textLabelNewName = new JLabel("Nytt namn");
//add(textLabel1);
// Create and add components - textfields
textInputName = new JTextField("");
textInputPersonalNumber = new JTextField("");
textInputName.setColumns(10);
textInputPersonalNumber.setColumns(10);
textInputNewName = new JTextField();
textInputNewName.setColumns(20);
// Add components to panel new customer
panelNewCustomer.add(textLabelName);
panelNewCustomer.add(textInputName);
panelNewCustomer.add(textLabelPersonalNumber);
panelNewCustomer.add(textInputPersonalNumber);
panelNewCustomer.add(buttonNewCustomer);
// Add components to panel to select customer
panelSelectCustomer.add(listScroller);
// Add components to panel new name
panelChangeName.add(textLabelNewName);
panelChangeName.add(textInputNewName);
panelChangeName.add(buttonAddNewName);
// Add components to panel new accounts
panelNewAccount.add(buttonAddNewSavingsAccount);
panelNewAccount.add(buttonAddNewCreditAccount);
// Add components to panel quit
panelQuit.add(buttonTerminate);
// Set borders to jpanels
panelNewCustomer.setBorder(BorderFactory.createTitledBorder("Skapa ny kund"));
panelChangeName.setBorder(BorderFactory.createTitledBorder("Ändra namn"));
panelNewAccount.setBorder(BorderFactory.createTitledBorder("Skapa nytt konto"));
panelQuit.setBorder(BorderFactory.createTitledBorder("Avsluta programmet"));
panelSelectCustomer.setBorder(BorderFactory.createTitledBorder("Välj kund"));
// Add panels to window
add(panelNewCustomer);
add(panelSelectCustomer);
add(panelChangeName);
add(panelNewAccount);
add(panelQuit);
// Listener
// FrameHandler handler = new FrameHandler();
// Add listener to components
//button1.addActionListener(handler);
buttonNewCustomer.addActionListener(this);
buttonAddNewName.addActionListener(this);
buttonAddNewSavingsAccount.addActionListener(this);
buttonAddNewCreditAccount.addActionListener(this);
buttonTerminate.addActionListener(this);
}
//private class FrameHandler implements ActionListener{
public void actionPerformed(ActionEvent event){
// New customer
if(event.getSource() == buttonNewCustomer && statusButtonNewCustomer)
{
String name = textInputName.getText();
String number = textInputPersonalNumber.getText();
boolean checkCustomerExist = customHandler.findCustomer(name, number); // Check if customer exist
if(!checkCustomerExist) // If not true add new customer
{
customHandler.addCustomer(name, number); // Call method to add name
setTitle(title + "Kund: " + name); // Set new title
model.addElement("name");
}
}
// Change name
if(event.getSource() == buttonAddNewName && statusButtonAddNewName)
{
String newName = textInputNewName.getText();
customHandler.changeName(newName); // call method to change name
setTitle(title + "Kund: " + newName);
}
// Create new savings account
if(event.getSource() == buttonAddNewSavingsAccount)
{
customHandler.CreateNewSavingsAccount();
}
// Create new credit account
if(event.getSource() == buttonAddNewCreditAccount)
{
customHandler.CreateNewCreditAccount();
}
// Terminate program
if(event.getSource()==buttonTerminate && statusButton2)
{
System.exit(3);
}
}
//}
}
You are lucky I am in a good mood. Here a very basic example, matching the code you provided. Type something in the textfield, hit the enter button and watch the list get populated.
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AddToJListDemo {
private static JFrame createGUI(){
JFrame frame = new JFrame( );
final DefaultListModel model = new DefaultListModel();
JList list = new JList( model );
final JTextField input = new JTextField( 10 );
input.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent aActionEvent ) {
String text = input.getText();
if ( text.length() > 0 ) {
model.addElement( text );
input.setText( "" );
}
}
} );
frame.add( list, BorderLayout.CENTER );
frame.add( input, BorderLayout.SOUTH );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
return frame;
}
public static void main( String[] args ) {
EventQueue.invokeLater( new Runnable() {
public void run() {
JFrame frame = createGUI();
frame.setSize( 200,200 );
frame.setVisible( true );
}
} );
}
}
Edit
Based on your full code, you must make the list a field in your GUI4EX class, similar to for example the buttonNewCustomer field
public class GUI4EX extends JFrame implements ActionListener{
//... all other field
DefaultListModel model;
//constructor
public GUI4EX(){
//all other code
//DefaultListModel model = new DefaultListModel(); instantiate the field instead
model = new DefaultListModel();
JList list = new JList(model);
//rest of your code
}
}
This will make sure you can access the model in the actionPerformed method. But if you cannot figure out something this basic, you should not be creating GUIs but reading up on basic Java syntax and OO principles