GridLayout positioning?
Hi,
Ok so heres my problem,
Ive got an array of 6 buttons and a label ive setup my jpanel to use gridlayout with 2 rows and 6 columns!
What i want to do is have the label in one row and the button array in the other how can i set it out like this as at the moment its taking both the label and buttons and laying them out across the two rows and six columns?!?
you just use a second PANEL with a BorderLayout
you put the Label in BorderLayout.NORTH and the other PANEL with the GridLayout to the BorderLayout.CENTER (its obvious you now only need 1 row with 6 colums in it which you can achieve by using new GridLa�out(0,6,sx,sy);
reading : determine the look of the gridlayout by the col�mns (6 columns then new row) and sx / sy spacing to next column/ row
like this
Panel p1=new Panel(new BorderLayout());
Panel p2=new Panel(new GridLayout(0,6,20,20));
p2.add(Butt1);
p2.add(Butt2);
p2.add(Butt3);
p2.add(Butt4);
p2.add(Butt5);
p2.add(Butt6);
p1.add(p2,BorderLayout.CENTER);
p1.add(label,BorderLayout.NORTH);this way you dont have to deal with the very complicated GridBagLayout!
Similar Messages
-
I've spent around 15 hours trying to work out how to draw something as simple as a line onto a JPanel!
I kind of understand about using paint, set color etc. if I was writing code in notepad I'm sure that it wouldn't be a problem but as I'm using the JDK SE form editor I'm very confused as to what should be done.
Basically i have a frame with 2 panels in gridLayout position and filled top to bottom left to right equally spaced.
I've added a button to the left panel. When this button is clicked I want to draw a line on the right panel. It's that simple! If I can do that then I can move on.
All the examples i've read don't show what to do when using the JDK SE form editor. Please can someone tell me exactly what to do...thankssee if you can follow this
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Testing extends JFrame
public Testing()
setSize(400,300);
setLocation(200,100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().add(new DrawPanel());
pack();
public static void main(String[] args){new Testing().setVisible(true);}
class DrawPanel extends JPanel
java.util.List points = new java.util.ArrayList();
public DrawPanel()
setPreferredSize(new Dimension(400,300));
setBackground(Color.WHITE);
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent me){
points = new java.util.ArrayList();
points.add(me.getPoint());}});
addMouseMotionListener(new MouseMotionListener(){
public void mouseMoved(MouseEvent me){}
public void mouseDragged(MouseEvent me){
points.add(me.getPoint());
DrawPanel.this.repaint();}});
public void paintComponent(Graphics g)
super.paintComponent(g);
if(points.size() > 0)
Point sPt = (Point)points.get(0);
for(int x = 1, y = points.size(); x < y; x++)
Point ePt = (Point)points.get(x);
g.drawLine(sPt.x,sPt.y,ePt.x,ePt.y);
sPt = ePt;
}if you want a bit of advice - dump the gui builder -
Start position of 2nd column in GridLayout
I have a gridlayout with 2 columns. Within the Gridlayout I have two transparent containers. The view is split nicely into 2 columns, but I want the second column to start halfway across the view (regardless of what is in column 1). Can I set a starting point for each column.
hi gareth.....
since you dont have a scrolling option... it happens like that....
what you can do is......
in your first column have an empty container and give the width and enable scrolling for it.... then insert the field inside it.
the same for the second column too.
it will work.
---regards,
alex b justin -
Problem with drawLine and GridLayout Manager
Hi
I am writing a piece of software that lets you design a local area network. Currently I have a JPanel with a GridLayout of 10 squares by 10 squares. Each of these grid spaces is filled with a small custom component that is blank if empty or displaying the relevant graphic to the user if a node has been placed. The difficulty that I am having is that I want to be able to draw a section of cable between nodes. As an example, when the user places a Server and a client, I want them to be able to hold down SHIFT, select the two nodes, then press a key (probably 'c') to automatically generate a run of cable between the two nodes. The software achieves this by getting the co-ordinates of the center point of the two nodes and drawing a line between them using the graphics class drawLine() method. I have all of this working fine apart from the bit where the cable needs to be drawn. The reason is that I can only create a section of cable by creating a new component and then using g.drawLine(). Fair enough. However, I can only draw within the small grid section designated by the GridLayout manager in the JPanel. What I am asking is how would I go about getting the software to draw a line between two relative co-ordinates on the screen, disregarding any positioning that the GridLayout manager tries to impose. To put it another way, how would I go about getting the software to draw a line between two absolutety specified co-ordinates, as opposed to relative co-ordinates currently being used? Any help would be greatly appeciated, thanksHere's a way to draw lines between component centers irrespective of layouts.
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
public class GridDrawing
public static void main(String[] args)
JLabel[] labels = new JLabel[100];
JPanel loPanel = new JPanel(new GridLayout(0,10));
for(int j = 0; j < labels.length; j++)
labels[j] = new JLabel(String.valueOf(j + 1), JLabel.CENTER);
labels[j].setBorder(BorderFactory.createEtchedBorder());
loPanel.add(labels[j]);
OverdrawPanel overdrawPanel = new OverdrawPanel();
CableSelector selector = new CableSelector(overdrawPanel, loPanel);
JPanel panel = new JPanel();
OverlayLayout overlay = new OverlayLayout(panel);
panel.add(overdrawPanel);
panel.setLayout(overlay);
panel.add(loPanel);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(panel);
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
class OverdrawPanel extends JPanel
List cableList;
public OverdrawPanel()
cableList = new ArrayList();
setOpaque(false);
protected void paintComponent(Graphics g)
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(Color.red);
for(int j = 0; j < cableList.size(); j++)
g2.draw((Line2D)cableList.get(j));
public void addCable(Point2D p1, Point2D p2)
Line2D line = new Line2D.Double(p1, p2);
cableList.add(line);
repaint();
public void register(CableSelector cs)
addMouseListener(cs);
class CableSelector extends MouseAdapter
OverdrawPanel overdrawPanel;
JPanel loPanel;
boolean firstPointSet;
Point2D firstPoint;
public CableSelector(OverdrawPanel op, JPanel lp)
overdrawPanel = op;
loPanel = lp;
firstPointSet = false;
overdrawPanel.register(this);
public void mousePressed(MouseEvent e)
Point p = e.getPoint();
Component[] c = loPanel.getComponents();
Rectangle r;
for(int j = 0; j < c.length; j++)
r = c[j].getBounds();
if(r.contains(p))
if(!firstPointSet)
firstPoint = new Point2D.Double(r.getCenterX(), r.getCenterY());
firstPointSet = true;
else
Point2D p2 = new Point2D.Double(r.getCenterX(), r.getCenterY());
overdrawPanel.addCable(firstPoint, p2);
firstPointSet = false;
} -
Adjust position and size of textField and button...
Dear All,
I have the following sample program which has a few textFields and a button, but the positions are not good. How do I make the textField to be at the right of label and not at the bottom of the label ? Also how to adjust the length of textField and button ? The following form design looks ugly. Please advise.
import javax.swing.*; //This is the final package name.
//import com.sun.java.swing.*; //Used by JDK 1.2 Beta 4 and all
//Swing releases before Swing 1.1 Beta 3.
import java.awt.*;
import java.awt.event.*;
import javax.swing.text.*;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import javax.swing.JFrame;
public class SwingApplication extends JFrame {
private static String labelPrefix = "Number of button clicks: ";
private int numClicks = 0;
String textFieldStringVEHNO = "Vehicle No";
String textFieldStringDATEOFLOSS = "Date of Loss";
String textFieldStringIMAGETYPE = "Image Type";
String textFieldStringIMAGEDESC = "Image Description";
String textFieldStringCLAIMTYPE = "Claim Type";
String textFieldStringSCANDATE = "Scan Date";
String textFieldStringUSERID = "User ID";
String ImageID;
public Component createComponents() {
//Create text field for vehicle no.
final JTextField textFieldVEHNO = new JTextField(5);
textFieldVEHNO.setActionCommand(textFieldStringVEHNO);
//Create text field for date of loss.
final JTextField textFieldDATEOFLOSS = new JTextField(10);
textFieldDATEOFLOSS.setActionCommand(textFieldStringDATEOFLOSS);
//Create text field for image type.
final JTextField textFieldIMAGETYPE = new JTextField(10);
textFieldIMAGETYPE.setActionCommand(textFieldStringIMAGETYPE);
//Create text field for image description.
final JTextField textFieldIMAGEDESC = new JTextField(10);
textFieldIMAGEDESC.setActionCommand(textFieldStringIMAGEDESC);
//Create text field for claim type.
final JTextField textFieldCLAIMTYPE = new JTextField(10);
textFieldCLAIMTYPE.setActionCommand(textFieldStringCLAIMTYPE);
//Create text field for scan date.
final JTextField textFieldSCANDATE = new JTextField(10);
textFieldSCANDATE.setActionCommand(textFieldStringSCANDATE);
//Create text field for user id.
final JTextField textFieldUSERID = new JTextField(10);
textFieldUSERID.setActionCommand(textFieldStringUSERID);
//Create some labels for vehicle no.
JLabel textFieldLabelVEHNO = new JLabel(textFieldStringVEHNO + ": ");
textFieldLabelVEHNO.setLabelFor(textFieldVEHNO);
//Create some labels for date of loss.
JLabel textFieldLabelDATEOFLOSS = new JLabel(textFieldStringDATEOFLOSS + ": ");
textFieldLabelDATEOFLOSS.setLabelFor(textFieldDATEOFLOSS);
//Create some labels for image type.
JLabel textFieldLabelIMAGETYPE = new JLabel(textFieldStringIMAGETYPE + ": ");
textFieldLabelIMAGETYPE.setLabelFor(textFieldIMAGETYPE);
//Create some labels for image description.
JLabel textFieldLabelIMAGEDESC = new JLabel(textFieldStringIMAGEDESC + ": ");
textFieldLabelIMAGEDESC.setLabelFor(textFieldIMAGEDESC);
//Create some labels for claim type.
JLabel textFieldLabelCLAIMTYPE = new JLabel(textFieldStringCLAIMTYPE + ": ");
textFieldLabelCLAIMTYPE.setLabelFor(textFieldCLAIMTYPE);
//Create some labels for scan date.
JLabel textFieldLabelSCANDATE = new JLabel(textFieldStringSCANDATE + ": ");
textFieldLabelSCANDATE.setLabelFor(textFieldSCANDATE);
//Create some labels for user id.
JLabel textFieldLabelUSERID = new JLabel(textFieldStringUSERID + ": ");
textFieldLabelUSERID.setLabelFor(textFieldUSERID);
Object[][] data = {
{"Mary", "Campione",
"Snowboarding", new Integer(5), new Boolean(false)},
{"Alison", "Huml",
"Rowing", new Integer(3), new Boolean(true)},
{"Kathy", "Walrath",
"Chasing toddlers", new Integer(2), new Boolean(false)},
{"Mark", "Andrews",
"Speed reading", new Integer(20), new Boolean(true)},
{"Angela", "Lih",
"Teaching high school", new Integer(4), new Boolean(false)}
String[] columnNames = {"First Name",
"Last Name",
"Sport",
"# of Years",
"Vegetarian"};
final JTable table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
//Add the scroll pane to this window.
getContentPane().add(scrollPane, BorderLayout.CENTER);
final JLabel label = new JLabel(labelPrefix + "0 ");
JButton buttonOK = new JButton("OK");
buttonOK.setMnemonic(KeyEvent.VK_I);
buttonOK.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
numClicks++;
ImageID = textFieldVEHNO.getText() + textFieldDATEOFLOSS.getText() + textFieldIMAGETYPE.getText();
label.setText(labelPrefix + ImageID);
ScanSaveMultipage doScan = new ScanSaveMultipage();
doScan.start(ImageID);
catch (Exception ev)
label.setLabelFor(buttonOK);
* An easy way to put space between a top-level container
* and its contents is to put the contents in a JPanel
* that has an "empty" border.
JPanel pane = new JPanel();
pane.setBorder(BorderFactory.createEmptyBorder(
20, //top
30, //left
30, //bottom
20) //right
pane.setLayout(new GridLayout(0, 1));
pane.add(textFieldLabelVEHNO);
pane.add(textFieldVEHNO);
pane.add(textFieldLabelDATEOFLOSS);
pane.add(textFieldDATEOFLOSS);
pane.add(textFieldLabelIMAGETYPE);
pane.add(textFieldIMAGETYPE);
pane.add(textFieldLabelIMAGEDESC);
pane.add(textFieldIMAGEDESC);
pane.add(textFieldLabelCLAIMTYPE);
pane.add(textFieldCLAIMTYPE);
pane.add(textFieldLabelDATEOFLOSS);
pane.add(textFieldDATEOFLOSS);
pane.add(textFieldLabelUSERID);
pane.add(textFieldUSERID);
pane.add(buttonOK);
pane.add(table);
//pane.add(label);
return pane;
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(
UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) { }
//Create the top-level container and add contents to it.
JFrame frame = new JFrame("SwingApplication");
SwingApplication app = new SwingApplication();
Component contents = app.createComponents();
frame.getContentPane().add(contents, BorderLayout.CENTER);
//Finish setting up the frame, and show it.
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
frame.pack();
frame.setVisible(true);Post Author: Ranjit
CA Forum: Crystal Reports
Sorry but, i've never seen formula editor for altering position and size. If you know one please navigate me.
I guess you have updated formula editor beside "Lock size and position" - if yes its not right. There is only one editor beside 4 items and editor is actually for Suppress.
Anyways, A trick to change size a position is:
Create 4-5 copies (as many as you expect positions) of the text object. place each at different positions, right click, Format, Suppress and in formula editor for suppress write the formula: If your condition is true, Suppress=false, else true.
Position will not change but user will feel; for different conditions -position is changed
Hope this helps.
Ranjit -
I need to control the position and size of each java swing component, help!
I setup a GUI which include 2 panels, each includes some components, I want to setup the size and position of these components, I use setBonus or setSize, but doesn't work at all. please help me to fix it. thanks
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.event.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.DefaultListModel;
public class weather extends JFrame {
private String[] entries={"1","22","333","4444"} ;
private JTextField country;
private JList jl;
private JTextField latitude;
private JTextField currentTime;
private JTextField wind;
private JTextField visibilityField;
private JTextField skycondition;
private JTextField dewpoint;
private JTextField relativehumidity;
private JTextField presure;
private JButton search;
private DefaultListModel listModel;
private JPanel p1,p2;
public weather() {
setUpUIComponent();
setTitle("Weather Report ");
setSize(600, 400);
setResizable(false);
setVisible(true);
private void setUpUIComponent(){
p1 = new JPanel();
p2 = new JPanel();
country=new JTextField(10);
latitude=new JTextField(12);
currentTime=new JTextField(12);
wind=new JTextField(12);
visibilityField=new JTextField(12);
skycondition=new JTextField(12);
dewpoint=new JTextField(12);
relativehumidity=new JTextField(12);
presure=new JTextField(12);
search=new JButton("SEARCH");
listModel = new DefaultListModel();
jl = new JList(listModel);
// jl=new JList(entries);
JScrollPane jsp=new JScrollPane(jl);
jl.setVisibleRowCount(8);
jsp.setBounds(120,120,80,80);
p1.add(country);
p1.add(search);
p1.add(jsp);
p2.add(new JLabel("latitude"));
p2.add(latitude);
p2.add(new JLabel("time"));
p2.add(currentTime);
p2.add(new JLabel("wind"));
p2.add(wind);
p2.add(new JLabel("visibility"));
p2.add(visibilityField);
p2.add(new JLabel("skycondition"));
p2.add(skycondition);
p2.add(new JLabel("dewpoint"));
p2.add(dewpoint);
p2.add(new JLabel("relativehumidity"));
p2.add(relativehumidity);
p2.add(new JLabel("presure"));
p2.add(presure);
this.getContentPane().setLayout(new FlowLayout());
this.setLayout(new GridLayout(1,2));
p2.setLayout(new GridLayout(8, 2));
this.add(p1);
this.add(p2);
public static void main(String[] args) {
JFrame frame = new weather();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
[http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html]
db -
Sticking components in JPanel to GridLayout
Could please anyone help in the following.
I have an application where some JPanel with several Swing components
positioned with help of GridLayout. What I need is to
remove and place components during runtime,
but the problem is that when I remove component placed somewhere
inbetween with use of the method remove() of the class JPanel,
all components are shifted so that the empty space is filled and
even one can see that the initial GridLayout is destroyed.
How can I stick all components to the initial grid cells of GridLayout?
I mean I do not want components to shift anywhere from their original
cells.
Thank you in advance.Well, that solution is what I came to also.
I mean I replacing removed compenent with some other invisible component.
But is this indeed the only way?
I tryied the method removeLayoutComponent() in the class GridLayout, but
I have not understood how it works and what it is for.
When I tryied it instead of remove() (of JPanel) it did not remove anything,
but it looks like something relevant to my situation.
PS The second line of my orginal poster should be read
"I have an application where some JPanel is created with several Swing components
positioned with help of GridLayout in it".
Sorry... -
Plotting the position of a robot.
Hi, I am building a GUI that receives data from a serial port. Once the information has been handle, I divide the stream into pieces and display the numbers they contain into JTextFields. Each of these pieces indicate the x-y coordinates, of a moving robot, which I want to show inside of a panel.
I can do the basics: draw a filled circle, the background, etc, but I dont know how to pass those numbers into the method that creates the draw. Also, I don't want to delete the "n-1" filled circles, so that at the end, I can see the path the robot took from the first position to the final one.
Thanks I really appreciate your help!First of all thanks for your prompt reply.
I have considered the option number one as well. As you can see in the following two classes, I call from InfoGpsGui the Dibujo class which makes the circle with variables "a" and "b". My problem is that I dont know how to implement that iteration that you mentioned, since I can't modify the parameters at the paintComponent method in Dibujo, so to be able to introduce these variables "a" and "b" from InfoGpsGui as it is receiving them from my serial port class.
I will appreciate any snippet or code that can give a hint on the matter.
// class Dibujo
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Arc2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
import java.awt.geom.Rectangle2D;
import javax.swing.JPanel;
public class Dibujo extends JPanel {
public static float a, b;
public Graphics2D comp2D;
public void paintComponent(Graphics comp) {
// Creates a Java 2D object
comp2D = (Graphics2D)comp;
// Defines the color of the rectangle that is going to be built
// to make a background
comp2D.setColor(Color.white);
Rectangle2D.Float background = new Rectangle2D.Float(
0F, 0F, (float)getSize().width, (float)getSize().height);
comp2D.fill(background);
// Defines a color-filled circle inside of the background
comp2D.setColor(Color.black);
BasicStroke pen2 = new BasicStroke();
comp2D.setStroke(pen2);
Ellipse2D.Float e1 = new Ellipse2D.Float(a, b, 15, 15);
comp2D.fill(e1);
// Class InfoGpsGui
import java.awt.Container;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.*;
public class InfoGpsGui extends JFrame{
static JTextField alt, lon, pos;
public static char[] letras = new char[5];
public static byte [] otroBuffer;
public static Dibujo map = new Dibujo();
private static Graphics comp;
public InfoGpsGui(){
//Characteristics of the frame
super("GPS Info");
setSize(650, 450);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//Outside-most frame, will contain the draw and info panels
JPanel pane = new JPanel();
pane.setLayout(new GridLayout(1, 0));
//Left sided frame, contains the drawing
JPanel draw = new JPanel();
//Container content = getContentPane();
draw.setLayout(new GridLayout(1,0));
draw.add(map);
pane.add(draw);
//Right sided frame, contains the info from the GPS
JPanel info = new JPanel();
info.setLayout(new GridLayout(3, 2));
JLabel altitudeLabel = new JLabel("Altitude: ");
alt = new JTextField(letras[0]);
JLabel positionLabel = new JLabel("Position: ");
pos = new JTextField(letras[1]);
JLabel longitudeLabel = new JLabel("Longitude: ");
lon = new JTextField(letras[2]);
//info.add(map);
info.add(altitudeLabel);
info.add(alt);
info.add(positionLabel);
info.add(pos);
info.add(longitudeLabel);
info.add(lon);
pane.add(info);
setContentPane(pane);
setVisible(true);
// Updates the values of the JTextFields in the GUI
public static void updateValues(String c, String d, String e){
alt.setText(c);
pos.setText(d);
lon.setText(e);
public static void main(String[] args){
InfoGpsGui berf = new InfoGpsGui();
SerialEcho input = new SerialEcho("COM4", 9600);
// Map prueba = new Map();
while (true) { // Keeps open the link between the serial port and the GUI
if (input.serialData) { // if there's data
otroBuffer = input.getData();
for (int i = 0; i < otroBuffer.length; i++) {
// System.out.print((char)otroBuffer);
letras = (char) otroBuffer; // Store data in letras
//System.out.println();
updateValues(Character.toString(letras[0]),Character.toString(letras[1]),
Character.toString(letras[2])); -
Hi all i just started java couple of days ago and im stuck on how to position my buttons on screen. I cant seem to position the button to the bottom of my screen lined up in rows. Also how can i insert an image area in the middle?
Thx people for your help
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SwingApplication implements ActionListener {
private static String labelPrefix = "Number of questions answered: ";
private int numClicks = 0;
final JLabel label = new JLabel(labelPrefix + "0 ");
//Specify the look and feel to use. Valid values:
//null (use the default), "Metal", "System", "Motif", "GTK+"
final static String LOOKANDFEEL = null;
public Component createComponents() {
JButton AnswerButton = new JButton("Answer");
JButton Submit = new JButton("Sumbit");
JButton button = new JButton("Next Question");
JTextField AnswerText = new JTextField("");
button.setMnemonic(KeyEvent.VK_I);
button.addActionListener(this);
label.setLabelFor(button);
* An easy way to put space between a top-level container
* and its contents is to put the contents in a JPanel
* that has an "empty" border.
JPanel pane = new JPanel(); //(new GridLayout(0, 1));
pane.setLayout(new GridLayout(2,3)) ; //2 rows, 3 columns
pane.add(button);
pane.add(label);
pane.add(AnswerText);
pane.add(AnswerButton);
pane.add(Submit);
pane.setBorder(BorderFactory.createEmptyBorder(
300, //top
300, //left
300, //bottom
300) //right
return pane;
}these links might help
http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html
http://java.sun.com/developer/onlineTraining/GUI/AWTLayoutMgr/shortcourse.html
then try this
import javax.swing.*;
import java.awt.*;
class SwingApplication extends JFrame
String labelPrefix = "Number of questions answered: ";
JLabel label = new JLabel(labelPrefix + "0 ");
public SwingApplication()
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocation(300,200);
setSize(400,300);
JButton answerButton = new JButton("Answer");
JButton submit = new JButton("Sumbit");
JButton button = new JButton("Next Question");
JTextField answerText = new JTextField("");
JPanel pane = new JPanel(new GridLayout(2,3));
pane.add(button);
pane.add(label);
pane.add(answerText);
pane.add(answerButton);
pane.add(submit);
getContentPane().add(pane,BorderLayout.SOUTH);
JLabel forImage = new JLabel(new ImageIcon("Test.gif"));
getContentPane().add(forImage,BorderLayout.CENTER);
public static void main(String[] args){new SwingApplication().setVisible(true);}
} -
Creating a gridlayout of jlabels and jbuttons in a JPanel
The assignment:
"Create a JPanel that contains an 8x8 checkerboard. Make all of the red squares JButtons and be sure to add them to the JPanel. Make all of the black squares JLabels and add them to the JPanel. Don't forget, you must use the add method to attach the JPanel to the JApplet's contentPane but that there is no contentPane for a JPanel. Be sure to set up any interfaces to handle the JButtons. Use a GridLayout to position and size each of the components instead of absolute locations and sizes."
This assignment introduces the JPanel to me for the first time, I have not seen what the JDialog and JFrame are.
What I have:
import java.awt.*;
import javax.swing.*;
* Class CheckerBoard - write a description of the class here
* @author (your name)
* @version (a version number)
public class CheckerBoard extends JPanel
JButton redSquare;
JLabel blackSquare;
* Called by the browser or applet viewer to inform this JApplet that it
* has been loaded into the system. It is always called before the first
* time that the start method is called.
public void init()
JPanel p = new JPanel();
setLayout(new GridLayout(8,8));
setSize(512,512);
ImageIcon red = new ImageIcon("GUI-006-RedButton.png");
ImageIcon black = new ImageIcon("GUI-006-BlackSquare.png");
blackSquare = new JLabel(black);
blackSquare.setSize(64,64);
redSquare = new JButton(red);
redSquare.setSize(64,64);
for (int i = 0; i < 64; i++) {
if ((i % 2) == 1)
add(blackSquare);
else
add(redSquare);
// this is a workaround for a security conflict with some browsers
// including some versions of Netscape & Internet Explorer which do
// not allow access to the AWT system event queue which JApplets do
// on startup to check access. May not be necessary with your browser.
JRootPane rootPane = this.getRootPane();
rootPane.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);
}After successfully compiling it when I try to run it there appears to be nothing to run. I've tried messing around with content panes but I'm not sure if I need to add one for this assignment at all.Some suggestions:
1) First and foremost, read about JPanels, JApplets, and JFrames. None of the help you can get here will substitute for your applying yourself towards this, absolutely none, and judging by your code, you have your work cut out for you.
2) Don't have your JPanel initialize with an init method, that's what Applets and JApplets do. Instead have it initialize with a proper constructor.
3) I'm wondering if your "workaround" code belongs in the JApplet that contains the JPanel and not in the JPanel. It has nothing to do with the JPanel's mission. For instance, what if you later decide to place this panel into a JFrame?
4) Avoid "setSize", and if at all possible, use "setPreferredSize" instead. You are working with LayoutManagers who do the size setting. You are best served by suggesting the size to them.
5) Please ask specific questions. Just dumping your code without a question is considered quite rude here. We are all volunteers. If you want our free advice, you really should be considerate enough to make it easy for us to help you.
Good luck.
Edited by: Encephalopathic on Dec 21, 2007 6:14 PM -
GUI component size/position control
Hi, everyone. I am trying to write a board game in Java. From my previous experience (I wrote a oscilloscope control interface using JFrame last year), most (or all?) of the GUI components (such as buttons and slider) change their sizes and positions automatically, when I used FlowLayout or BoardLayout layout manager. I also tried the BoxLayout layout manager, but it didn't work well.
Are there any way that I can control the size and the position of GUI components? By using a specific layout manager? or are there any way other than using different layout manager?
When I create my board game, I want my buttons to sit on the exact location I want, and appear at the size I want.
Thanks a lot.
DavidsonAbsolute positioning or writing your own layout manager is easier than you think, especially in the case of a board game.
Here is what you can do to use existing java class:
1. extends a JPanel with GridLayout, and overide all methods involving get size and set Size to fixed size. This is your actual game board.
2. use another JPanel with horizontal BoxLayout, add the panel in step 1 first, then add a Horizontal Glue, so in this new Panel, the width of your game board is honored here.
3. use another JPanel with verical BoxLayout, add the panel in step 2 first, then add a vertical glue. The height of the game board is honored here.
4. Both the width and the height are guarantteed to be fixed when the painting area is larger than the actual board.
5.To handle the case where the painting area is smaller than the board, you can use a JScrollPane, or to set the minimum size of the parent container so that it won't happen. -
I've noticed that awt and swing components have methods which are supposed to resize and move them directly, without using LayoutManagers (methods like setX(), setY(), setLocation(), setSize(), reshape() etc).
But when I try to use them, the component always stays the same. Let's say I have a single component on a Frame, so it takes all the available space. I don't seem to be able to resize and then move it using the above methods.
Or do I miss something? Is there any way that I could lay my components out on a container just by using these methods, or do I need to do something for them to work?
Thanks in advance. =DHirsch wrote:
But why is that, that
Container.setLayout(null);
should never be used?I suppose that absolute statements should never be made. null layout has its place (in fact, some here such as navy coder use it exclusively), but many if not most of us prefer to use the layout managers for many reasons. They automate the placement of your components, they make it much easier to create resizeable applications, they make it safer to create GUIs that will be used in multiple environments where different screen sizes are possible.
For example, suppose you create a program that displays JRadioButtons like so:
import java.awt.GridLayout;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class FuPanel2
private static void createAndShowUI()
String radioLabels[] =
"Fubar", "Snafu", "Bohica"
// create a JPanel for jradiobuttons and have it use gridlayout
JPanel radioPanel = new JPanel(new GridLayout(0, 1, 5, 5));
ButtonGroup btnGrp = new ButtonGroup();
for (int i = 0; i < radioLabels.length; i++)
JRadioButton rBtn = new JRadioButton(radioLabels);
btnGrp.add(rBtn);
radioPanel.add(rBtn);
JFrame frame = new JFrame("FuPanel2");
frame.getContentPane().add(radioPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
public static void main(String[] args)
java.awt.EventQueue.invokeLater(new Runnable()
public void run()
createAndShowUI();
You'll notice that the JPanel that holds the JRadioButtons uses the GridLayout. If I want to add another JRadioButton, "Tarfu", all I have to do is add the String to the array and another radiobutton is produced and placed in the right location. I don't have to worry about setting sizes or positions of anything as it's all done for me:
String radioLabels[] =
"Fubar", "Snafu", "Bohica", "Tarfu" // have added "Tarfu"
};Edited by: Encephalopathic on Aug 10, 2008 4:58 AM -
Beginner question for java appelets regarding positioning.
I am creating a java appelet, and I am having issues positioning labels, text boxes , buttons. Is there a way I can specify where each is positioned?
Thank you!
for example here is my code:
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
public class AdditionOfFractions extends Applet implements ActionListener {
Label Num1Lbl = new Label("num1");
Label Num2Lbl = new Label("num2");
Label Den1Lbl = new Label("den1");
Label Den2Lbl = new Label("den2");
Label ResultLbl = new Label("Result");
TextField Num1Text = new TextField(4);
TextField Num2Text = new TextField(4);
TextField Den1Text = new TextField(4);
TextField Den2Text = new TextField(4);
TextField ResultText = new TextField(4);
Button ComputeBtn = new Button("Compute");
Button ExitBtn = new Button("Exit");
public void actionPerformed(ActionEvent thisEvent)throws NumberFormatException {
if(ComputeBtn.hasFocus()){
System.out.println("test");
int num1 = Integer.parseInt(Num1Text.getText());
int num2 = Integer.parseInt(Num2Text.getText());
int den1 = Integer.parseInt(Den1Text.getText());
int den2 = Integer.parseInt(Den2Text.getText());
int newDen = 0;
if(den1 != den2){
public void init()
//initialise
ResultText.setEditable(false);
ComputeBtn.addActionListener(this);
ExitBtn.addActionListener(this);
//add components
add(Num1Lbl);
add(Num1Text);
add(Den1Lbl);
add(Den1Text);
add(Num2Lbl);
add(Num2Text);
add(Den2Lbl);
add(Den2Text);
add(ResultLbl);
add(ResultText);
add(ComputeBtn);
add(ExitBtn);
}797737 wrote:
I am creating a java appelet, and I am having issues positioning labels, text boxes , buttons. Is there a way I can specify where each is positioned?Definitely, for your simple Applet you'll probably just want to use a <tt>java.awt.GridLayout</tt>. This will effectively position all your components in a grid pattern that you set in the contructor.
//make a grid 4 rows, 2 columns
GridLayout gridLayout = new GridLayout(4, 2);Then you'll need to set this for the Applet like so:
pubic void init(){
//initial your components as usual
setLayout(gridLayout);
//add components as usual;
}Now 37, you don't want the <tt>actionPerformed()</tt> method to throw any Exceptions. Instead put your code inside a try/catch block:
public void actionPerformed(ActionEvent ae)
int num1, num2, den1, den2;
try {
num1 = Integer.parseInt(Num1Text.getText());
num2 = Integer.parseInt(Num2Text.getText());
den1 = Integer.parseInt(Den1Text.getText());
den2 = Integer.parseInt(Den2Text.getText());
catch(NumberFormatException)
//provide DEFAULT VALUES HERE;
}37, try to use the <tt>EventObject.getSource()</tt>, or <tt>ActionEvent.getActionCommand()</tt>.
public void actionPerformed(ActionEvent ae) {
//Choose one of the following lines
//line 2 is probably a better choice here
Button button = (Button)ae.getSource();
String actionCommand = ae.getActionCommand();
if(actionCommand.equals("Compute"))
//try/catch block here
//compute here
//set results
// OR create a compute() that
// includes all three lines above
}Now OP, I have a question for you. Do you see a way to LIMIT the values of <tt>num1, num2, den1, den2</tt> so that your program is safe to run -- so that the compute formula does not throw any ArithmeticExceptions? -
how come when i compile, it says :
:\Documents and Settings\Tang\Desktop\Grid.java:22: cannot find symbol
symbol : class Position
location: class Grid
container.add (button , new Position (0,0) ) ;
how do i position a button???
import javax.swing.* ;
import java.awt.*;
class Grid extends JFrame
public static void main (String args [])
Grid grid = new Grid ();
public Grid ()
init() ;
public void init()
JFrame frame = new JFrame() ;
Container container = frame.getContentPane() ;
container.setLayout (new GridLayout (3,3)) ;
JButton button = new JButton ("BUTTON1") ;
container.add (button ,new Position (0,0) ) ;
}There's JavaDoc for Position:
* Represents a location within a document. It is intended to abstract away
* implementation details of the document and enable specification of
* positions within the document that are capable of tracking of change as
* the document is edited (i.e. offsets are fragile).
Where the hell is there any word about GridLayout?
If You want to add to GdidLayout at a given position, you have to select the index of a Component:
0 | 1 | 2
3 | 4 | 5
6 | 7 | 8
so if you want to add it into center grid:
add(button,4) -
HELP!!! save position of the components!!!
Hi!
I have a JLayeredPane where I insert some images. I move this images. BUT when I press a button (that invoke a ActionListener) all the images return at initial position!!!
THE PROGRAM:
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import javax.swing.text.*; //per StyledDocument
import javax.swing.BorderFactory;
import javax.imageio.*;
public class mio implements ActionListener,MouseMotionListener,MouseListener{
JTextArea statusInfo; //info da passare a PROGRAMMA TODO
JTextArea PASpar; // PARAMETRI X TODO
JTextArea PASimage; //IMMAGINI X TODO
Color whitex = new Color(255,255,255);
Color bluex = new Color(100,105,170);
Color bluexx = new Color(100,150,170);
Color redx = new Color(255,0,0);
JFrame frame; //contiene tutto
JFrame frameP;
JMenuBar menu;
JMenu fileMenu;
JMenuItem nuovo;
JMenuItem apriimgf;
JMenuItem aprimosf;
JMenuItem salva;
JMenuItem stampa;
JMenuItem esci;
JMenu modMenu;
JMenuItem annulla;
JMenu helpMenu;
JMenuItem help;
JPanel panel; //contiene oggetti entro menu
JPanel panel2;
JPanel panel3; //xbottoni
JLayeredPane pane;
JTextArea spiega;
JTextArea dico2;
JLayeredPane panelpane; //dove carico img
JButton apriimg;
JButton chiudi;
JButton aprimos;
JButton ok;
JButton mosaica;
JButton superR;
JButton salvab;
JButton migliora;
JButton nuovob;
int _dragFromX = 0; // pressed this far inside ball's
int _dragFromY = 0;
boolean _canDrag = false;
int i;
int px;
int py;
int mousex;
int mousey;
int rifno;//x img d riferimento
int scelta; //1 = immagini 2=mosaico
int Nimg; // NUMERO IMG KE INSERISCO <= 12
JLabel image;
ImageIcon icon;
int ximg, yimg; //posizione img in panel
int xgrid,ygrid; //griglia panel
int[] ximgs,yimgs; //x,y img
JLabel[] images;
int hicon,wicon; //h w img
int[] wimgs,himgs;
int muovi; //img da muovere nell'array
public final static int ONE_SECOND = 500; ////
private JProgressBar progressBar;
private javax.swing.Timer timer;
private JButton startButton;
private LongTask task;
private JTextArea taskOutput;
static private String newline = "\n";
// =================== MAIN
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
mio m = new mio();
/*public static void main(String argv[]){
mio m = new mio();
// ================ COSTRUTTORE
public mio(){
rifno = 0;//no img d rif
Nimg = 0;
frame = new JFrame("interfaccia");
PASpar = new JTextArea();
PASimage = new JTextArea();
menu = new JMenuBar();
menu.setOpaque(true);
menu.setBackground(bluex);
// ********* Menu file *********
fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
nuovo = new JMenuItem("Nuovo");
nuovo.setMnemonic(KeyEvent.VK_N);
apriimgf = new JMenuItem("Apri immagini");
apriimgf.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_1, ActionEvent.ALT_MASK)); //alt+1
aprimosf = new JMenuItem("Apri mosaico");
salva = new JMenuItem("Salva");
salva.setMnemonic(KeyEvent.VK_S);
esci = new JMenuItem("Esci");
esci.setMnemonic(KeyEvent.VK_E);
//********* Menu Modifica ***********
modMenu = new JMenu("Modifica");
modMenu.setMnemonic(KeyEvent.VK_M);
annulla = new JMenuItem("Annulla");
annulla.setMnemonic(KeyEvent.VK_A);
// ********* Help Menu *************
helpMenu = new JMenu("HELP");
help = new JMenuItem("Help");
menu.add(fileMenu);
fileMenu.add(nuovo);
fileMenu.add(apriimgf);
fileMenu.add(aprimosf);
fileMenu.add(salva);
fileMenu.addSeparator();
fileMenu.addSeparator();
fileMenu.add(esci);
menu.add(modMenu);
modMenu.add(annulla);
menu.add(helpMenu);
helpMenu.add(help);
// ActionListener x ogni voce d menu
nuovo.addActionListener(this);
apriimgf.addActionListener(this);
aprimosf.addActionListener(this);
salva.addActionListener(this);
esci.addActionListener(this);
annulla.addActionListener(this);
help.addActionListener(this);
frame.setJMenuBar(menu);//in frame menu
panel=new JPanel(new BorderLayout(2,2));
frame.getContentPane().add(panel);
spiega = new JTextArea(" 1. Aprire TUTTE le immagini da mosaicare"+ newline +" Oppure il mosaico da migliorare"+newline,3,40);
spiega.setEditable(false);
spiega.setBorder(BorderFactory.createLineBorder(Color.black));//bordo
spiega.setBackground(bluex);
panelpane = new JLayeredPane();
panelpane.setPreferredSize(new Dimension(900,550));
panelpane.setBackground(whitex);
panelpane.setLayout(new GridLayout(0,4)); //max 12 img e occupano tutto subito
panelpane.setBorder(BorderFactory.createLineBorder(Color.black));
panelpane.addMouseListener(this);
panelpane.addMouseMotionListener(this);
xgrid = 225;
ygrid =183;
ximg = 0;
yimg = 0;
images = new JLabel[12];//immagini
ximgs = new int[12];
yimgs = new int[12];
wimgs = new int[12];
himgs = new int[12];
panel3= new JPanel();
panel3.setBackground(bluex);
panel3.setLayout(new BoxLayout(panel3, BoxLayout.Y_AXIS));
panel3.setBorder(BorderFactory.createLineBorder(Color.black));
chiudi = new JButton("Chiudi applicazione");
chiudi.addActionListener(this);
chiudi.setBackground(bluex);
// ******* 1 FRAME
apriimg = new JButton("Apri immagine");
apriimg.addActionListener(this);
apriimg.setBackground(bluex);
aprimos = new JButton("Apri mosaico");
aprimos.addActionListener(this);
aprimos.setBackground(bluex);
ok = new JButton("Prosegui");
ok.addActionListener(this);
ok.setBackground(bluex);
ok.setEnabled(false); //disabilito
//****** 2 frame
mosaica = new JButton(" Mosaica ");
mosaica.addActionListener(this);
mosaica.setBackground(bluex);
mosaica.setVisible(false);
superR = new JButton("Super-Risoluzione");
superR.addActionListener(this);
superR.setBackground(bluex);
superR.setVisible(false);
// ********* 3 frame
salvab = new JButton(" Salva mosaico ");
salvab.addActionListener(this);
salvab.setBackground(bluex);
salvab.setVisible(false);
migliora = new JButton(" Migliora mosaico ");
migliora.addActionListener(this);
migliora.setBackground(bluex);
migliora.setVisible(false);
nuovob = new JButton(" Nuovo progetto ");
nuovob.addActionListener(this);
nuovob.setBackground(bluex);
nuovob.setVisible(false);
statusInfo = new JTextArea(3,40);
statusInfo.setBorder(BorderFactory.createLineBorder(Color.black));
statusInfo.setBackground(bluex);
JScrollPane scrollArea = new JScrollPane(statusInfo);
panel.add((spiega), BorderLayout.NORTH);
panel.add((panelpane), BorderLayout.CENTER);
panel.add((panel3), BorderLayout.EAST);
panel.add((scrollArea), BorderLayout.SOUTH);
panel3.add(apriimg);
panel3.add(salvab);//3 frame
panel3.add(new JSeparator(JSeparator.HORIZONTAL));
panel3.add(aprimos);
panel3.add(mosaica); // 2 frame
panel3.add(migliora);
panel3.add(new JSeparator(JSeparator.HORIZONTAL));
panel3.add(ok);
panel3.add(superR); // 2 frame
panel3.add(nuovob); // 3 frame
panel3.add(new JSeparator(JSeparator.HORIZONTAL));
panel3.add(chiudi);
frame.pack();
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}// chiude costruttore
// ================ metti mosaico
public void mettiMosaico(){
panelpane.removeAll();
ImageIcon img1 = new ImageIcon("mosaico.jpg");
Image imgesize1 = resize2Icon("mosaico.jpg"); // resize
img1 = new ImageIcon(imgesize1);
JLabel image1 = new JLabel(img1);
image1.setLocation(200,10);
panelpane.add(image1);
panelpane.repaint();
// ================= RESIZE MOSAICO
public Image resize2Icon(String image){
Image img;
Image inImage = new ImageIcon(image).getImage();
int maxDim = 500;
double scale = (double) maxDim / (double) inImage.getHeight(null);
if (inImage.getWidth(null) > inImage.getHeight(null))
scale = (double) maxDim / (double) inImage.getWidth(null);
// Determine size of new image.
//One of them
// should equal maxDim.
int scaledW = (int) (scale * inImage.getWidth(null));
int scaledH = (int) (scale * inImage.getHeight(null));
System.out.println(">> "
+ inImage.getSource().getClass()
+ " aspect ratio = "
+ scaledW + " , " + scaledH);
img = inImage.getScaledInstance(scaledW , scaledH, Image.SCALE_SMOOTH);
return img;
// ================= RESIZE IMAGES
public Image resizeIcon(String image){
Image img;
Image inImage = new ImageIcon(image).getImage();
int maxDim = 180;
double scale = (double) maxDim / (double) inImage.getHeight(null);
if (inImage.getWidth(null) > inImage.getHeight(null))
scale = (double) maxDim / (double) inImage.getWidth(null);
// Determine size of new image.
//One of them
// should equal maxDim.
int scaledW = (int) (scale * inImage.getWidth(null));
int scaledH = (int) (scale * inImage.getHeight(null));
System.out.println(">> "
+ inImage.getSource().getClass()
+ " aspect ratio = "
+ scaledW + " , " + scaledH);
img = inImage.getScaledInstance(scaledW , scaledH, Image.SCALE_SMOOTH);
return img;
// ================== img RIFERIMENTO
public void imgRif(){
frameP.setVisible(false);//tolgo frame
rifno=1;
spiega.setText (" Con il mouse indicare l'immagine di riferimento"+newline);
}//fine imgRif
// ================== BARRA PROGRESS
public void barraP(){
final JFrame framePb = new JFrame("ELABORAZIONE in corso");
framePb.setSize(300,1000);
framePb.setBackground(bluex);
statusInfo.append(" Elaborazione in corso... "+newline);
JPanel panelPb=new JPanel(new BorderLayout());
panelPb.setBackground(bluex);
panelPb.setBorder(BorderFactory.createLineBorder(Color.black));
panelPb.setPreferredSize(new Dimension(300,100));
framePb.getContentPane().add(panelPb);
task = new LongTask();
progressBar = new JProgressBar(0, task.getLengthOfTask());
progressBar.setValue(0);
progressBar.setStringPainted(true);
panelPb.add(progressBar);
//Create a timer.
timer = new javax.swing.Timer(ONE_SECOND, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
progressBar.setValue(task.getCurrent());
String s = task.getMessage();
if (task.isDone()) {
Toolkit.getDefaultToolkit().beep();
timer.stop();
statusInfo.append(" Eseguita elaborazione "+newline);
spiega.setText (" 4. Migliora, Salva, Nuovo progetto o Esci"+newline);
superR.setVisible(false);
mosaica.setVisible(false);
salvab.setVisible(true);
migliora.setVisible(true);
nuovob.setVisible(true);
framePb.setVisible(false);
framePb.setCursor(null); //turn off the wait cursor
progressBar.setValue(progressBar.getMinimum());
//panelpane.removeAll();
//inserisco mosaico creato
framePb.pack();
framePb.setVisible(true);
framePb.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
task.go();
timer.start();
framePb.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
// ===================================================================================== EVENTI
public void actionPerformed(ActionEvent e) {
Object source = e.getSource(); //chi ha invocato evento
// ====================================================================================== NUOVO
if((source == nuovo)||(source == nuovob)){
System.out.println("Nuovo");
mio m = new mio();
// ====================================================================================== HELP
if(source == help){
System.out.println("Help");
final JFrame framePh = new JFrame(" - H E L P - ");
framePh.setSize(300,1000);
JTextArea help=new JTextArea(" Help per utente! "+newline,5,40);
help.setEditable(false);
help.setBorder(BorderFactory.createLineBorder(Color.black));//bordo
//help.setBackground(bluex);
JButton escih = new JButton(" Esci ");
escih.setBackground(bluex);
escih.addActionListener(new ActionListener(){ //quando premo esci
public void actionPerformed(ActionEvent e){
framePh.setVisible(false); // SQUALLIDO! esci meglio!
framePh.getContentPane().add(help);
framePh.pack();
framePh.setVisible(true);
// ======================================================================================== APRI
if((source == apriimgf) || (source == apriimg)){ //apri + img
System.out.println("Apri");
scelta=1; //immagini
Image imgresize;
JFileChooser fileChooser = new JFileChooser();
fileChooser.addChoosableFileFilter(new ImageFilter());//filtro
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.setAccessory(new ImagePreview(fileChooser));//anteprima
fileChooser.setCurrentDirectory(new File("."));
fileChooser.setMultiSelectionEnabled(true);
int status = fileChooser.showOpenDialog(null);
if (status == JFileChooser.APPROVE_OPTION) {
File selectedFiles[] = fileChooser.getSelectedFiles();
if (selectedFiles.length>12){
System.out.println("selezionati piu' di 12 img");
return;
if (Nimg>12){
System.out.println("Ho piu' di 12 img");
return;
//int imgora = Nimg + selectedFiles.length; //immagini totali caricate fin'ora
int imgPrima = Nimg; //img prima di inserire le selezionate
int imgIns = selectedFiles.length; //immagini inserite ora.
for (int im=0,n=selectedFiles.length; im<n; im++) {
icon = new ImageIcon(selectedFiles[im].getAbsolutePath());
statusInfo.append(" Inserito: " + selectedFiles[im].getName() + newline);
int hicon = icon.getIconHeight();
int wicon = icon.getIconWidth();
if ((hicon>183)||(wicon>225)){
imgresize = resizeIcon(selectedFiles[im].getAbsolutePath()); // resize
icon = new ImageIcon(imgresize);
if (ximg>675){
if (yimg>366){
System.out.println(" TROPPE IMG!!! ");
else{
ximg=0;
yimg=yimg+ygrid;
image = new JLabel(icon);
image.setBounds(ximg,yimg,hicon,wicon);
//aggiorno dati IMMAGINI
yimgs[im+imgPrima]=yimg;
ximgs[im+imgPrima]=ximg;
images[im+imgPrima] = image;
himgs[im+imgPrima] = hicon;
wimgs[im+imgPrima] = wicon;
statusInfo.append("");
panelpane.add(images[im+imgPrima], new Integer(0),12-(im+imgPrima)); //ULTIMA SOPRA
//images[im+imgPrima].setLocation(ximgs[im+imgPrima],yimgs[im+imgPrima]);
ximg = ximg + xgrid;
Nimg=Nimg+1; //n img totale
ok.setEnabled(true); //abilito
aprimos.setEnabled(false); //abilito
spiega.setText (" 2.Con il mouse spostare le immagini creando un 'mosaico'"+newline);
// ============================================================================= apri mosaico
if((source == aprimos)||(source == aprimosf)){
System.out.println("Apri mosaico");
scelta=2; //mosaico
JFileChooser fileChooser = new JFileChooser();
fileChooser.addChoosableFileFilter(new ImageFilter());//filtro
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.setAccessory(new ImagePreview(fileChooser));//anteprima
fileChooser.setCurrentDirectory(new File("."));
fileChooser.setMultiSelectionEnabled(false);
int status = fileChooser.showOpenDialog(null);
if (status == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
icon = new ImageIcon(selectedFile.getAbsolutePath());
int hicon = icon.getIconHeight();
int wicon = icon.getIconWidth();
image = new JLabel(icon);
image.setBounds(ximg,yimg,hicon,wicon);
statusInfo.append("");
panelpane.add(image,new Integer(1),1);//dopo sopra
ok.setEnabled(true); //abilito
apriimg.setEnabled(false); //abilito
aprimos.setEnabled(false); //abilito
spiega.setText (" 2. Proseguire"+newline);
// =============================================================================== SALVA
if(source == salva){
System.out.println("Salva");
try {
FileOutputStream fos = new FileOutputStream ("info.doc"); //doc.ser
ObjectOutputStream oos = new ObjectOutputStream (fos);
String infoo = statusInfo.getText(); // NON E' GIUSTO!!!
oos.writeObject(infoo);
oos.flush();
oos.close();
statusInfo.append(" Salvato il progetto in: info.doc"+newline);
} catch (IOException e1) {
statusInfo.setText (" Unable to save");
e1.printStackTrace(); //scrivo eccezione
// =============================================================================== PROSEGUI
if(source == ok){
System.out.println("Prosegui");
apriimg.setVisible(false);
aprimos.setVisible(false);
ok.setVisible(false);
mosaica.setVisible(true);
panelpane.removeMouseMotionListener(this);
if (scelta==1){
superR.setVisible(true);
panelpane.revalidate ();
spiega.setText (" 3. Scegliere Mosaicatura o Super-Risoluzione"+newline);
}else{
panelpane.revalidate ();
spiega.setText (" 3. Eseguire Mosaicatura"+newline);
// ================================================================================= ESCI
if((source == esci)||(source==chiudi)){
System.out.println("Esci");
System.exit(0);
// =================================================================================== ANNULLA
if(source == annulla){
System.out.println("Annulla");
// ======================================================================================== MOSAICA
if(source == mosaica){
System.out.println("Mosaica");
frameP = new JFrame("Parametri di Mosaicatura");
frameP.setSize(800,800);
frameP.setBackground(bluex);
JPanel panelP=new JPanel(new GridLayout(1,0));
panelP.setBackground(bluex);
panelP.setBorder(BorderFactory.createLineBorder(Color.black));
panelP.setPreferredSize(new Dimension(500,500));
frameP.getContentPane().add(panelP);
JPanel panelP0 = new JPanel(new FlowLayout()); //avvia
panelP0.setBackground(bluex);
panelP0.setBorder(BorderFactory.createLineBorder(Color.black));
panelP.add(panelP0);
JPanel panelP1 = new JPanel(new FlowLayout());//parametri
panelP1.setBackground(bluex);
//panelP1.setLayout(new BoxLayout(panelP1, BoxLayout.Y_AXIS));
panelP1.setBorder(BorderFactory.createLineBorder(Color.black));
panelP.add(panelP1);
JPanel panelP2=new JPanel(new FlowLayout());
panelP2.setBackground(bluex);
panelP2.setBorder(BorderFactory.createLineBorder(Color.black));
panelP.add(panelP2);
//**************** panel 1 : PARAMETRI
JTextArea dico3 = new JTextArea(" Parametri di miscelazione",10,40);
dico3.setEditable(false);
dico3.setBorder(BorderFactory.createLineBorder(Color.black));//bordo
JRadioButton primo = new JRadioButton("First frame");
primo.setActionCommand("first");
primo.setSelected(true);
primo.setBackground(bluex);
JRadioButton secondo = new JRadioButton("Last frame");
secondo.setActionCommand("last");
secondo.setBackground(bluex);
JRadioButton terzo = new JRadioButton("Average");
terzo.setActionCommand("average");
terzo.setBackground(bluex);
JRadioButton quarto = new JRadioButton("Median");
quarto.setActionCommand("median");
quarto.setBackground(bluex);
JRadioButton quinto = new JRadioButton("Feathering");
quinto.setActionCommand("feathering");
quinto.setBackground(bluex);
final ButtonGroup group = new ButtonGroup(); //raggruppo x fare esclusione
group.add(primo);
group.add(secondo);
group.add(terzo);
group.add(quarto);
group.add(quinto);
// ******** panel 0 : avvia
JTextArea dico = new JTextArea(" Se si vuole avviare la mosaicatura premere 'Avvia'" newline" in tal caso se non sono stati settati parametri verranno utilizzati quelli di default",10,40);
dico.setEditable(false);
dico.setBorder(BorderFactory.createLineBorder(Color.black));//bordo
JButton ok1 = new JButton("Avvia");
ok1.setBackground(bluex);
ok1.addActionListener(new ActionListener(){ //quando premo ok ...
public void actionPerformed(ActionEvent e){
String command = group.getSelection().getActionCommand();
statusInfo.append(" Parametri di mosaicatura, miscelazione: "+command + newline);
frameP.setVisible(false); // SQUALLIDO! esci meglio!
barraP();
mettiMosaico();
// ******** panel 2 : IMG RIFERIMENTO
dico2 = new JTextArea(" Per impostare l'immagine di riferimento" newline " premere 'Imposta' e selezionare l'immagine "+newline,10,40);
dico2.setEditable(false);
dico2.setBorder(BorderFactory.createLineBorder(Color.black));//bordo
JButton imposta = new JButton("Imposta");
imposta.setBackground(bluex);
imposta.addActionListener(new ActionListener(){ //quando premo ok ...
public void actionPerformed(ActionEvent e){
String command = group.getSelection().getActionCommand();
imgRif();
panelP1.add(dico3);
panelP1.add(primo);
panelP1.add(secondo);
panelP1.add(terzo);
panelP1.add(quarto);
panelP1.add(quinto);
panelP0.add(dico);
panelP0.add(ok1);
panelP2.add(dico2);
panelP2.add(imposta);
primo.addActionListener(this);
secondo.addActionListener(this);
JTabbedPane tabbedPane = new JTabbedPane(); //a schedario
tabbedPane.setBackground(bluex);
tabbedPane.addTab("Avvia Mosaicatura", null, panelP0, null);
tabbedPane.addTab("Parametri", null, panelP1, null);
tabbedPane.addTab("Img Riferimento", null, panelP2, null);
tabbedPane.setSelectedIndex(0);
panelP.add(tabbedPane);
frameP.pack();
frameP.setVisible(true);
// ========================================================================== super risoluzione
if(source == superR){
System.out.println("Super-risoluzione");
final JFrame frameP = new JFrame("Parametri di Super-risoluzione");
frameP.setSize(800,800);
frameP.setBackground(bluex);
JPanel panelP = new JPanel(new GridLayout(1,0));
panelP.setBackground(bluex);
panelP.setBorder(BorderFactory.createLineBorder(Color.black));
panelP.setPreferredSize(new Dimension(500,500));
frameP.getContentPane().add(panelP);
JPanel panelP0 = new JPanel(new FlowLayout()); //avvia
panelP0.setBackground(bluex);
panelP0.setBorder(BorderFactory.createLineBorder(Color.black));
panelP.add(panelP0);
JPanel panelP1 = new JPanel(new FlowLayout());//parametri
panelP1.setBackground(bluex);
panelP1.setBorder(BorderFactory.createLineBorder(Color.black));
panelP.add(panelP1);
//**************** panel 1 : PARAMETRI
JTextArea dico3 = new JTextArea(" Parametri di super-risoluzione",10,40);
dico3.setEditable(false);
dico3.setBorder(BorderFactory.createLineBorder(Color.black));//bordo
JRadioButton primo = new JRadioButton("Nearest");
primo.setActionCommand("nearest");
primo.setSelected(true);
primo.setBackground(bluex);
JRadioButton secondo = new JRadioButton("Weighted");
secondo.setActionCommand("weighted");
secondo.setBackground(bluex);
final ButtonGroup group = new ButtonGroup(); //raggruppo x fare esclusione
group.add(primo);
group.add(secondo);
// ******** panel 0 : avvia
JTextArea dico = new JTextArea(" Se si vuole avviare la super-risoluzione premere 'Avvia'" newline" in tal caso se non sono stati settati parametri verranno utilizzati quelli di default",10,40);
dico.setEditable(false);
dico.setBorder(BorderFactory.createLineBorder(Color.black));//bordo
JButton ok1 = new JButton("Avvia");
ok1.setBackground(bluex);
ok1.addActionListener(new ActionListener(){ //quando premo ok ...
public void actionPerformed(ActionEvent e){
String command = group.getSelection().getActionCommand();
statusInfo.append(" Parametri super-risoluzione: "+command + newline);
frameP.setVisible(false); // SQUALLIDO! esci meglio!
barraP();
panelP1.add(dico3);
panelP1.add(primo);
panelP1.add(secondo);
panelP0.add(dico);
panelP0.add(ok1);
primo.addActionListener(this);
secondo.addActionListener(this);
JTabbedPane tabbedPane = new JTabbedPane(); //a schedario
tabbedPane.setBackground(bluex);
tabbedPane.addTab(" Avvia super-risoluzione", null, panelP0, null);
tabbedPane.addTab(" Parametri", null, panelP1, null);
tabbedPane.setSelectedIndex(0);
panelP.add(tabbedPane);
frameP.pack();
frameP.setVisible(true);
mettiMosaico();
// ===================================================== Mouse Event
public void mousePressed(MouseEvent e) {
mousex = e.getX(); // Save the x coord of the click
mousey = e.getY(); // Save the y coord of the click
for (int m=0; m<Nimg; m++){
Point p = images[m].getLocation(); //posizione img[m] in panel
px = (int)p.getX();
py = (int)p.getY();
if (mousex >= px && mousex <= (px+images[muovi].getWidth())
&& mousey >= py && mousey <= (py+images[muovi].getHeight())) {//se mouse dentro img
_canDrag = true;
_dragFromX = mousex-px; // how far from left
_dragFromY = mousey-py; // how far from top
muovi = m; //setto immagine da muovere!!!!
if (rifno==0){panelpane.moveToFront(images[muovi]);}//davanti img ke muovo
//se =1 nn mi muove img
}//chiudo FOR
if (rifno==1){
statusInfo.append(" Immagine di riferimento: "+ muovi + newline);
frameP.setVisible(true);
dico2.append(" Immagine di riferimento impostata :"+muovi + newline);
rifno=0;
public void mouseDragged(MouseEvent e) {
if (_canDrag) { // True only if button was pressed inside ball.
//--- Ball pos from mouse and original click displacement
int ballX = e.getX() - dragFromX;
int ballY = e.getY() - dragFromY;
images[muovi].setLocation(_ballX,_ballY);
//--- Don't move the ball off the screen sides
ballX = Math.max(ballX, 0);
ballX = Math.min(ballX, panelpane.getWidth() - images[muovi].getWidth());
//--- Don't move the ball off top or bottom
ballY = Math.max(ballY, 0);
ballY = Math.min(ballY, panelpane.getHeight() - images[muovi].getHeight());
Point p = images[muovi].getLocationOnScreen();
int px = (int)p.getX();
int py = (int)p.getY();
//panelpane.repaint(); // Repaint because position changed.
public void mouseExited(MouseEvent e) {
_canDrag = false;
}//end mouseExited
public void mouseEntered (MouseEvent e) {} // ignore these events
public void mouseClicked (MouseEvent e) {
public void mouseReleased(MouseEvent e) {
//e.consume();
} // ignore these events
public void mouseMoved(MouseEvent e) {}
}// chiude classeplease reuse the threads you've already started on this topic
http://forum.java.sun.com/thread.jspa?threadID=573384&tstart=50
and also, use the [url http://forum.java.sun.com/help.jspa?sec=formatting]formatting tags when posting code.
keep in mind, this is an awful lot of code, and few will have the time to read through all of it, so if at all possible, make a smaller example case for your problem when you can so that we don't have to try to sort through hundreds of lines of code to find what you want to do.
Maybe you are looking for
-
I can't use Yahoo messenger (it doesn't open the dialogue window), but in other PCs with older versions of Firefox I don't have problems As stated earlier even though when I have an incoming message I hear the "Beep" Firefox does not open the dialogu
-
WPF DataGridComboboxColumn selction fails if Drag&Drop is used
I've got a Usercontrol with TabControl including Datagrid for each tabItem. The Datagrid has 3 Columns, one as a combobox column. Now I've implemented some Drag&Drop function for moving rows using PreviewMouseLeftButtonDown and Drop event. With that
-
Hi All, I wanted to know if there is a option of tracing as to what the user is trying to do like in ABAP stack we have st01 similarly can we do tracing in JAVA stack i wanted to trace something in enterpirse portal like whether the request is reachi
-
Brother DCP 7020 Scanner Driver Problem
Hi, Hadn't used the scanner on my Brother DCP 7020 in 6 months and couldn't remember how to do scans. Called Brother Tech Support and they reminded me that the icon for scanning is in the Menu Bar at top of screen. For reasons not clear to me at the
-
Anybody have issues with the iTunes 7.1 update and Logic?
Scenerio: Working happily in Logic Pro. Software Update appears with available updates to iTunes and Quicktime. I needed a break from editing, so I accpeted the update. Immediately relaunched Logic Pro and at the Updating the Tree stage my machine fr