Search Results

Search found 491 results on 20 pages for 'jframe'.

Page 8/20 | < Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >

  • How to delete Drawn Line in java?

    - by Jeyjey
    Hello Folks, well this is my code: import javax.swing.; import javax.; import java.awt.; import java.awt.Color; import java.awt.Graphics.; import java.awt.event.*; import javax.swing.UIManager; public class SimpleGUI extends JFrame{ public SimpleGUI(){ this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ; } public void go(){ Drawpanel = new Mypanel(); JFrame frame = new JFrame("Chasing Line"); frame.getContentPane().add(BorderLayout.CENTER, Drawpanel); frame.setSize(300,300); frame.setVisible(true); Drawpanel.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() { public void mouseMoved(java.awt.event.MouseEvent evt) { DrawpanelMouseMoved(evt); } }); } public void DrawpanelMouseMoved(java.awt.event.MouseEvent evt) { xpos=evt.getX(); ypos=evt.getY(); System.out.println("Coordinates : X :"+ xpos+"Y: "+ypos); Drawpanel.paintImage(xpos,ypos); } class Mypanel extends JPanel{ public void paintImage(int xpost,int ypost){ Graphics d = getGraphics(); d.setColor(Color.black); d.drawLine(xpost, 0, xpost, this.getHeight()); d.setColor(Color.red); d.drawLine(0, ypost, this.getWidth(),ypost); this.validate(); } } // end the inner class public static void main(String[] args){ try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } catch(Exception e) { System.err.println("Look and feel not set"); } SimpleGUI win = new SimpleGUI(); win.go(); } Mypanel Drawpanel; private int xpos=0; private int ypos=0; } // close SimpleGUI class The problem is how can i delete the old lines?, i mea,make only the current x and y lines appear on the screen, make the intersection between both lines "follow" the mouse pointer. thanks for any reply.

    Read the article

  • Using addMouseListener() and paintComponent() for JPanel

    - by Alex
    This is a follow-up to my previous question. I've simplified things as much as I could, and it still doesn't work! Although the good thing I got around using getGraphics(). A detailed explanation on what goes wrong here is massively appreciated. My suspicion is that something's wrong with the the way I used addMouseListener() method here. import java.awt.Color; import java.awt.Graphics; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JFrame; import javax.swing.JPanel; public class MainClass1{ private static PaintClass22 inst2 = new PaintClass22(); public static void main(String args[]){ JFrame frame1 = new JFrame(); frame1.add(inst2); frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame1.setTitle("NewPaintToolbox"); frame1.setSize(200, 200); frame1.setLocationRelativeTo(null); frame1.setVisible(true); } } class PaintClass11 extends MouseAdapter{ int xvar; int yvar; static PaintClass22 inst1 = new PaintClass22(); public PaintClass11(){ inst1.addMouseListener(this); inst1.addMouseMotionListener(this); } @Override public void mouseClicked(MouseEvent arg0) { // TODO Auto-generated method stub xvar = arg0.getX(); yvar = arg0.getY(); inst1.return_paint(xvar, yvar); } } class PaintClass22 extends JPanel{ private static int varx; private static int vary; public void return_paint(int input1, int input2){ varx = input1; vary = input2; repaint(varx,vary,10,10); } public void paintComponent(Graphics g){ super.paintComponents(g); g.setColor(Color.RED); g.fillRect(varx, vary, 10, 10); } }

    Read the article

  • Error Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException [migrated]

    - by user134212
    I'm new here. I'm learning how to program on java and I have a problem with my code. I really have no clue why my code is not working. I think my mistake may be here, but I'm not quite sure. m3 = new Matriz(ren2,col2); btSumar.addActionListener(new ActionListener() { Matriz m3;//(ren2,col2); public void actionPerformed(ActionEvent e) { m3 = new Matriz(ren2,col2); if(ventanaAbierta==true) { try { crearMat.SUMA(m1,m2); } catch(Exception nul) { System.out.println(nul); } } else { JOptionPane.showMessageDialog(null,"Ya se realizo la suma"); } } }); My Complete code import java.awt.*; import javax.swing.*; import javax.swing.BorderFactory; import javax.swing.border.Border; import java.awt.event.*; import java.awt.*; import java.io.*; import java.util.*; public class Practica2 { private int opcion,ren2,col2; private JFrame ventana,ventanaPrintMatriz; private JPanel panel,panel2; private Border borderRed2,borderBlue2,borderGreen2,borderGreen4; private Color red,green,blue,white,black; private Font Verdana14,ArialBlack18; private JLabel labelTitulo; public JButton btSalir,btSumar,btRestar,btMultiplica,btTranspuesta,btCrear; private ImageIcon suma,resta,multi,crear,salir,trans; private boolean ventanaAbierta = false; private static ValidacionesMatrices valida; private static Operaciones operacion; private static Matriz m1,m2,m3; private static ImprimirMatriz printMat; public Practica2() { panel = new JPanel(); panel.setLayout(null); ventana = new JFrame("Operaciones con Matrices"); ventana.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); ventana.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { //Sale del programa System.exit(0); } }); ventana.setContentPane(panel); ventana.setVisible(true); ventana.setResizable(false); ventana.setBounds(150,150,300,380); //ventana.setBounds(0,0,650,650); } public void inicializarComponentes() { panel2 = new JPanel(); panel2.setLayout(null); labelTitulo = new JLabel("Practica #2"); suma = new ImageIcon("suma1.png"); resta = new ImageIcon("resta1.png"); multi = new ImageIcon("multi1.png"); trans = new ImageIcon("trans2.png"); crear = new ImageIcon("crear1.png"); salir = new ImageIcon("salir1.png"); btTranspuesta = new JButton("Transpuesta",trans); btMultiplica = new JButton("Multiplica",multi); btRestar = new JButton("Restar",resta); btSumar = new JButton("Sumar",suma); btCrear = new JButton("Crear",crear); btSalir = new JButton("Salir",salir); //Tipo de letra ArialBlack18 = new Font("Arial Black",Font.BOLD,18); //Color green = new Color(0,255,0); //Formato labelTitulo labelTitulo.setBounds(80,-60,200,150); labelTitulo.setFont(ArialBlack18); labelTitulo.setForeground(blue); labelTitulo.setVisible(true); //Formato de CrearMatriz btCrear.setBounds(80,50,130,30); btCrear.setToolTipText("Crea una matriz"); //Formato de Muliplica btMultiplica.setBounds(80,100,130,30); btMultiplica.setToolTipText("Mat[A] * Mat[B]"); //Formato de botonRestar btRestar.setBounds(80,150,130,30); btRestar.setToolTipText("Mat[A] - Mat[B]"); //Formato del botonSumar btSumar.setBounds(80,200,130,30); btSumar.setToolTipText("Mat[A] + Mat[B]"); //Formato de Transpuesta btTranspuesta.setBounds(80,250,130,30); btTranspuesta.setToolTipText("Mat[A]^-1"); //Formato del botonSalir btSalir.setBounds(80,300,130,30); //Agregando componentes al panel1 panel2.add(labelTitulo); panel2.add(btMultiplica); panel2.add(btCrear); panel2.add(btRestar); panel2.add(btSumar); panel2.add(btSalir); panel2.add(btTranspuesta); //Formato panel2 panel2.setBackground(green); panel2.setVisible(true); panel2.setBounds(0,0,300,380); //Argregamos componentes al panelPrincipal= panel.add(panel2); //BotonCrear btCrear.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) //throws IOException { if(ventanaAbierta==false) { ventanaAbierta=true; new CrearMatriz(); } else { JOptionPane.showMessageDialog(null,"Ya se crearon las Matrices"); } } }); m3 = new Matriz(ren2,col2); btSumar.addActionListener(new ActionListener() { Matriz m3;//(ren2,col2); public void actionPerformed(ActionEvent e) { m3 = new Matriz(ren2,col2); if(ventanaAbierta==true) { try { crearMat.SUMA(m1,m2); } catch(Exception nul) { System.out.println(nul); } } else { JOptionPane.showMessageDialog(null,"Ya se realizo la suma"); } } }); //BotonSalir btSalir.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); panel.setVisible(true); panel.setBounds(0,0,350,380); } class VentanaMatriz { private JFrame ventana; private JPanel panel; private JTextArea textArea1,textArea2; private JLabel mat1,mat2; private JTextField textField1; public VentanaMatriz() { panel = new JPanel(); panel.setLayout(null); ventana = new JFrame("Creacion de Matrices"); ventana.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { ventana.dispose(); } }); ventana.setContentPane(panel); ventana.setVisible(true); ventana.setResizable(false); ventana.setBounds(200,100,850,420); } public void inicializarComponentes() { //Colores black = new Color(0,0,0); white = new Color(255,255,255); blue = new Color(0,0,255); green = new Color(0,255,0); red = new Color(255,0,0); //Tipo de letra Verdana14 = new Font("Verdana",Font.BOLD,14); //Tipos de borde borderRed2 = BorderFactory.createLineBorder(red,2); borderBlue2 = BorderFactory.createLineBorder(blue,2); borderGreen2 = BorderFactory.createLineBorder(green,2); borderGreen4 = BorderFactory.createLineBorder(green,4); //Agregando componentes al panel1 panel.add(mat1); panel.add(textArea1); panel.add(mat2); panel.add(textArea2); //Formato panel2 panel.setBackground(blue); panel.setVisible(true); panel.setBounds(0,0,850,420); } } class CrearMatriz { public int col1,re1,ren2,col2; public Matriz m1,m2,m3; public CrearMatriz() { int col1,ren1,ren2,col2; ren2 = Integer.parseInt(JOptionPane.showInputDialog("Numero de Renglones Matriz A: ")); col2 = Integer.parseInt(JOptionPane.showInputDialog("Numero de Columnas Matriz A: ")); final Matriz m1= new Matriz(ren2,col2); ren2 = Integer.parseInt(JOptionPane.showInputDialog("Numero de Renglones Matriz B: ")); col2 = Integer.parseInt(JOptionPane.showInputDialog("Numero de Columnas Matriz B: ")); final Matriz m2= new Matriz(ren2,col2); m3 = new Matriz(ren2,col2); m1.llenarMatriz(); m2.llenarMatriz(); m1.printMat(); m2.printMat(); } public void SUMA(Matriz m1,Matriz m2) { Matriz m3; if(ventanaAbierta==false) { m3 = new Matriz(ren2,col2); if(valida.validaSumayResta(m1,m2)) { m3 = operacion.sumaMat(m1,m2); JOptionPane.showMessageDialog(null,"La suma es = "); m3.imprimeMatriz(); } else { JOptionPane.showMessageDialog(null,"No es posible hacer la suma"); } } } public void RESTA() { } //btSumar = new JButton("Sumar",suma); //BotonSumar //Mostrar matriz 1 y 2 // System.out.println("\n\n\nMatriz 1="); // m1.imprimeMatriz(); // System.out.println("\nMatriz 2="); //Poner en botones /* if(valida.validaSumayResta(m1,m2)) { m3 = operacion.sumaMat(m1,m2); JOptionPane.showMessageDialog(null,"La suma es = "); m3.imprimeMatriz(); } else { JOptionPane.showMessageDialog(null,"No es posible hacer la suma"); } if(valida.validaSumayResta(m1,m2)) { m3=operacion.restaMat(m1,m2); JOptionPane.showMessageDialog(null,"La resta es = "); m3.imprimeMatriz(); } else { JOptionPane.showMessageDialog(null,"No es posible hacer la resta"); } if(valida.validaMultiplicacion(m1,m2)){ m3=operacion.multiplicaMat(m1,m2); JOptionPane.showMessageDialog(null,"La multiplicacion es = "); m3.imprimeMatriz(); } else { JOptionPane.showMessageDialog(null,"No es posible hacer la multiplicacion"); } JOptionPane.showMessageDialog(null,"La multiplicacion es = "); m1=operacion.transpuesta(m1); m2=operacion.transpuesta(m2); */ } class Matriz { public JTextField matriz; //public JTextArea texto; private JFrame ventanaPrintMatriz; private JPanel panel2; int ren; int col; int pos[][]; public Matriz(int ren1, int col1) { ren = ren1; col = col1; pos = new int [ren][col];/*una matriz de enteros de renglon por columan*/ } public void llenarMatriz() { for(int i=0;i<ren;i++) for(int j=0;j<col;j++) pos[i][j]=(int) (Math.random()*10);/*la posicion i y j crea un entero random*/ } /*vuelve a recorrer los espacio de i y j*/ } //Esta clase era un metodo de CrearMatriz class ImprimirMatriz { public void ImprimirMatriz() { panel2 = new JPanel(); panel2.setLayout(null); ventanaPrintMatriz = new JFrame("Matriz"); ventana.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { //Practica2.ventanaAbierta=false; ventana.dispose(); } }); int i,j; int x=0,y=0; borderRed2 = BorderFactory.createLineBorder(red,2); white = new Color(255,255,255); red = new Color(255,0,0); black = new Color(0,0,0); blue = new Color(0,0,255); for(i=0;i<ren;i++) { for(j=0;j<col;j++) { matriz = new JTextField(" "+pos[i][j]); matriz.setBorder(borderRed2); matriz.setForeground(white); matriz.setBounds(x+25,y+25,25,25); matriz.setBackground(black); matriz.setEditable(false); matriz.setVisible(true); //Se incrementa la coordenada en X //para el siguiente Textfield no se encime x=x+35; //Agregamos el textField al panel panel2.add(matriz); } //Regreso las cordenadas de X a 0 para que el //siguiente renglon empieze en donde mismo x=0; //Incremento las coordenada Y para que se brinque //de linea y=y+35; } //Formato panel2 panel2.setBounds(150,150,350,380); panel2.setBackground(blue); //panel2.setEditable(false); panel2.setVisible(true); //Formato de Ventana ventanaPrintMatriz.setContentPane(panel2); ventanaPrintMatriz.setBounds(150,150,350,380); ventanaPrintMatriz.setResizable(false); ventanaPrintMatriz.setVisible(true); } } class Operaciones { public Matriz sumaMat(Matriz m1, Matriz m2) { Matriz m3; m3 = new Matriz(m1.ren, m1.col); for(int i=0;i<m1.col;i++) for(int j=0;j<m1.ren;j++) m3.pos[i][j]=m1.pos[i][j]+m2.pos[i][j]; return m3; } public Matriz restaMat(Matriz m1, Matriz m2) { Matriz m3; m3 = new Matriz(m1.ren, m1.col); for(int i=0;i<m1.col;i++) for(int j=0;j<m1.ren;j++) m3.pos[i][j]=m1.pos[i][j]-m2.pos[i][j]; return m3; } public Matriz multiplicaMat(Matriz m1, Matriz m2) { Matriz m3; m3 = new Matriz(m1.ren, m2.col); for(int i=0;i<m1.ren;i++) for(int j=0;j<m2.col;j++) { m3.pos[i][j]=0; for(int k=0;k<m1.col;k++) m3.pos[i][j]+=(m1.pos[i][k]*m2.pos[k][j]); } return m3; } public Matriz transpuesta(Matriz m1) { Matriz m3=new Matriz(m1.col,m1.ren); for(int i=0;i<m1.col;i++) for(int j=0;j<m1.ren;j++) m3.pos[i][j]=m1.pos[j][i]; return m3; } } class ValidacionesMatrices { public boolean validaSumayResta(Matriz m1, Matriz m2) { if((m1.ren==m2.ren) && (m1.col==m2.col)) return true; else return false; } public boolean validaMultiplicacion(Matriz m1, Matriz m2) { if(((m1.ren==m2.ren) && (m1.col==m2.col)) || (m1.col==m2.ren)) return true; else return false; } } public static void main(String[] args) { Practica2 practica2 = new Practica2(); practica2.inicializarComponentes(); } } Exc

    Read the article

  • Recursion causes exit to exit all JFrames (terminates app)

    - by Trizicus
    I have made an application that gives the user the option to open up a new spawn of the application entirely. When the user does so and closes the application the entire application terminates; not just the window. How should I go about recursively spawning an application and then when the user exits the JFrame spawn; killing just that JFrame and not the entire instance? Here is the relevant code: [...] JMenuItem newMenuItem = new JMenuItem ("New"); newMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new MainWindow(); } }); fileMenu.add(newMenuItem); [....] JMenuItem exit = new JMenuItem("Exit"); exit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }); fileMenu.add(exit); [...]

    Read the article

  • Laying out JPanels to make a simple GUI

    - by Elvis
    Hello, first of all, this is more or less my first GUI and ive learned Java for not more then a week, so it might contain some serious programming errors. What i have right now is: Buttons and labels are part of OptionPanel and are on the left, DrawingPanel is about 5x5 px in size and is on the right. What I am trying to do is a simple test, to get me more familiar with the GUI. The rectangle should be movable and re-sizeable by the user when clicking the respective buttons: http://www.upload.ee/image/612005/JFrame2.jpg Right now i have: JFrame MainFrame - Makes JFrame (Not using the setSize function. using .pack() instead. not sure about it) JPanel MergedPanel - FlowLayout - Adds JPanel OptionsPanel and JPanel DrawingPanel together and gets injected to JFrame MainFrame JPanel DrawPanel - This JPanel is responsible of drawing the rectangle. JPanel OptionPanel - FlowLayout - This JPanel is responsible of the buttons. Help please.

    Read the article

  • Avoid Circular Reference in Swing GUI

    - by drhorrible
    Maybe it's not worth worrying about in this scenario, but lets say you have two classes, a JFrame with all its components, and a server-like class that handles requests from remote clients. The user is able to start and stop server objects through the GUI, and is shown various events that happen to each server object. Whether or not I use an explicit pattern (like MVC), it seems like the JFrame needs a reference to the server class (to call start and stop) and the server needs a reference to the JFrame (to notify of it of certain events). Is this a problem, or am I looking at this situation in the wrong way?

    Read the article

  • calling a service layer method to my presentation layer

    - by Josepth Vodary
    Ok I feel really dumb asking this but I seem to be missing something really simple here. I have the following code in a class in my service layer - public Items getItems(String category, float amount, String color, String type) The code reads from a database and returns the results - I plan on placing it in a jframe. Nice and simple. But no matter how I call it from the jframe I get errors in eclipse that the code is wrong - either that their are illegal modifiers or such. So obviously I am calling it completely wrong, so my stupid question is how do you call that method into a jframe? For example - if I try to call it this way: public Items getItems(); I get told that getItems is an illegal parameter. If I call this.. Items getItems(); I am told its undefined

    Read the article

  • How to make game menu Java

    - by Deathsbreed
    I've been searching all over for how to make a game menu, but I haven't found anything useful. I have a very simple Pong like game (source-code here), and I want to add a main menu to it. This wouldn't be too much of a problem if I was making a standalone with JFrame instead of an Applet, but I want this to be available on the web (not downloaded). I might have been able to do some of it myself, except for the fact that it would mean having a very heavy main class (in this case the GNP.java file). So I was thinking, is there a way to basically have a Java Applet and have it use a JFrame and how? and if not, what could I do? Thanks!

    Read the article

  • Real-time graphing in Java

    - by thodinc
    I have an application which updates a variable about between 5 to 50 times a second and I am looking for some way of drawing a continuous XY plot of this change in real-time. Though JFreeChart is not recommended for such a high update rate, many users still say that it works for them. I've tried using this demo and modified it to display a random variable, but it seems to use up 100% CPU usage all the time. Even if I ignore that, I do not want to be restricted to JFreeChart's ui class for constructing forms (though I'm not sure what its capabilities are exactly). Would it be possible to integrate it with Java's "forms" and drop-down menus? (as are available in VB) Otherwise, are there any alternatives I could look into? EDIT: I'm new to Swing, so I've put together a code just to test the functionality of JFreeChart with it (while avoiding the use of the ApplicationFrame class of JFree since I'm not sure how that will work with Swing's combo boxes and buttons). Right now, the graph is being updated immediately and CPU usage is high. Would it be possible to buffer the value with new Millisecond() and update it maybe twice a second? Also, can I add other components to the rest of the JFrame without disrupting JFreeChart? How would I do that? frame.getContentPane().add(new Button("Click")) seems to overwrite the graph. package graphtest; import java.util.Random; import javax.swing.JFrame; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.plot.XYPlot; import org.jfree.data.time.Millisecond; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; public class Main { static TimeSeries ts = new TimeSeries("data", Millisecond.class); public static void main(String[] args) throws InterruptedException { gen myGen = new gen(); new Thread(myGen).start(); TimeSeriesCollection dataset = new TimeSeriesCollection(ts); JFreeChart chart = ChartFactory.createTimeSeriesChart( "GraphTest", "Time", "Value", dataset, true, true, false ); final XYPlot plot = chart.getXYPlot(); ValueAxis axis = plot.getDomainAxis(); axis.setAutoRange(true); axis.setFixedAutoRange(60000.0); JFrame frame = new JFrame("GraphTest"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ChartPanel label = new ChartPanel(chart); frame.getContentPane().add(label); //Suppose I add combo boxes and buttons here later frame.pack(); frame.setVisible(true); } static class gen implements Runnable { private Random randGen = new Random(); public void run() { while(true) { int num = randGen.nextInt(1000); System.out.println(num); ts.addOrUpdate(new Millisecond(), num); try { Thread.sleep(20); } catch (InterruptedException ex) { System.out.println(ex); } } } } }

    Read the article

  • Fonts, goes back to default size

    - by Bladimir Ruiz
    Every time I change the font, it goes back to the default size, which is 12, even if I change it before with the "Tamano" menu, it only goes back to 12 every time, my guess would be the way I change the size with deriveFont(), but don't I now any other way to change it. public static class cambiar extends JFrame { public cambiar() { final Font aryal = new Font("Comic Sans MS", Font.PLAIN, 12); JFrame ventana = new JFrame("Cambios en el Texto!"); JPanel adentro = new JPanel(); final JLabel texto = new JLabel("Texto a Cambiar!"); texto.setFont(aryal); JMenuBar menu = new JMenuBar(); JMenu fuentes = new JMenu("Fuentes"); /* Elementos de Fuentes */ JMenuItem arial = new JMenuItem("Arial"); arial.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Font arrrial = new Font("Arial", Font.PLAIN, 12); float tam = (float) texto.getFont().getSize(); String hola = String.valueOf(tam); texto.setFont(arrrial); texto.setFont(texto.getFont().deriveFont(tam)); } }); fuentes.add(arial); /* FIN Fuentes */ JMenu tamano = new JMenu("Tamano"); /* Elementos de Tamano */ JMenuItem font13 = new JMenuItem("13"); font13.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { texto.setFont(texto.getFont().deriveFont(23.0f)); } }); JMenuItem font14 = new JMenuItem("14"); arial.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { texto.setFont(aryal); } }); JMenuItem font15 = new JMenuItem("15"); arial.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { texto.setFont(aryal); } }); JMenuItem font16 = new JMenuItem("16"); arial.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { texto.setFont(aryal); } }); JMenuItem font17 = new JMenuItem("17"); arial.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { texto.setFont(aryal); } }); JMenuItem font18 = new JMenuItem("18"); arial.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { texto.setFont(aryal); } }); JMenuItem font19 = new JMenuItem("19"); arial.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { texto.setFont(aryal); } }); JMenuItem font20 = new JMenuItem("20"); arial.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { texto.setFont(aryal); } }); tamano.add(font13); /* FIN tanano */ JMenu tipo = new JMenu("Tipo"); /* Elementos de tipo */ /* FIN tipo */ /* Elementos del JMENU */ menu.add(fuentes); menu.add(tamano); menu.add(tipo); /* FIN JMENU */ /* Elementos del JPanel */ adentro.add(menu); adentro.add(texto); /* FIN JPanel */ /* Elementos del JFRAME */ ventana.add(adentro); ventana.setVisible(true); ventana.setSize(250, 250); /* FIN JFRAME */ } } Thanks in Advance!

    Read the article

  • JPanel clock and button merge

    - by user1509628
    I'm having a problem with in merging time and button together... I can't get the button show in the JPanel. This is my code: import java.awt.Color; import java.awt.Font; import java.text.DateFormat; import java.text.SimpleDateFormat; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public final class Date_Time extends JFrame{ private static final long serialVersionUID = 1L; private JPanel show_date_time = new JPanel(); private JLabel time = new JLabel("Time:"); private JLabel show_time = new JLabel("Show Time"); DateFormat dateFormat2 = new SimpleDateFormat("h:mm:ss a"); java.util.Date date2; private JLabel label; private JPanel panel; public Date_Time(){ this.setSize(300, 300); this.setResizable(false); getContentPane().add(Show_Time_date()); } private JButton button1 = new JButton(); private JFrame frame1 = new JFrame(); public JPanel Show_Time_date(){ frame1.add(show_date_time); show_date_time.setBackground(Color.ORANGE); frame1.add(button1); getShow_date_time().setLayout(null); Font f; f = new Font("SansSerif", Font.PLAIN, 15); getTime().setBounds(0,250,400,30); getTime().setFont(f); getShow_date_time().add(getTime()); setShow_time(new JLabel("")); updateDateTime(); getShow_time().setBounds(37,250,400,30); getShow_time().setFont(f); getShow_date_time().add(getShow_time()); return getShow_date_time(); } public static void main(String[] args) { Date_Time Main_win=new Date_Time(); Main_win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Main_win.setVisible(true); } public void updateDateTime() { Thread th = new Thread(new Runnable() { @Override public void run() { while(true) { date2 = new java.util.Date(); String dateTime = dateFormat2.format(date2); getShow_time().setText(dateTime); getShow_time().updateUI(); } } }); th.start(); } /** * @return the show_time */ public JLabel getShow_time() { return show_time; } /** * @param show_time the show_time to set */ public void setShow_time(JLabel show_time) { this.show_time = show_time; } /** * @return the time */ public JLabel getTime() { return time; } /** * @param time the time to set */ public void setTime(JLabel time) { this.time = time; } /** * @return the show_date_time */ public JPanel getShow_date_time() { return show_date_time; } /** * @param show_date_time the show_date_time to set */ public void setShow_date_time(JPanel show_date_time) { this.show_date_time = show_date_time; } /** * @return the label1 */ /** * @param label1 the label1 to set */ /** * @return the label */ public JLabel getLabel() { return label; } /** * @param label the label to set */ public void setLabel(JLabel label) { this.label = label; } /** * @return the panel */ public JPanel getPanel() { return panel; } /** * @param panel the panel to set */ public void setPanel(JPanel panel) { this.panel = panel; } }

    Read the article

  • Repaint() not calling paint() in Java

    - by Joshua Auriemma
    Let me start off by saying I know I've violated some basic Java principles in this messy code, but I'm desperately trying to finish a program by Tuesday for a social science experiment, and I don't know Java, so I'm basically just fumbling through it for now. With that disclaimer out of the way, I have a separate program working where a circle is moving around the screen and the user must click on it. It works fine when its in its own separate class file, but when I add the code to my main program, it's no longer working. I don't even really understand why repaint() calls my paint() function — as far as I'm concerned, it's magic, but I've noticed that repaint() calls paint() in my test program, but not in the more complicated actual program, and I assume that's why the circle is no longer painting on my program. Entire code is below: import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import javax.swing.*; import java.awt.event.*; import java.awt.geom.Ellipse2D; import java.io.FileReader; import java.io.IOException; import java.util.Calendar; public class Reflexology1 extends JFrame{ private static final long serialVersionUID = -1295261024563143679L; private Ellipse2D ball = new Ellipse2D.Double(0, 0, 25, 25); private Timer moveBallTimer; int _ballXpos, _ballYpos; JButton button1, button2; JButton movingButton; JTextArea textArea1; int buttonAClicked, buttonDClicked; private long _openTime = 0; private long _closeTime = 0; JPanel thePanel = new JPanel(); JPanel thePlacebo = new JPanel(); final JFrame frame = new JFrame("Reflexology"); final JFrame frame2 = new JFrame("The Test"); JLabel label1 = new JLabel("Press X and then click the moving dot as fast as you can."); public static void main(String[] args){ new Reflexology1(); } public Reflexology1(){ frame.setSize(600, 475); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setTitle("Reflexology 1.0"); frame.setResizable(false); frame2.setSize(600, 475); frame2.setLocationRelativeTo(null); frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame2.setTitle("Reflexology 1.0"); frame2.setResizable(false); button1 = new JButton("Accept"); button2 = new JButton("Decline"); //movingButton = new JButton("Click Me"); ListenForAcceptButton lForAButton = new ListenForAcceptButton(); ListenForDeclineButton lForDButton = new ListenForDeclineButton(); button1.addActionListener(lForAButton); button2.addActionListener(lForDButton); //movingButton.addActionListener(lForMButton); JTextArea textArea1 = new JTextArea(24, 50); textArea1.setText("Tracking Events\n"); textArea1.setLineWrap(true); textArea1.setWrapStyleWord(true); textArea1.setSize(15, 50); textArea1.setEditable(false); FileReader reader = null; try { reader = new FileReader("EULA.txt"); textArea1.read(reader, "EULA.txt"); } catch (IOException exception) { System.err.println("Problem loading file"); exception.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException exception) { System.err.println("Error closing reader"); exception.printStackTrace(); } } } JScrollPane scrollBar1 = new JScrollPane(textArea1, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); AdjustmentListener listener = new MyAdjustmentListener(); thePanel.add(scrollBar1); thePanel.add(button1); thePanel.add(button2); frame.add(thePanel); ListenForMouse lForMouse = new ListenForMouse(); thePlacebo.addMouseListener(lForMouse); thePlacebo.add(label1); frame2.add(thePlacebo); ListenForWindow lForWindow = new ListenForWindow(); frame.addWindowListener(lForWindow); frame2.addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e){ if(e.getKeyChar() == 'X' || e.getKeyChar() == 'x') {moveBallTimer.start();} } }); frame.setVisible(true); moveBallTimer = new Timer(1000, new ActionListener() { public void actionPerformed(ActionEvent e) { moveBall(); System.out.println("Timer started!"); repaint(); } }); addKeyListener(new KeyAdapter() { public void keyPressed(KeyEvent e) { if(frame2.isVisible()){ moveBallTimer.start(); } } }); } private class ListenForAcceptButton implements ActionListener{ public void actionPerformed(ActionEvent e){ if (e.getSource() == button1){ Calendar ClCDateTime = Calendar.getInstance(); System.out.println(ClCDateTime.getTimeInMillis() - _openTime); _closeTime = ClCDateTime.getTimeInMillis() - _openTime; //frame.getContentPane().remove(thePanel); //thePlacebo.addKeyListener(lForKeys); //frame.getContentPane().add(thePlacebo); //frame.repaint(); //moveBallTimer.start(); frame.setVisible(false); frame2.setVisible(true); frame2.revalidate(); frame2.repaint(); } } } private class ListenForDeclineButton implements ActionListener{ public void actionPerformed(ActionEvent e){ if (e.getSource() == button2){ JOptionPane.showMessageDialog(Reflexology1.this, "You've declined the license agreement. DO NOT RESTART the program. Please go inform a researcher that you have declined the agreement.", "WARNING", JOptionPane.INFORMATION_MESSAGE); System.exit(0); } } } private class ListenForWindow implements WindowListener{ public void windowActivated(WindowEvent e) { //textArea1.append("Window is active"); } // if this.dispose() is called, this is called: public void windowClosed(WindowEvent arg0) { } // When a window is closed from a menu, this is called: public void windowClosing(WindowEvent arg0) { } // Called when the window is no longer the active window: public void windowDeactivated(WindowEvent arg0) { //textArea1.append("Window is NOT active"); } // Window gone from minimized to normal state public void windowDeiconified(WindowEvent arg0) { //textArea1.append("Window is in normal state"); } // Window has been minimized public void windowIconified(WindowEvent arg0) { //textArea1.append("Window is minimized"); } // Called when the Window is originally created public void windowOpened(WindowEvent arg0) { //textArea1.append("Let there be Window!"); Calendar OlCDateTime = Calendar.getInstance(); _openTime = OlCDateTime.getTimeInMillis(); //System.out.println(_openTime); } } private class MyAdjustmentListener implements AdjustmentListener { public void adjustmentValueChanged(AdjustmentEvent arg0) { AdjustmentEvent scrollBar1; //System.out.println(scrollBar1.getValue())); } } public void paint(Graphics g) { //super.paint(g); frame2.paint(g); Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.RED); g2d.fill(ball); System.out.println("Calling fill()"); } protected void moveBall() { //System.out.println("I'm in the moveBall() function!"); int width = getWidth(); int height = getHeight(); int min, max, randomX, randomY; min =200; max = -200; randomX = min + (int)(Math.random() * ((max - min)+1)); randomY = min + (int)(Math.random() * ((max - min)+1)); //System.out.println(randomX + ", " + randomY); Rectangle ballBounds = ball.getBounds(); //System.out.println(ballBounds.x + ", " + ballBounds.y); if (ballBounds.x + randomX < 0) { randomX = 200; } else if (ballBounds.x + ballBounds.width + randomX > width) { randomX = -200; } if (ballBounds.y + randomY < 0) { randomY = 200; } else if (ballBounds.y + ballBounds.height + randomY > height) { randomY = -200; } ballBounds.x += randomX; ballBounds.y += randomY; _ballXpos = ballBounds.x; _ballYpos = ballBounds.y; ball.setFrame(ballBounds); } public void start() { moveBallTimer.start(); } public void stop() { moveBallTimer.stop(); } private class ListenForMouse implements MouseListener{ // Called when the mouse is clicked public void mouseClicked(MouseEvent e) { //System.out.println("Mouse Panel pos: " + e.getX() + " " + e.getY() + "\n"); if (e.getX() >=_ballXpos && e.getX() <= _ballXpos + 25 && e.getY() <=_ballYpos && e.getY() >= _ballYpos - 25 ) { System.out.println("TRUE"); } System.out.println("{e.getX(): " + e.getX() + " / " + "_ballXpos: " + _ballXpos + " | " + "{e.getY(): " + e.getY() + " / " + "_ballYpos: " + _ballYpos); } public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } } // System.out.println("e.getX(): " + e.getX() + " / " + "_ballXpos: " + _ballXpos); // Mouse over public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } // Mouse left the mouseover area: public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } } Could anyone tell me what I need to do to get repaint() to call the paint() method in the above program? I'm assuming the multiple frames is causing the problem, but that's just a guess. Thanks.

    Read the article

  • Please Critique Code (Java, Java2D, javax.swing.Timer)

    - by Trizicus
    Learn by practice right? Please critique and suggest anything! Thanks :) import java.awt.EventQueue; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import javax.swing.JFrame; public class MainWindow { public static void main(String[] args) { new MainWindow(); } JFrame frame; GraphicsPanel gp = new GraphicsPanel(); MainWindow() { EventQueue.invokeLater(new Runnable() { public void run() { frame = new JFrame("Graphics Practice"); frame.setSize(680, 420); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); gp.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} }); gp.addMouseMotionListener(new MouseMotionListener() { public void mouseDragged(MouseEvent e) {} public void mouseMoved(MouseEvent e) {} }); frame.add(gp); } }); } } GraphicsPanel: import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JPanel; import javax.swing.Timer; public class GraphicsPanel extends JPanel { Test t; Timer test; GraphicsPanel() { t = new Test(); setLayout(new BorderLayout()); add(t, BorderLayout.CENTER); test = new Timer(17, new Gameloop(this)); test.start(); } class Gameloop implements ActionListener { GraphicsPanel gp; Gameloop(GraphicsPanel gp) { this.gp = gp; } public void actionPerformed(ActionEvent e) { try { t.incX(); gp.repaint(); } catch (Exception ez) { } } } } Test: import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Toolkit; import javax.swing.JComponent; public class Test extends JComponent { Toolkit tk; Image img; int x, y; Test() { tk = Toolkit.getDefaultToolkit(); img = tk.getImage(getClass().getResource("images.jpg")); this.setPreferredSize(new Dimension(15, 15)); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g.create(); g2d.setColor(Color.red); g2d.drawString("x: " + x, 350, 50); g2d.drawImage(img, x, 80, null); g2d.dispose(); } public void incX() { x++; } }

    Read the article

  • ActionListener problem

    - by thegamer
    Hello, i am trying to make an actionListener on a button in another button which has also an actionlistener and i just couldn't figure it out for some way. I am trying to make an action on the 2nd button but i couldn't figure it out.If anyone helps me i'd appreciate! here is the code below: import java.awt.; import java.awt.event.; import javax.swing.; import java.io.; import java.util.*; public class basic implements ActionListener{ public static void main(String[] args) { basic process = new basic (); } public basic(){ JFrame fan = new JFrame("Scheme"); JPanel one = new JPanel(new BorderLayout()); fan.add(one); JPanel uno = new JPanel(); uno.setLayout(new BoxLayout(uno, BoxLayout.Y_AXIS)); JButton addB = new JButton("first choice"); addB.setAlignmentX(Component.CENTER_ALIGNMENT); uno.add(addB); addDButton.setActionCommand("hehe"); addDButton.addActionListener(this); one.add(uno,BorderLayout.CENTER); fan.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); fan.setSize(500,700); fan.setLocationByPlatform(true); fan.setVisible(true); } public void actionPerformed(ActionEvent evt) { JPanel markP = new JPanel(new FlowLayout(FlowLayout.RIGHT,10,20)); JDialog dialog = new JDialog((JFrame)null); dialog.getContentPane().add(markP,BorderLayout.CENTER); if (evt.getActionCommand().equals("hehe")) { JLabel title = new JLabel("Proceed"); title.setFont(new Font("Arial",Font.BOLD,15)); markP.add(title,BorderLayout.NORTH); JButton exit = new JButton("Exit"); markP.add(exit); //here i want to create another actionListener on the exit button only without affecting the other content which is in the button "addB " so that when i click on the addB button the J dialog pops up, and than when i click on exit button the program will return to the menu.I couldn't figure it out. dialog.toFront(); dialog.setModal(true); dialog.pack(); // dialog.setLocationRelativeTo(null); // dialog.setVisible(true); } // here the code goes on but the problem is that of the actionListener which is concerned.

    Read the article

  • Custom Monitor Resolution not recognized by Java

    - by Angie
    My weird monitor's native resolution isn't recognized by Windows, so I have to set a custom resolution for it. The problem is that java doesn't recognize it since it's not on Win7's "approved" list, so full-screen mode gets "stuck". Netbeans comes out of full-screen fine, so there has to be a way around this. Anyone know it? This example reproduces the issue: package resolutionexample; import java.awt.Dimension; import java.awt.DisplayMode; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import javax.swing.JFrame; import javax.swing.SwingUtilities; public class Main { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable(){ public void run() { GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice gd = ge.getDefaultScreenDevice(); DisplayMode currentDM = gd.getDisplayMode(); boolean currentInAvailable = false; System.out.println("Available resolutions:"); for ( DisplayMode availDM : gd.getDisplayModes() ){ //System.out.println(availDM.getWidth() + "x" + availDM.getHeight()); if ( availDM.equals(currentDM) ){ currentInAvailable = true; } } System.out.println("Current resolution: " + currentDM.getWidth() + "x" + currentDM.getHeight() ); System.out.println("Current in available: " + currentInAvailable); JFrame frame = new JFrame("Resolution Bug Example"); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); if ( !gd.isFullScreenSupported() ){System.exit(0);} gd.setFullScreenWindow(frame); gd.setFullScreenWindow(null); } }); } } Output running 1680x1050 (the monitor's wonky native resolution): run: Available resolutions: Current resolution: 1680x1050 Current in available: false Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Invalid display mode at sun.awt.Win32GraphicsDevice.setDisplayMode(Win32GraphicsDevice.java:393) at sun.awt.Win32GraphicsDevice.setFullScreenWindow(Win32GraphicsDevice.java:329) at resolutionexample.Main$1.run(Main.java:43) at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209) at java.awt.EventQueue.dispatchEvent(EventQueue.java:597) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161) at java.awt.EventDispatchThread.run(EventDispatchThread.java:122) BUILD SUCCESSFUL (total time: 2 seconds) Output if I set my resolution to 1024x768 before running: run: Available resolutions: Current resolution: 1024x768 Current in available: true BUILD SUCCESSFUL (total time: 2 seconds)

    Read the article

  • Malformed Farsi characters on AWT

    - by jlover2010
    Hi As i started programming by jdk6, i had no problem in text components neither in awt nor in swing. But for labels or titles of awt components, yes : I couldn't have Farsi characters displayable on AWTs just as simple as Swing by typing them into the source code. lets check this SSCCE : import javax.swing.*; import java.awt.*; import java.io.*; import java.util.Properties; public class EmptyFarsiCharsOnAWT extends JFrame{ public EmptyFarsiCharsOnAWT() { super("????"); setDefaultCloseOperation(3); setVisible(rootPaneCheckingEnabled); } public static void main(String[] args) throws AWTException, IOException { JFrame jFrame = new EmptyFarsiCharsOnAWT(); MenuItem show ; // approach 1 = HardCoding : /* show = new MenuItem("\u0646\u0645\u0627\u06cc\u0634"); * */ // approach 2 = using simple utf-8 saved text file : /* BufferedReader in = new BufferedReader(new FileReader("farsiLabels.txt")); String showLabel = in.readLine(); in.close(); show = new MenuItem(showLabel); * */ // approach 3 = using properties file : FileReader in = new FileReader("farsiLabels.properties"); Properties farsiLabels = new Properties(); farsiLabels.load(in); show = new MenuItem(farsiLabels.getProperty("tray.show")); PopupMenu popUp = new PopupMenu(); popUp.add(show); // creating Tray object Image iconIamge = Toolkit.getDefaultToolkit().getImage("greenIcon.png"); TrayIcon trayIcon = new TrayIcon(iconIamge, null, popUp); SystemTray tray = SystemTray.getSystemTray(); tray.add(trayIcon); jFrame.setIconImage(iconIamge); } } Yes, i know each of three approaches in source code does right when you may test it from IDE , but if you make a JAR contains just this class, by means of NetBeans project clean&build ,you won't see the expected characters and will just get EMPTY/BLANK SQUARES ! Unfortunately, opposed to other situations i encountered before, here there is no way to avoid using awt and make use of Swing in this case. And this was just an SSCCE i made to show the problem and my recent (also first) application suffers from this subject. Note: it seems i can not attach anything, so the contents od the text file would be this: ????? and the contents of properties file: #Sun May 02 09:45:10 IRDT 2010 tray.show=????? but i don't think by giving you the unicode-scape sequence, these would be necessary any way... And i think should have to let you know I posted this question a while ago in SDN and "the Java Ranch" forums and other native forums and still I'm watching... By the way i am using latest version of Netbeans IDE... I will be so grateful if anybody has a solution to this damn AWT components never rendered any Farsi character for me... Thanks in advance

    Read the article

  • Component must be a valid peer (when i remove frame.add(Component);)

    - by boyd
    i have this code here for creating and drawing array of pixels into an image import javax.swing.JFrame; import java.awt.Canvas; import java.awt.Graphics; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; public class test extends Canvas implements Runnable{ private static final long serialVersionUID = 1L; public static int WIDTH = 800; public static int HEIGHT = 600; public boolean running=true; public int[] pixels; public BufferedImage img; public static JFrame frame; private Thread thread; public static void main(String[] arg) { test wind = new test(); frame = new JFrame("WINDOW"); frame.add(wind); frame.setVisible(true); frame.setSize(WIDTH, HEIGHT); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); wind.init(); } public void init(){ thread=new Thread(this); thread.start(); img=new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB); pixels=((DataBufferInt)img.getRaster().getDataBuffer()).getData(); } public void run(){ while(running){ render(); try { thread.sleep(55); } catch (InterruptedException e) { e.printStackTrace(); } } } public void render(){ BufferStrategy bs=this.getBufferStrategy(); if(bs==null){ createBufferStrategy(4); return; } drawRect(0,0,150,150); Graphics g= bs.getDrawGraphics(); g.drawImage(img, 0, 0, WIDTH, HEIGHT, null); g.dispose(); bs.show(); } private void drawRect(int x, int y, int w, int h) { for(int i=x;i<w;i++) for(int j=x;j<h;j++) pixels[i+j*WIDTH]=346346; } } Why i get "Component must be a valid peer" error when i remove the line: frame.add(wind); Why I want to remove it? Because I want to create a frame using a class object(from another file) and use the code Window myWindow= new Window() to do exactly the same thing BTW: who knows Java and understands what i wrote please send me a message with your skype or yahoo messenger id.I want to cooperate with you for a project (graphics engine for games)

    Read the article

  • mulformed Farsi characters on AWT

    - by jlover2010
    Hi As i started programming by jdk6, i had no problem in text components neither in awt nor in swing. But for labels or titles of awt components, yes : I couldn't have Farsi characters displayable on AWTs just as simple as Swing by typing them into the source code. lets check this SSCCE : import javax.swing.*; import java.awt.*; import java.io.*; import java.util.Properties; public class EmptyFarsiCharsOnAWT extends JFrame{ public EmptyFarsiCharsOnAWT() { super("????"); setDefaultCloseOperation(3); setVisible(rootPaneCheckingEnabled); } public static void main(String[] args) throws AWTException, IOException { JFrame jFrame = new EmptyFarsiCharsOnAWT(); MenuItem show ; // approach 1 = HardCoding : /* show = new MenuItem("\u0646\u0645\u0627\u06cc\u0634"); * */ // approach 2 = using simple utf-8 saved text file : /* BufferedReader in = new BufferedReader(new FileReader("farsiLabels.txt")); String showLabel = in.readLine(); in.close(); show = new MenuItem(showLabel); * */ // approach 3 = using properties file : FileReader in = new FileReader("farsiLabels.properties"); Properties farsiLabels = new Properties(); farsiLabels.load(in); show = new MenuItem(farsiLabels.getProperty("tray.show")); PopupMenu popUp = new PopupMenu(); popUp.add(show); // creating Tray object Image iconIamge = Toolkit.getDefaultToolkit().getImage("greenIcon.png"); TrayIcon trayIcon = new TrayIcon(iconIamge, null, popUp); SystemTray tray = SystemTray.getSystemTray(); tray.add(trayIcon); jFrame.setIconImage(iconIamge); } } Yes, i know each of three approaches in source code does right when you may test it from IDE , but if you make a JAR contains just this class (and its resources) by means of NetBeans project clean&build ,you won't see the expected characters and will just get EMPTY/BLANK SQUARES ! Unfortunately, opposed to other situations i encountered before, here there is no way to avoid using awt and make use of Swing in this case. And this was just an SSCCE i made to show the problem and my recent (also first) application suffers from this subject. And i think should have to let you know I posted this question a while ago in SDN and "the Java Ranch" forums and other native forums and still I'm watching... By the way i am using latest version of Netbeans IDE... I will be so grateful if anybody has a solution to this damn AWT components never rendered any Farsi character for me... Thanks in advance

    Read the article

  • Unselecting RadioButtons in Java Swing

    - by Thomas
    When displaying a group of JRadioButtons, initially none of them is selected (unless you programmatically enforce that). I would like to be able to put buttons back into that state even after the user already selected one, i.e., none of the buttons should be selected. However, using the usual suspects doesn't deliver the required effect: calling 'setSelected(false)' on each button doesn't work. Interestingly, it does work when the buttons are not put into a ButtonGroup - unfortunately, the latter is required for JRadioButtons to be mutually exclusive. Also, using the setSelected(ButtonModel, boolean) - method of javax.swing.ButtonGroup doesn't do what I want. I've put together a small program to demonstrate the effect: two radio buttons and a JButton. Clicking the JButton should unselect the radio buttons so that the window looks exactly as it does when it first pops up. import java.awt.Container; import java.awt.GridLayout; import java.awt.event.*; import javax.swing.*; /** * This class creates two radio buttons and a JButton. Initially, none * of the radio buttons is selected. Clicking on the JButton should * always return the radio buttons into that initial state, i.e., * should disable both radio buttons. */ public class RadioTest implements ActionListener { /* create two radio buttons and a group */ private JRadioButton button1 = new JRadioButton("button1"); private JRadioButton button2 = new JRadioButton("button2"); private ButtonGroup group = new ButtonGroup(); /* clicking this button should unselect both button1 and button2 */ private JButton unselectRadio = new JButton("Unselect radio buttons."); /* In the constructor, set up the group and event listening */ public RadioTest() { /* put the radio buttons in a group so they become mutually * exclusive -- without this, unselecting actually works! */ group.add(button1); group.add(button2); /* listen to clicks on 'unselectRadio' button */ unselectRadio.addActionListener(this); } /* called when 'unselectRadio' is clicked */ public void actionPerformed(ActionEvent e) { /* variant1: disable both buttons directly. * ...doesn't work */ button1.setSelected(false); button2.setSelected(false); /* variant2: disable the selection via the button group. * ...doesn't work either */ group.setSelected(group.getSelection(), false); } /* Test: create a JFrame which displays the two radio buttons and * the unselect-button */ public static void main(String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); RadioTest test = new RadioTest(); Container contentPane = frame.getContentPane(); contentPane.setLayout(new GridLayout(3,1)); contentPane.add(test.button1); contentPane.add(test.button2); contentPane.add(test.unselectRadio); frame.setSize(400, 400); frame.setVisible(true); } } Any ideas anyone? Thanks!

    Read the article

  • JPanel components paint-time problem

    - by Tom Brito
    I'm having a problem that when my frame is shown (after a login dialog) the buttons are not on correct position, then in some miliseconds they go to the right position (the center of the panel with border layout). When I make a SSCCE, it works correct, but when I run my whole code I have this fast-miliseconds delay to the buttons to go to the correct place. Unfortunately, I can't post the whole code, but the method that shows the frame is: public void login(JComponent userView) { centerPanel.removeAll(); centerPanel.add(userView); centerPanel.revalidate(); centerPanel.repaint(); frame.setVisible(true); } What would cause this delay to the panel layout? (I'm running everything in the EDT) -- update In my machine, this SSCCE shows the layout problem in 2 of 10 times I run it: import java.awt.BorderLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class TEST { public static void main(String[] args) throws Exception { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { System.out.println("Debug test..."); JPanel btnPnl = new JPanel(); btnPnl.add(new JButton("TEST")); JFrame f = new JFrame("TEST"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane().setLayout(new BorderLayout()); f.getContentPane().add(btnPnl); f.pack(); f.setSize(800, 600); f.setVisible(true); System.out.println("End debug test!"); } }); } } The button first appers in the up-left, and then it goes to the center. Please, note that I'm understand, not just correct. Is it a java bug? --update OK, so the SSCCE don't show the problem with you that tried till now. Maybe it's my computer performance problem. But this don't answer the question, I still think Java Swing is creating new threads for make the layout behind the scenes.

    Read the article

  • How many ways a java Program can end ?

    - by Frank
    I know use System.exit(0) can end a java program, for instance, if I have a JFrame window, it will close and end the program, but I wonder how many other ways, can it be closed and the program be ended ? Including when an error occurs, will the program be shut down and the JFrame be closed ?

    Read the article

  • How to set text above and below a JButton icon?

    - by mre
    I want to set text above and below a JButton's icon. At the moment, in order to achieve this, I override the layout manager and use three JLabel instances (i.e. 2 for text and 1 for the icon). But this seems like a dirty solution. Is there a more direct way of doing this? Note -I'm not looking for a multi-line solution, I'm looking for a multi-label solution. Although this article refers to it as a multi-line solution, it actually seems to refer to a multi-label solution. EXAMPLE import java.awt.Component; import java.awt.FlowLayout; import javax.swing.BoxLayout; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingUtilities; import javax.swing.UIManager; public final class JButtonDemo { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { createAndShowGUI(); } }); } private static void createAndShowGUI(){ final JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new FlowLayout()); frame.add(new JMultiLabelButton()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } private static final class JMultiLabelButton extends JButton { private static final long serialVersionUID = 7650993517602360268L; public JMultiLabelButton() { super(); setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); add(new JCenterLabel("Top Label")); add(new JCenterLabel(UIManager.getIcon("OptionPane.informationIcon"))); add(new JCenterLabel("Bottom Label")); } } private static final class JCenterLabel extends JLabel { private static final long serialVersionUID = 5502066664726732298L; public JCenterLabel(final String s) { super(s); setAlignmentX(Component.CENTER_ALIGNMENT); } public JCenterLabel(final Icon i) { super(i); setAlignmentX(Component.CENTER_ALIGNMENT); } } }

    Read the article

  • Components are not longer resizable after moving

    - by Junior Software Developer
    Hi guys My question relates to swing programming. I want to enlarge a component (component x) by removing it from its parent panel (component a) and adding it in one of component a's parent (component b). Before that, I call setVisible(false) on all components in b. After that I want to make this back by removing it from b and adding on a. After that all components are not longer resizable. Why that? An easy example: import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTabbedPane; public class SwingTest { private static ViewPanel layer1; private static JFrame frame; private static JTabbedPane tabbedPane; private static ViewPanel root; public static void main(String[] args) { frame = new JFrame(); frame.setLayout(new BorderLayout()); frame.setMinimumSize(new Dimension(800, 600)); root = new ViewPanel(); root.setBackground(Color.blue); root.setPreferredSize(new Dimension(400, 600)); root.setLayout(new BorderLayout()); root.add(new JLabel("blue area")); layer1 = new ViewPanel(); layer1.setBackground(Color.red); layer1.setPreferredSize(new Dimension(400, 600)); layer1.setLayout(new BorderLayout()); tabbedPane = new JTabbedPane(); tabbedPane.add("A", new JLabel("A label")); tabbedPane.setPreferredSize(new Dimension(400, 600)); layer1.add(tabbedPane); root.add(layer1); frame.add(root, BorderLayout.NORTH); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.pack(); frame.setVisible(true); Thread t = new Thread() { @Override public void run() { try { Thread.sleep(8000); System.out.println("start"); for (Component c : root.getComponents()) { c.setVisible(false); } layer1.remove(tabbedPane); root.add(tabbedPane); Thread.sleep(8000); root.remove(tabbedPane); layer1.add(tabbedPane); for (Component c : root.getComponents()) { c.setVisible(true); c.repaint(); } } catch (InterruptedException e) { //... } } }; t.start(); } }

    Read the article

  • How does the event dispatch thread work?

    - by Roman
    With the help of people on stackoverflow I was able to get the following working code of the simples GUI countdown (it just displays a window counting down seconds). My main problem with this code is the invokeLater stuff. As far as I understand the invokeLater send a task to the event dispatching thread (EDT) and then the EDT execute this task whenever it "can" (whatever it means). Is it right? To my understanding the code works like that: In the main method we use invokeLater to show the window (showGUI method). In other words, the code displaying the window will be executed in the EDT. In the main method we also start the counter and the counter (by construction) is executed in another thread (so it is not in the event dispatching thread). Right? The counter is executed in a separate thread and periodically it calls updateGUI. The updateGUI is supposed to update GUI. And GUI is working in the EDT. So, updateGUI should also be executed in the EDT. It is why the code for the updateGUI is inclosed in the invokeLater. Is it right? What is not clear to me is why we call the counter from the EDT. Anyway it is not executed in the EDT. It starts immediately a new thread and the counter is executed there. So, why we cannot call the counter in the main method after the invokeLater block? import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingUtilities; public class CountdownNew { static JLabel label; // Method which defines the appearance of the window. public static void showGUI() { JFrame frame = new JFrame("Simple Countdown"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); label = new JLabel("Some Text"); frame.add(label); frame.pack(); frame.setVisible(true); } // Define a new thread in which the countdown is counting down. public static Thread counter = new Thread() { public void run() { for (int i=10; i>0; i=i-1) { updateGUI(i,label); try {Thread.sleep(1000);} catch(InterruptedException e) {}; } } }; // A method which updates GUI (sets a new value of JLabel). private static void updateGUI(final int i, final JLabel label) { SwingUtilities.invokeLater( new Runnable() { public void run() { label.setText("You have " + i + " seconds."); } } ); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { showGUI(); counter.start(); } }); } }

    Read the article

  • using Inheritence with GUI (graphical user interfaces) in Java

    - by maya
    hi everyone, I work on inheritence with GUI (graphical user interfaces) let me explain for example I made super class which is vehicle and the subclass is car, so the code to make inheritence will be public class Car extends Vehicle then I want to build the class Car as JFrame like public class Car JFrame implements ActionListener { so the problem is that I couldn't put both codes in the same class, and I need to do that. anyone help me. thanks in advance I wish that the question would be clear

    Read the article

< Previous Page | 4 5 6 7 8 9 10 11 12 13 14 15  | Next Page >