Problem in repainting jtextarea
My requirement is, client has to sent string messages and server has to receive these messages and display it in jtextarea. In my code sending and receiving are done properly, but the problem is the jtextarea is not updated, it goes blank.
I have attached the client and server files, can anyone solve my problem?
Thanks in advance.
//server file
import java.net.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import java.util.*;
import java.text.*;
import java.awt.*;
import java.awt.event.*;
public class MessageCenter extends javax.swing.JFrame {
public MessageCenter() {
initComponents();
private void initComponents() {
jLabel1 = new JLabel();
jScrollPane1 = new JScrollPane();
jTextArea1 = new JTextArea();
jPanel1 = new JPanel();
jLabel5 = new JLabel();
jLabel3 = new JLabel();
jButton1 = new JButton();
jButton2 = new JButton();
jLabel2 = new JLabel();
jLabel4 = new JLabel();
menuBar = new JMenuBar();
fileMenu = new JMenu();
Start = new JMenuItem();
jSeparator1 = new JSeparator();
Stop = new JMenuItem();
jSeparator2 = new JSeparator();
Exit = new JMenuItem();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setTitle("Message Center");
setMaximizedBounds(new java.awt.Rectangle(0, 0, 560, 700));
setBounds(0,0,600,700);
setName("");
jLabel1.setBackground(new java.awt.Color(255, 255, 255));
jLabel1.setFont(new java.awt.Font("Georgia", 1, 24));
jLabel1.setForeground(new java.awt.Color(34, 44, 106));
jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
jLabel1.setText("Message Center");
jLabel1.setIconTextGap(0);
getContentPane().add(jLabel1, java.awt.BorderLayout.NORTH);
jTextArea1.setColumns(20);
jTextArea1.setFont(new java.awt.Font("Book Antiqua", 0, 12));
jTextArea1.setLineWrap(true);
jTextArea1.setRows(25);
jTextArea1.setBorder(null);
jScrollPane1.setViewportView(jTextArea1);
getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
jPanel1.setLayout(new java.awt.GridLayout(1, 6, 10, 5));
jPanel1.add(jLabel5);
jPanel1.add(jLabel3);
jButton1.setText("Start");
jPanel1.add(jButton1);
jButton2.setText("Stop");
jPanel1.add(jButton2);
jPanel1.add(jLabel2);
jPanel1.add(jLabel4);
getContentPane().add(jPanel1, java.awt.BorderLayout.SOUTH);
fileMenu.setText("File");
Start.setText("Start");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("hello");
StartActionPerformed(evt);
fileMenu.add(Start);
fileMenu.add(jSeparator1);
Stop.setText("Stop");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
StopActionPerformed(evt);
fileMenu.add(Stop);
fileMenu.add(jSeparator2);
Exit.setText("Exit");
fileMenu.add(Exit);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
pack();
private void StartActionPerformed(java.awt.event.ActionEvent evt) {
try{
Server t=new Server(jTextArea1);
t.listenSocket();
catch(Exception e)
e.printStackTrace();
private void StopActionPerformed(java.awt.event.ActionEvent evt) {
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MessageCenter().setVisible(true);
private JMenuItem Exit;
private JMenuItem Start;
private JMenuItem Stop;
private JMenu fileMenu;
private JButton jButton1;
private JButton jButton2;
private JLabel jLabel1;
private JLabel jLabel2;
private JLabel jLabel3;
private JLabel jLabel4;
private JLabel jLabel5;
private JPanel jPanel1;
private JScrollPane jScrollPane1;
private JSeparator jSeparator1;
private JSeparator jSeparator2;
public JTextArea jTextArea1;
private JMenuBar menuBar;
class ClientThread implements Runnable {
private Socket client;
JTextArea jt;
ClientThread(Socket client,JTextArea jt) {
this.client = client;
this.jt=jt;
public void run(){
try{
//DataInputStream dis= new DataInputStream(client.getInputStream());
DataInputStream dis= new DataInputStream(new BufferedInputStream(client.getInputStream()));
System.out.println("client connected");
//BufferedReader dis = new BufferedReader(new InputStreamReader(s.getInputStream()));
String msg=null;
byte msg1[]=new byte[200];
while(true)
try{
if(dis.available()>0)
dis.readFully(msg1,0,dis.available());
// System.out.println("Msg is ==> "+new String(msg1));
new PrinterThread(jt,new String(msg1)).start();
msg1=new byte[200];
Thread.sleep(1000);
}catch (Exception e) {
System.out.println("Exception ");
} catch (IOException e) {
System.out.println("Exception occurred");
class Server {
JTextArea jt;
public Server(JTextArea jt)
this.jt=jt;
public void listenSocket() throws Exception
ServerSocket ss=null;
try{
ss=new ServerSocket(8000);
System.out.println("Server started");
catch (IOException e) {
System.out.println("Exception");
System.exit(-1);
while(true){
ClientThread w;
try{
w = new ClientThread(ss.accept(),jt);
Thread t = new Thread(w);
t.start();
catch (IOException e) {
System.out.println("Accept failed: 8000");
public static void main(String args[])throws Exception {
/*Server t=new Server();
t.listenSocket();*/
class PrinterThread extends Thread
public PrinterThread(JTextArea jt1,String msg)
jTextArea1 = jt1;
this.msg=msg;
System.out.println("PrinterThread constructor ");
public void run()
try
Date today;
SimpleDateFormat formatter;
String output;
String pattern="dd.MM.yyyy '@' H:mm";
formatter = new SimpleDateFormat(pattern);
today = new Date();
output = formatter.format(today);
System.out.println(" "+output+" "+msg+" \n");
jTextArea1.append(" "+output+" "+msg+" \n");
jTextArea1.updateUI();
jTextArea1.revalidate();
// JOptionPane.showMessageDialog(null,"hi");
//System.out.println("Get text "+jTextArea1.getText());
catch (Exception exception) {}
private JComboBox combo;
private JTextArea jTextArea1;
String msg=null;
//client.java
import java.net.*;
import java.io.*;
import java.io.File;
public class client {
public static void main(String args[]) {
try {
Socket ss=new Socket(InetAddress.getLocalHost(),8000);
DataOutputStream dos=new DataOutputStream(ss.getOutputStream());
for(int i=1;i<100;i++){
if((i%2)==0)
dos.writeBytes("1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,3233");
else
dos.writeBytes("1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42");
Thread.sleep(5000);
catch(Exception e) {
e.printStackTrace();
System.out.println(" ");
}
You need to run your Server in a separate Thread.
Right now its running in the GUI Event Thread.I created new thread for my server, now it's updating jtextarea.
Thank you very much.
Similar Messages
-
Problem with repaint of display after a click event
Hi,
I have a problem with repaint of display. In particular in method keyPressed() i inserted a statement that, after i clicked bottom 2 of phone, must draw a string. But this string doesn't drawing.
Instead if i reduce to icon the window, which emulate my application, and then i enlarge it, i see display repainted with the string.
I don't know why.
Any suggestions?
Please help me.modified your code little
don't draw in keyPressed
import java.io.IOException;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
public class PlayerCanvas extends Canvas implements CommandListener{
Display display;
Displayable dsp11;
private Image play, pause, stop, next, previous = null;
private int gamcode;
private Command quitCmd = new Command("Back", Command.ITEM, 1);
public PlayerCanvas(Display display,Displayable dsp11){
this.display =display;
this.dsp11 =dsp11;
addCommand(quitCmd);
createController();
setCommandListener(this);
display.setCurrent(this);
protected void paint(Graphics g)
g.setColor(255,200,150);
g.fillRect(0, 0, getWidth(), getHeight());
if (play != null){
g.drawImage(play, getWidth()/5, getHeight()-50, Graphics.BOTTOM | Graphics.HCENTER);
if (stop != null){
g.drawImage(stop, getWidth()/5, getHeight()-10, Graphics.BOTTOM | Graphics.HCENTER);
if (next != null){
g.drawImage(next, (getWidth()/5)+10, getHeight()-30, Graphics.BOTTOM | Graphics.LEFT);
if (previous != null){
g.drawImage(previous, (getWidth()/5)-30, getHeight()-30, Graphics.BOTTOM | Graphics.LEFT);
/////this will draw on key UP
g.setColor(0,0,0);
System.out.print(gamcode);
if(gamcode==Canvas.UP){
g.drawString("PROVA",10, 0, 0);
}else if(gamcode==Canvas.DOWN){
g.drawString("DIFFERENT",10, 30, 0);
private void createController()
try {
play = Image.createImage("/icon3.png");//replace your original images plz
pause = Image.createImage("/icon3.png");
stop = Image.createImage("/icon3.png");
next = Image.createImage("/icon3.png");
previous = Image.createImage("/icon3.png");
} catch (IOException e) {
play = null;
pause = null;
stop = null;
next = null;
previous = null;
if (play == null){
System.out.println("cannot load play.png");
if (pause == null){
System.out.println("cannot load pause.png");
if (stop == null){
System.out.println("cannot load stop.png");
if (next == null){
System.out.println("cannot load next.png");
if (previous == null){
System.out.println("cannot load previous.png");
protected void keyPressed(int keyCode)
repaint();
if ( (keyCode == 2) || (UP == getGameAction(keyCode)) ){
gamcode = UP;
repaint();
else if ( (keyCode == 8) || (DOWN == getGameAction(keyCode)) ){
gamcode =DOWN;
repaint();
else if ( (keyCode == 4) || (LEFT == getGameAction(keyCode)) ){
else if ( (keyCode == 6) || (RIGHT == getGameAction(keyCode)) ){
public void commandAction(Command arg0, Displayable arg1) {
// TODO Auto-generated method stub
if(arg0==quitCmd){
display.setCurrent(dsp11);
} -
My requirement is, client has to sent string messages and server has to receive these messages and display it in jtextarea. In my code sending and receiving are done properly, but the problem is the jtextarea is not updated, it goes blank.
I have attached the client and server files, can anyone solve my problem?
Thanks in advance.
//server file
import java.net.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import java.util.*;
import java.text.*;
import java.awt.*;
import java.awt.event.*;
public class MessageCenter extends javax.swing.JFrame {
public MessageCenter() {
initComponents();
private void initComponents() {
jLabel1 = new JLabel();
jScrollPane1 = new JScrollPane();
jTextArea1 = new JTextArea();
jPanel1 = new JPanel();
jLabel5 = new JLabel();
jLabel3 = new JLabel();
jButton1 = new JButton();
jButton2 = new JButton();
jLabel2 = new JLabel();
jLabel4 = new JLabel();
menuBar = new JMenuBar();
fileMenu = new JMenu();
Start = new JMenuItem();
jSeparator1 = new JSeparator();
Stop = new JMenuItem();
jSeparator2 = new JSeparator();
Exit = new JMenuItem();
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setTitle("Message Center");
setMaximizedBounds(new java.awt.Rectangle(0, 0, 560, 700));
setBounds(0,0,600,700);
setName("");
jLabel1.setBackground(new java.awt.Color(255, 255, 255));
jLabel1.setFont(new java.awt.Font("Georgia", 1, 24));
jLabel1.setForeground(new java.awt.Color(34, 44, 106));
jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
jLabel1.setText("Message Center");
jLabel1.setIconTextGap(0);
getContentPane().add(jLabel1, java.awt.BorderLayout.NORTH);
jTextArea1.setColumns(20);
jTextArea1.setFont(new java.awt.Font("Book Antiqua", 0, 12));
jTextArea1.setLineWrap(true);
jTextArea1.setRows(25);
jTextArea1.setBorder(null);
jScrollPane1.setViewportView(jTextArea1);
getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER);
jPanel1.setLayout(new java.awt.GridLayout(1, 6, 10, 5));
jPanel1.add(jLabel5);
jPanel1.add(jLabel3);
jButton1.setText("Start");
jPanel1.add(jButton1);
jButton2.setText("Stop");
jPanel1.add(jButton2);
jPanel1.add(jLabel2);
jPanel1.add(jLabel4);
getContentPane().add(jPanel1, java.awt.BorderLayout.SOUTH);
fileMenu.setText("File");
Start.setText("Start");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("hello");
StartActionPerformed(evt);
fileMenu.add(Start);
fileMenu.add(jSeparator1);
Stop.setText("Stop");
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
StopActionPerformed(evt);
fileMenu.add(Stop);
fileMenu.add(jSeparator2);
Exit.setText("Exit");
fileMenu.add(Exit);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
pack();
private void StartActionPerformed(java.awt.event.ActionEvent evt) {
try{
Server t=new Server(jTextArea1);
t.listenSocket();
catch(Exception e)
e.printStackTrace();
private void StopActionPerformed(java.awt.event.ActionEvent evt) {
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MessageCenter().setVisible(true);
private JMenuItem Exit;
private JMenuItem Start;
private JMenuItem Stop;
private JMenu fileMenu;
private JButton jButton1;
private JButton jButton2;
private JLabel jLabel1;
private JLabel jLabel2;
private JLabel jLabel3;
private JLabel jLabel4;
private JLabel jLabel5;
private JPanel jPanel1;
private JScrollPane jScrollPane1;
private JSeparator jSeparator1;
private JSeparator jSeparator2;
public JTextArea jTextArea1;
private JMenuBar menuBar;
class ClientThread implements Runnable {
private Socket client;
JTextArea jt;
ClientThread(Socket client,JTextArea jt) {
this.client = client;
this.jt=jt;
public void run(){
try{
//DataInputStream dis= new DataInputStream(client.getInputStream());
DataInputStream dis= new DataInputStream(new BufferedInputStream(client.getInputStream()));
System.out.println("client connected");
//BufferedReader dis = new BufferedReader(new InputStreamReader(s.getInputStream()));
String msg=null;
byte msg1[]=new byte[200];
while(true)
try{
if(dis.available()>0)
dis.readFully(msg1,0,dis.available());
// System.out.println("Msg is ==> "+new String(msg1));
new PrinterThread(jt,new String(msg1)).start();
msg1=new byte[200];
Thread.sleep(1000);
}catch (Exception e) {
System.out.println("Exception ");
} catch (IOException e) {
System.out.println("Exception occurred");
class Server {
JTextArea jt;
public Server(JTextArea jt)
this.jt=jt;
public void listenSocket() throws Exception
ServerSocket ss=null;
try{
ss=new ServerSocket(8000);
System.out.println("Server started");
catch (IOException e) {
System.out.println("Exception");
System.exit(-1);
while(true){
ClientThread w;
try{
w = new ClientThread(ss.accept(),jt);
Thread t = new Thread(w);
t.start();
catch (IOException e) {
System.out.println("Accept failed: 8000");
public static void main(String args[])throws Exception {
/*Server t=new Server();
t.listenSocket();*/
class PrinterThread extends Thread
public PrinterThread(JTextArea jt1,String msg)
jTextArea1 = jt1;
this.msg=msg;
System.out.println("PrinterThread constructor ");
public void run()
try
Date today;
SimpleDateFormat formatter;
String output;
String pattern="dd.MM.yyyy '@' H:mm";
formatter = new SimpleDateFormat(pattern);
today = new Date();
output = formatter.format(today);
System.out.println(" "+output+" "+msg+" \n");
jTextArea1.append(" "+output+" "+msg+" \n");
jTextArea1.updateUI();
jTextArea1.revalidate();
// JOptionPane.showMessageDialog(null,"hi");
//System.out.println("Get text "+jTextArea1.getText());
catch (Exception exception) {}
private JComboBox combo;
private JTextArea jTextArea1;
String msg=null;
//client.java
import java.net.*;
import java.io.*;
import java.io.File;
public class client {
public static void main(String args[]) {
try {
Socket ss=new Socket(InetAddress.getLocalHost(),8000);
DataOutputStream dos=new DataOutputStream(ss.getOutputStream());
for(int i=1;i<100;i++){
if((i%2)==0)
dos.writeBytes("1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,3233");
else
dos.writeBytes("1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42");
Thread.sleep(5000);
catch(Exception e) {
e.printStackTrace();
System.out.println(" ");
}You need to run your Server in a separate Thread.
Right now its running in the GUI Event Thread.I created new thread for my server, now it's updating jtextarea.
Thank you very much. -
Problem with repaint() in JPanel
Hi,
This is the problem: I cyclically call the repaint()-method but there is no effect of it.
When does it appear: The problem occurs by calling the repaint()-method of a JPanel -class.
This is what i am doing: The repaint() is called from a different class which is my GUI. I do this call in an endless loop which is done within a Thread.
I tried to add a KeyListener to the JPanel-class and there I called the repaint()-method when i press a Key. Then the Panel is repainted.
so I implemented a "callRepaint"-method in the JPanel-class that does nothing else than call repaint() (just like the keyPressed()-method does). But when i cyclically call this "callRepaint"-method from my GUI nothing happens.
Now a few codedetails:
// JPanel-class contains:
int i = 0;
public void callRepaint(){
repaint();
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawLine(i++,0,200,200);
public void keyPressed(KeyEvent e) {
repaint(); // This is working
//GUI-class contains:
// This method is called cyclically
public void draw() {
lnkJPanelclass.repaint(); // This calling didn't work
// lnkJPanelclass.callRepaint(); // This calling didn't work
Thanks for your advices in advance!
Cheers spike@ARafique:
This works fine:
import java.awt.*;
import java.awt.event.*;
import java.util.Date;
import javax.swing.*;
public class Test extends JFrame implements ActionListener{
private JTextField label;
private Timer timer;
private Container cont;
public Test() {
label = new JTextField("",0);
timer = new Timer(1000,this);
cont = getContentPane();
cont.add(label);
setSize(250,70);
setDefaultCloseOperation(3);
setVisible(true);
timer.start();
public void actionPerformed(ActionEvent e){
label.setText(new Date(System.currentTimeMillis()).toString());
public static void main(String[] args){
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Test();
}no repaint()/revalidate() needed -
Selection problem in rendered JtextArea.
I create a jtable by rendering one column using jTextarea. While selecting the row, color of selection not geting to the rendered Jtextarea. How can i solve this problem.
please help meDo you include code in your getTableCellRendererComponent method to change
the color depending on if the row is selected or not? You'll need something like
if ( isSelected ) {
setForeground( table.getSelectionForeground() );
setBackground( table.getSelectionBackground() );
} else {
setForeground( table.getForeground() );
setBackground( table.getBackground() );
}: jay -
Problem to "repaint" the 3D screen
Hi everyone, I wrote an application that moves some geometrical objects when the user click on them, using Picking. The situation was supposed to happens like this: after the user clicks on an object i translate it to a distant position in order to hide it, so the place where the objects were stays empty, then i wait for some seconds and other configurations (i mean other positions) of the objects appear.
The problem is that the place does not stays empty it keep the old frame (i mean the old positions configuration) during all time i wait and just after that the frame show the new configuration. I guess it something related to Thread.sleep() the method i use to wait some seconds.
So my question is: Is there other strategy to do this such thing i intend? Maybe something like �Repaint�. Since now thanks a lot. I hope to have made myself to understand due my poor English writing.
�der.messengers, i'm writing the Behavior class but i got a doubt, how can i get the action that wakeup the Thread.sleep in order to pass to wakeuponBehaviorPost class?
The code i found is like this:
public class MyBehaviorTranslation extends Behavior{
MyBehaviorTranslation(Group root, Bounds bounds) {
this.setSchedulingBounds(bounds);
BranchGroup branchGroup = new BranchGroup();
branchGroup.addChild(this);
root.addChild(branchGroup);
public void initialize(){
// set initial wakeup condition
this.wakeupOn(new WakeupOnBehaviorPost(???, 0));
// set someIntegerValue to your specific value
// null can be replaced by an specific Behavior Object to send this value
// called by Java 3D when appropriate stimulus occures
public void processStimulus(Enumeration criteria){
// do what is necessary
// resetup Behavior
this.wakeupOn(new WakeupOnBehaviorPost(????, 0));
}Thanks a lot since now.
�der. -
I'm using the swing packege 1.1 and having some problem when trying to limit the number of character per line in a JTextArea component.
I want the JTextArea to change line when a certain number of character are typed in one of these lines.
Any idea?
thank you all.Do you mean you want to set the number of characters per line for example to 20 so all the lines in the JTextArea will hold only 20 characters? If so, this code shows a way to do it. If you use a fixed-width font, as in the example, all lines will hold the same number of characters. If you use a variable-width font, you could have lines with slightly more or slightly fewer characters, depending on what the user enters. The frame must not be resized.
int chars_per_line=20;
JFrame jf=new JFrame();
JTextArea jta=new JTextArea(24,chars_per_line);
jta.setFont(new Font("Courier",Font.PLAIN,14));
jta.setLineWrap(true);
jf.getContentPane().add(jta);
jf.pack();
jf.setResizable(false);
jf.setVisible(true); -
Problem with JMENU / JTEXTAREA
Hello All,
I have the following problem:
I want to create a little text editor. I just have a window containing
a menu bar and a text area. The basic functions work fine. I can open a
file and read it into the text area.
The problem I have is, that my menu is affected by the file chooser window. When I close the file chooser parts of the selected file or the
file chooser will be painted in my menu. In the worst case it deletes menu items.
Does anybody knows help?
Thank you in advance.
RalfIt sounds like your program is busy doing something else after the filechooser closes, which is causing your GUI not to repaint. I assume you are performing some io on the file after the user click the OK button, that is probably whats causing it to not redisplay your menus. Or you could be getting an exception opening your file which usually causes the GUI to hang. If you not getting an exception and your sure your io code isn't infinite looping, then your best option to fix this is to run the io code in a separate thread.
-
Select problem in the JTextArea
Hi
I have a problem on the select(), I am trying to select multiple lines of text in the JTextArea, but select(int start, int end) can only select single line, int end will be cut to the length of the line instead of going to the next line. Can anyone give me any advice?
Thanks in advanceDefaultHighlighter highlighter = (DefaultHighlighter)textArea.getHighlighter();
highlighter.setDrawsLayeredHighlights(false); -
I'm trying to write a class with a button which, when clicked, will alternate between two panels.
My problem is the entire "details" message will not display.
I've tried various combinations of layout managers with calls to setSize() and setRows(), or using a JTextPane instead.
My brain feels like a bowl of spaghetti because I'm not getting anywhere.
What am I missing?
Thanx to one and all.import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class ToggleButton extends JFrame implements ActionListener
private JButton button;
private JPanel panel , detailPanel;
private Container contentPane = getContentPane();
public ToggleButton()
setLayout(new GridLayout(2,1));
setBounds(400 , 250 , 200 , 100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
button = new JButton("Show Details");
button.addActionListener(this);
panel = new JPanel();
panel.add(button);
JTextArea details = new JTextArea();
TitledBorder border = BorderFactory.createTitledBorder("Details");
details.setBorder(border);
details.setLineWrap(true);
String text = "Now is the time for all good women to come to the aid of their men.";
details.setText(text);
detailPanel = new JPanel();
detailPanel.add(details);
contentPane.add(panel);
setVisible(true);
public void actionPerformed(ActionEvent ae)
if (ae.getActionCommand().equals("Show Details"))
button.setText("Hide Details");
setBounds(400 , 250 , 200 , 200);
contentPane.add(detailPanel);
else
button.setText("Show Details");
contentPane.remove(detailPanel);
setBounds(400 , 250 , 200 , 100);
public static void main(String[] args)
new ToggleButton();
}public void actionPerformed(ActionEvent ae)
if (ae.getActionCommand().equals("Show Details"))
button.setText("Hide Details");
setBounds(400 , 250 , 200 , 200);
contentPane.add(detailPanel);
else
button.setText("Show Details");
contentPane.remove(detailPanel);
setBounds(400 , 250 , 200 , 100);
validate();
}The Grid layout will cause problems, but I am sure you can figure that out.
FYI: It might be better practice to toggle the details panel's visibility rather than adding and removing it. Just a thought. -
Problems with disappearing JTextArea when activating JMenu
Im having trouble with using JTextArea in conjunction with JMenu and JInternalFrame. I have a program that uses JInternalFrames for navigation, when the navigation been used I set the JInternalFrame to setVisible(false) and display a JMenuBar with several components and a JTextArea. The JTextArea gets displayed as it should and so is the JMenuBar but when a JMenuItem has been activated the JTextArea becomes invisible or partly invisible. Anyone have any suggestions?
//Function that removes the JInternalFrame and adds the JMenuBar and JTextArea to the program
public void ordBehandlare()
ramnav.setVisible(false); //ramnav == JInternalFrame
Container cont = getContentPane();
cont.add(ordbehandlarArea); //ordbehandlarArea == JTextArea
setJMenuBar(ordBehandBar); //ordBehandBar == JMenuBar
Grateful for any answers...From the 5 lines of code you posted I have no idea whats wrong, but I'm sure you can create a 20 line program that we can compile and execute that demonstrates your problem. Chances are while your creating this simple program you will find your error.
-
Hi,
I have a JFrame, which contains a JPanel (named activePanel). I also added a method to change the active JPanel. It goes like this:
public class MyFrame extends JFrame {
private JPanel activePanel;
public void setActivePanel(JPanel otherPanel) {
activePanel.setVisible(false);
activePanel = otherPanel;
activePanel.revalidate();
activePanel.setVisible(true);
this.getContentPane().validate();
this.getContentPane().repaint();
System.out.println("finished!"); // for debugging only
The problem is that when this method is called, the current activePanel becomes invisible, the 'finished'-string is printed, but the otherPanel is still not showing...
What is going wrong? What can I do?
TIAHello!
I think you would like to replace the active panel
with another panel.
There are two methods to do this:
1.
Remove the panel from the frame and then add the new
panel to the frame
2.
Use CardLayout manager instead. It is very fine!
This layout manager lays out components like cards in deck.
Only one 'card' can be shown at a time (int this situation the activePanel).
You can use the show(Container c, String name) method
to switch between panels.
I have used this layout manager in my project and it works
fine.
Hope it helps you
regards
Feri -
Problem using repaint() method from another class
I am trying to make tower of hanoi...but unable to transfer rings from a tower to another...i had made three classes....layout21 where all componentents of frame assembled and provided suitable actionlistener.....second is mainPanel which is used to draw the rods n rings in paintComponent.....and third is tower in which code for hanoi is available...i had made an object of mainPanel at layoout21 n tower but i m not able to call repaint from tower..gives an error : cannot find the symbol....method repaint in tower.
code fragments od three classes are:
LAYOUT21
class layout21 extends JFrame implements ActionListener
{ private Vector rod1 = new Vector();
private Vector rod2 = new Vector();
private Vector rod3 = new Vector();
private String elem; //comment
public String r22;
public boolean in=false;
public int count=0; //no of times the transfer to other rods performed
private int r3,rings; // current no of rings
private JComboBox nor,col;
private JLabel no;
private JLabel moved;
private JLabel no1;
private JButton start;
private JButton ref;
private AboutDialog dialog;
private JMenuItem aboutItem;
private JMenuItem exitItem;
private tower t;
final mainPanel2 p =new mainPanel2();
public layout21()
{ t = new tower();
Toolkit kit =Toolkit.getDefaultToolkit();
Image img = kit.getImage("java.gif");
setIconImage(img);
setTitle("Tower Of Hanoi");
setSize(615,615);
setResizable(false);
setBackground(Color.CYAN);
JMenuBar mbar = new JMenuBar();
setJMenuBar(mbar);
JMenu fileMenu = new JMenu("File");
mbar.add(fileMenu);
aboutItem = new JMenuItem("About");
aboutItem.addActionListener(this);
fileMenu.add(aboutItem);
exitItem = new JMenuItem("Exit");
exitItem.addActionListener(this);
fileMenu.add(exitItem);
Container contentPane =getContentPane();
JPanel bspanel = new JPanel();
JPanel bnpanel = new JPanel();
setBackground(Color.CYAN);
//JComboBox
nor = new JComboBox();
nor.setEditable(false);
nor.addItem("3");
nor.addItem("4");
nor.addItem("5");
nor.addItem("6");
nor.addItem("7");
nor.addItem("8");
nor.addItem("9");
bspanel.add(nor);
col = new JComboBox();
col.setEditable(false);
col.addItem("BLACK");
col.addItem("GREEN");
col.addItem("CYAN");
bspanel.add(col);
JLabel tl = new JLabel("Time");
tl.setFont(new Font("Serif",Font.BOLD,12));
bspanel.add(tl);
JTextField tlag = new JTextField("0",4);
bspanel.add(tlag);
start =new JButton("Start");
bspanel.add(start);
ref =new JButton("Refresh");
bspanel.add(ref);
JButton end =new JButton("End");
bspanel.add(end);
start.addActionListener(this);
nor.addActionListener(this);
col.addActionListener(this);
ref.addActionListener(this);
end.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose(); // Closes the dialog
contentPane.add(bspanel,BorderLayout.SOUTH);
JLabel count = new JLabel("No of Transfer reguired:");
count.setFont(new Font("Serif",Font.BOLD,16));
bnpanel.add(count);
no = new JLabel("7");
no.setFont(new Font("Serif",Font.BOLD,16));
bnpanel.add(no);
JLabel moved = new JLabel("Moved:");
moved.setFont(new Font("Serif",Font.BOLD,16));
bnpanel.add(moved);
no1 = new JLabel("0");
no1.setFont(new Font("Serif",Font.BOLD,16));
bnpanel.add(no1);
contentPane.add(bnpanel,BorderLayout.NORTH);
contentPane.add(p,BorderLayout.CENTER);
String r = (String)nor.getSelectedItem();
rings = Integer.valueOf(r).intValue();
p.draw(rings,1) ;
public void actionPerformed(ActionEvent evt)
{ Object source = evt.getSource();
if(source == start)
r3 = Integer.valueOf((String)nor.getSelectedItem()).intValue();
p.transfer(false);
t.initialise(rod1,rod2,rod3,0);
t.towerOfHanoi(r3);
//repaint();
if(source == ref)
{ rod1.removeAllElements() ;
rod2.removeAllElements() ;
rod3.removeAllElements() ;
count=0;
r3 = Integer.valueOf((String)nor.getSelectedItem()).intValue();
p.draw(r3,1);
p.transfer(true);
no1.setText(""+0);
p.trans_vec(rod1,rod2,rod3);
t.initialise(rod1,rod2,rod3,0);
System.out.println("");
repaint();
if(source == nor)
{ JComboBox j = (JComboBox)source;
String item = (String)j.getSelectedItem();
int ring1 = Integer.valueOf(item).intValue();
int a=1;
for(int i=1;i<=ring1;i++)
{ a = a*2;
a=a-1;
no.setText(""+a);
p.draw(ring1,1);
repaint();
if(source == aboutItem)
{ if (dialog == null) // first time
dialog = new AboutDialog(this);
dialog.setVisible(true);
if(source == exitItem)
{ System.exit(0);
if (source==col)
{ JComboBox j = (JComboBox)source;
String item = (String)j.getSelectedItem();
repaint();
TOWER
class tower extends Thread
{ private Vector rod1 = new Vector();
private Vector rod2 = new Vector();
private Vector rod3 = new Vector();
private int count ;
private String elem;
final mainPanel2 z =new mainPanel2();
public void initialise(Vector r1,Vector r2,Vector r3,int c)
{ rod1 = r1;
rod2 = r2;
rod3 = r3;
count =c;
public void towerOfHanoi(int rings)
for(int i=0;i<rings;i++)
rod1.add(" "+(i+1));
System.out.println("rod1:"+rod1.toString());
hanoi(rings,1,2);
public void hanoi(int m,int i, int j)
if(m>0)
{ hanoi(m-1,i,6-i-j);
if(i==1 && j==2 && rod1.isEmpty()==false)
{ count++;
//no1.setText(""+count);
elem = (String)rod1.remove(0);
rod2.add(0,elem);
//z.trans_vec(rod1,rod2,rod3);
repaint(); //NOT ABLE TO USE METHOD HERE...WHY??
//z.hanoi_paint();
try
this.sleep(2000);
catch (Exception e) { e.printStackTrace() ; }
System.out.println(count+". ROD 2:"+rod2.toString());
if(i==1 && j==3 && rod1.isEmpty()==false)
{ count++;
//no1.setText(""+count);
elem = (String)rod1.remove(0);
rod3.add(0,elem);
//z.trans_vec(rod1,rod2,rod3);
repaint();//
// z.hanoi_paint();
try
this.sleep(2000);
catch (Exception e) { e.printStackTrace() ; }
System.out.println(count+". ROD 3:"+rod3.toString());
if(i==2 && j==1 && rod2.isEmpty()==false)
{ count++;
//no1.setText(""+count);
elem = (String)rod2.remove(0);
rod1.add(0,elem);
//z.trans_vec(rod1,rod2,rod3);
repaint();
//z.hanoi_paint();
try
this.sleep(2000);
catch (Exception e) { e.printStackTrace() ; }
System.out.println(count+". ROD 1:"+rod1.toString());
if(i==2 && j==3 && rod2.isEmpty()==false)
{ count++;
//no1.setText(""+count);
elem = (String)rod2.remove(0);
rod3.add(0,elem);
//z.trans_vec(rod1,rod2,rod3);
repaint();
//z.hanoi_paint();
try
this.sleep(2000);
catch (Exception e) { e.printStackTrace() ; }
System.out.println(count+". ROD 3:"+rod3.toString());
if(i==3 && j==1 && rod3.isEmpty()==false)
{ count++;
//no1.setText(""+count);
elem = (String)rod3.remove(0);
rod1.add(0,elem);
//z.trans_vec(rod1,rod2,rod3);
repaint();
//z.hanoi_paint();
try
this.sleep(2000);
catch (Exception e) { e.printStackTrace() ; }
System.out.println(count+". ROD 1:"+rod1.toString());
if(i==3 && j==2 && rod3.isEmpty()==false)
{ count++;
//no1.setText(""+count);
elem = (String)rod3.remove(0);
rod2.add(0,elem);
//z.trans_vec(rod1,rod2,rod3);
repaint();
//z.hanoi_paint();
try
this.sleep(2000);
catch (Exception e) { e.printStackTrace() ; }
System.out.println(count+". ROD 2:"+rod2.toString());
hanoi(m-1,6-i-j,j);
MAINPANEL
class mainPanel2 extends JPanel //throws IOException
public Vector line = new Vector();
public Vector rod11= new Vector();
public Vector rod22= new Vector();
public Vector rod33= new Vector();
public int no_ring;
public int rod_no;
String pixel;
StringTokenizer st,st1;
int x,y;
public boolean initial =true;
public void paintComponent(Graphics g)
{ System.out.println("repaint test");
bresenham(100,60,100,360);
bresenham(101,60,101,360);
bresenham(102,60,102,360);
bresenham(103,60,103,360);
bresenham(104,60,104,360);
g.setColor(Color.BLUE);
while(line.size()>0)
{ pixel = (String)line.remove(0);
st = new StringTokenizer(pixel);
x = Integer.valueOf(st.nextToken()).intValue();
y = Integer.valueOf(st.nextToken()).intValue();
g.drawLine(x,y,x,y);
bresenham(300,60,300,360);
bresenham(301,60,301,360);
bresenham(302,60,302,360);
bresenham(303,60,303,360);
bresenham(304,60,304,360);
while(line.size()>0)
{ pixel = (String)line.remove(0);
st = new StringTokenizer(pixel);
x = Integer.valueOf(st.nextToken()).intValue();
y = Integer.valueOf(st.nextToken()).intValue();
g.drawLine(x,y,x,y);
bresenham(500,60,500,360);
bresenham(501,60,501,360);
bresenham(502,60,502,360);
bresenham(503,60,503,360);
bresenham(504,60,504,360);
while(line.size()>0)
{ pixel = (String)line.remove(0);
st = new StringTokenizer(pixel);
x = Integer.valueOf(st.nextToken()).intValue();
y = Integer.valueOf(st.nextToken()).intValue();
g.drawLine(x,y,x,y);
bresenham(0,361,615,361);//used to get a pixel according to algo.. . func not provided
bresenham(0,362,615,362);
bresenham(0,363,615,363);
bresenham(0,364,615,364);
bresenham(0,365,615,365);
while(line.size()>0)
{ pixel = (String)line.remove(0);
st = new StringTokenizer(pixel);
x = Integer.valueOf(st.nextToken()).intValue();
y = Integer.valueOf(st.nextToken()).intValue();
g.drawLine(x,y,x,y);
if(initial==true)
g.setColor(Color.RED);
for(int i = no_ring;i>0;i--)
{ g.drawLine(100-(i*8),360-(no_ring - i)*10,100+(i*8)+5,360-(no_ring - i)*10);
g.drawLine(100-(i*8),359-(no_ring - i)*10,100+(i*8)+5,359-(no_ring - i)*10);
g.drawLine(100-(i*8),358-(no_ring - i)*10,100+(i*8)+5,358-(no_ring - i)*10);
g.drawLine(100-(i*8),357-(no_ring - i)*10,100+(i*8)+5,357-(no_ring - i)*10);
g.drawLine(100-(i*8),356-(no_ring - i)*10,100+(i*8)+5,356-(no_ring - i)*10);
// draw for each rod
//System.out.println("rod11:"+rod11);
//System.out.println("rod22:"+rod22);
//System.out.println("rod33:"+rod33);
int r1 = rod11.size();
int r2 = rod22.size();
int r3 = rod33.size();
String rd1,rd2,rd3;
int r11,r12,r21,r22,r31,r32;
if(initial == false)
{ g.setColor(Color.RED);
while(rod11.size()>0)
{ r12 = rod11.size()-1;
rd1 = (String)rod11.remove(r12);
r11 = Integer.valueOf(rd1).intValue();
g.drawLine(100-((r11+1)*8),360-(r1 - (r11+1))*10,100+((r11+1)*8)+5,360-(r1 - (r11+1))*10);
g.drawLine(100-((r11+1)*8),359-(r1 - (r11+1))*10,100+((r11+1)*8)+5,359-(r1 - (r11+1))*10);
g.drawLine(100-((r11+1)*8),358-(r1 - (r11+1))*10,100+((r11+1)*8)+5,358-(r1 - (r11+1))*10);
g.drawLine(100-((r11+1)*8),357-(r1 - (r11+1))*10,100+((r11+1)*8)+5,357-(r1 - (r11+1))*10);
g.drawLine(100-((r11+1)*8),356-(r1 - (r11+1))*10,100+((r11+1)*8)+5,356-(r1 - (r11+1))*10);
while(rod22.size()>0)
{ g.setColor(Color.RED);
r22 = rod22.size()-1;
System.out.println("TEST *************************:"+r22);
try
// e.printStackTrace();
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr) ;
br.readLine() ;
}catch(Exception f) {}
rd2 = ((String)rod22.remove(r22)).trim();
r21 = Integer.valueOf(rd2).intValue();
g.drawLine(300-((r22+1)*8),360-(r2 - (r22+1))*10,300+((r22+1)*8)+5,360-(r2 - (r22+1))*10);
g.drawLine(300-((r22+1)*8),359-(r2 - (r22+1))*10,300+((r22+1)*8)+5,359-(r2 - (r22+1))*10);
g.drawLine(300-((r22+1)*8),358-(r2 - (r22+1))*10,300+((r22+1)*8)+5,358-(r2 - (r22+1))*10);
g.drawLine(300-((r22+1)*8),357-(r2 - (r22+1))*10,300+((r22+1)*8)+5,357-(r2 - (r22+1))*10);
g.drawLine(300-((r22+1)*8),356-(r2 - (r22+1))*10,300+((r22+1)*8)+5,356-(r2 - (r22+1))*10);
while(rod33.size()>0)
{ g.setColor(Color.RED);
r32 = rod33.size()-1;
rd3 = (String)rod33.remove(r32);
r31 = Integer.valueOf(rd3).intValue();
g.drawLine(500-((r32+1)*8),360-(r3 - (r32+1))*10,500+((r32+1)*8)+5,360-(r3 - (r32+1))*10);
g.drawLine(500-((r32+1)*8),359-(r3 - (r32+1))*10,500+((r32+1)*8)+5,359-(r3 - (r32+1))*10);
g.drawLine(500-((r32+1)*8),358-(r3 - (r32+1))*10,500+((r32+1)*8)+5,358-(r3 - (r32+1))*10);
g.drawLine(500-((r32+1)*8),357-(r3 - (r32+1))*10,500+((r32+1)*8)+5,357-(r3 - (r32+1))*10);
g.drawLine(500-((r32+1)*8),356-(r3 - (r32+1))*10,500+((r32+1)*8)+5,356-(r3 - (r32+1))*10);
why i m not able to use repaint() method in tower class? from where i can use repaint() methodi can't read your code - not formatted with code tags
I have no chance of getting it to compile (AboutDialog class?? p.draw() ??)
here's a basic routine - add a couple of things to this to demonstrate what is not
being redrawn
(compare the readability of below code (using tags) to yours)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Testing extends JFrame
public Testing()
setSize(400,300);
setLocation(400,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
final DrawPanel dp = new DrawPanel();
JButton btn = new JButton("Change Text Location/Repaint");
getContentPane().add(dp,BorderLayout.CENTER);
getContentPane().add(btn,BorderLayout.SOUTH);
btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
dp.x = (int)(Math.random()*300);
dp.y = (int)(Math.random()*150)+50;
repaint();}});
public static void main(String[] args){new Testing().setVisible(true);}
class DrawPanel extends JPanel
int x = 50, y = 50;
public void paintComponent(Graphics g)
super.paintComponent(g);
g.drawString("Hello World",x,y);
} -
Problems with repainting in new JD 9.0.4.0
I just installed new JD 9.0.4.0 . I think that from this moment I have problems with painting java graphics objects (for example Application Module tests or simple login dialogs). When I move that window, its remains are left on the screen until I overlap them with other non-java window. Has anybody the same experience ?
I haven't seen this. One thought (call it grasping at straws) would be to set the environment variable: J2D_D3D=false
That disables Java2D and sometimes fixes some quirks.
Rob
Team JDev -
I drawn some rectangles.If one rectangle was clicked,the rectangles below it should move down..but for me,its not repainting.the old location as well as the new location was there when i click the rectangle...
import javax.swing.JApplet;
* To change this template, choose Tools | Templates
* and open the template in the editor.
import java.awt.event.MouseEvent;
import javax.swing.*;
import java.awt.*;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Rectangle;
import java.awt.event.MouseListener;
import java.util.ArrayList;
* @author 8563
public class TestTree extends JApplet
@Override
public void init()
Container con = getContentPane();
con.setLayout(new BorderLayout());
setPreferredSize(new Dimension(300, 300));
JScrollPane scroll = new JScrollPane();
getContentPane().add(scroll, BorderLayout.CENTER);
scroll.setViewportView(new ImagePanel());
private class ImagePanel extends JPanel implements MouseListener {
ImagePanel image;
Rectangle rext = new Rectangle(40, 40, 30, 15);
int[] x = {75, 95, 115, 130};
int[] width = {15, 15, 15, 15};
boolean selected1 = false;
int count;
Rectangle [] rects;
Rectangle [] rectangles;
ArrayList<Rectangle> hlp;
public ImagePanel()
prepareData();
this.addMouseListener(this);
@Override
protected void paintComponent(Graphics g)
Graphics2D g2 = (Graphics2D) g;
g2.draw(rext);
drawRect(g2);
public void prepareData()
int x = 75;
int y = 85;
int w = 20;
int h = 15;
hlp = new ArrayList<Rectangle>();
for (int i = 0; i < 4; i++) {
hlp.add(new Rectangle(x, y, w, h));
y += 25;
rectangles = hlp.toArray(new Rectangle[hlp.size()]);
public void drawRect(Graphics g)
Graphics2D g2 = (Graphics2D) g;
for (Rectangle r : rectangles)
g2.draw(r);
//repaint();
public void mouseClicked(MouseEvent e)
Point mse_clk = e.getPoint();
int count_incr = count+1;
int y = 150;
for(int i=count_incr;i<rectangles.length;i++)
if(selected1)
rectangles.setLocation(rectangles[i].x,rectangles[i].y+20);
// repaint();
repaint();
public void mousePressed(MouseEvent e)
Point pres_point = e.getPoint();
for (int i=0;i<rectangles.length;i++)
if(rectangles[i].contains(pres_point))
selected1 = true;
count = i;
break;
public void mouseReleased(MouseEvent e)
public void mouseEntered(MouseEvent e)
public void mouseExited(MouseEvent e)
public static void main(String[] args) {
JApplet applet = new TestTree();
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(applet);
f.setSize(400, 400);
f.setLocationRelativeTo(null);
applet.init();
f.setVisible(true);@Override
protected void paintComponent(Graphics g)
// paint the background..
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.draw(rext);
drawRect(g2);
}
Maybe you are looking for
-
Startup disaster, Root/user password change, Please help!!
Hi, my ibook g4 was purchased on ebay through a seller with 100% feedback (a school district). It came with Tiger already installed, and I bought the Leopard Retail upgrade disc, installed all that, and did software updates to get it up and running a
-
Devices does not show up in left-hand column
Ipod nano is connected to USB port and has fully charged. "Devices" doesn't show up in left-hand column. Library, Store, Genius, and Playlists are listed. Looked on public forums, but no viable solution displayed. I welcome suggestions. Nano was
-
Need to delete specific Months Data from SQL Server Table
Greetings Everyone, So i have one table which contains 5 years old data, now business wants to keep just one year old data and data from qurter months i.e. (jan, mar, June, sep and December), i need to do this in stored procedure. how i can achive th
-
Webdynpro application deployment failed.
Our development team working on NWDS to develop some webdynpro application, but they are unable to deploy the application on one of portal. Error Logs Jul 29, 2011 8:46:28 AM Info: The SDM client uses an old SDM client API. Jul 29, 2011 8:46:28 AM
-
SLM2048 - Password problems with special chars
Hi all, We´ve got a SLM2048 in use (most current FW) and I wanted to apply our new password standards onto that switch. So I changed the password of the user admin and used special chars, which were =&!= and clicked update and save changes. I now