I am new for Java. I have searched how to set the size of the JTextField and JButton, but I still cannot make it work. Hope someone tell me how to solve it. I declare the height and width, but the component seems doesn't take it. The JTextField and JButton with red & yellow background should be same height. Also the JTextField width is very long.
There is my code:
package MyPackage;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.*;
import java.io.*;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.*;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.ComponentOrientation;
import javax.swing.JTextField;
public class MainForm extends JFrame implements ActionListener {
private PDFNotesBean PDFNotesBean = null;
private JMenuItem cascade = new JMenuItem("Cascade");
private int numInterFrame=0;
private JDesktopPane desktop=null;
private ArrayList<File> fileList=new ArrayList<File>();
private static int categoryButtonWidth= 40;
private static int categoryTextFieldWidth=60;
private static int categoryHight=40;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run()
{
new MainForm();
}
});
}
public MainForm(){
super("Example");
//it is equal to this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// Name the JMenu & Add Items
JMenu menu = new JMenu("File");
menu.add(makeMenuItem("Open"));
menu.add(makeMenuItem("Save"));
menu.add(makeMenuItem("Quit"));
// Add JMenu bar
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
//menuBar.add(menuWindow);
setJMenuBar(menuBar);
this.setMinimumSize(new Dimension(400, 500));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
desktop = new JDesktopPane();
this.setLayout(new BorderLayout());
setCategoryPanel();
this.add(desktop, BorderLayout.CENTER);
setVisible(true);
}
private void setCategoryPanel(){
//set the color label category
JPanel panelCategory=new JPanel();
panelCategory.setLayout(new BoxLayout(panelCategory, BoxLayout.LINE_AXIS));
JButton btnCategory_1=new JButton("");
btnCategory_1.setPreferredSize(new Dimension ( categoryButtonWidth, categoryHight));
btnCategory_1.setBackground(Color.red);
btnCategory_1.addActionListener(this);
panelCategory.add(btnCategory_1);
JTextField txtCategory_1 = new JTextField();
txtCategory_1.setPreferredSize(new Dimension (categoryTextFieldWidth, categoryHight));
panelCategory.add(txtCategory_1);
JButton btnCategory_2=new JButton("");
btnCategory_2.setPreferredSize(new Dimension ( categoryButtonWidth, categoryHight));
btnCategory_2.setBackground(Color.YELLOW);
btnCategory_2.addActionListener(this);
panelCategory.add(btnCategory_2);
JTextField txtCategory_2 = new JTextField( );
txtCategory_1.setPreferredSize(new Dimension (categoryTextFieldWidth, categoryHight));
panelCategory.add(txtCategory_2);
this.add(panelCategory, BorderLayout.NORTH);
}
public void actionPerformed(ActionEvent e) {
// Menu item actions
String command = e.getActionCommand();
if (command.equals("Quit")) {
System.exit(0);
} else if (command.equals("Open")) {
// Open menu item action
JFileChooser fileChooser = new JFileChooser();
int returnVal = fileChooser.showOpenDialog(MainForm.this);
if (returnVal == fileChooser.APPROVE_OPTION) {
numInterFrame=numInterFrame+1;
File file = fileChooser.getSelectedFile();
fileList.add(file);
AddNote(file);
// Load file
} else if (returnVal == JFileChooser.CANCEL_OPTION ) {
// Do something else
}
}
else if (command.equals("Save")) {
// Save menu item action
System.out.println("Save menu item clicked");
}
}
private JMenuItem makeMenuItem(String name) {
JMenuItem m = new JMenuItem(name);
m.addActionListener(this);
return m;
}
private void AddNote(File file){
JInternalFrame internalFrame = new JInternalFrame("PDFAnnotation"
+ file.getName(), true, true, true, true);
internalFrame.setBounds(0, 0, 600, 100);
desktop.add(internalFrame);
PDFPanel p=new PDFPanel();
JPanel e =p.getJPanel(file);
internalFrame.add(e, BorderLayout.CENTER);
internalFrame.setVisible(true);
this.add(desktop, BorderLayout.CENTER);
//resize the internal frame as full screen
Dimension size = desktop.getSize();
int w = size.width ;
int h = size.height ;
int x=0;
int y=0;
desktop.getDesktopManager().resizeFrame(internalFrame, x, y, w, h);
}
}
Don't use the setPreferredSize() method.
All Swing components will have a preferred size.
For a JTextField you can use:
JTextField textField = new JTextField(5);
to indication how many characters you want to display at one time.
For the JButton, the width is determined by the text you add to the button.
When you use a BoxLayout, the width of the components is increased to fill the available space.
Just use a FlowLayout (which is the default for a JPanel) and the components will be displayed at their preferred sizes.
Related
This is my button click event. i want to create combo boxes each time i click the button.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jButton1.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent evt){
List<JComboBox> listOfComboBoxes = new ArrayList<JComboBox>();
for(int i=1;i<4;i++){
int x = 28;
int y = 100;
int a = 145;
int b = 28;
listOfComboBoxes.get(i);
listOfComboBoxes.get(i).addItem("--Select the Teacher--");
listOfComboBoxes.get(i).setLayout(null);
listOfComboBoxes.get(i).setLocation(x,y);
add(listOfComboBoxes.get(i)).setSize(a,b);
x=x+30;
a=a+40;
i++;
}
}
});
You are coping with two issues: one is adding combos (say to a JPanel), and the second is laying out those combos.
Let's break it into two, and understand the adding mechanism first :
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MakeCombos extends JFrame {
private static final int Number_OF_COMBOS = 4;
private JButton jButton1;
List<JComboBox> listOfComboBoxes;
private JPanel panel;
int counter = 0;
MakeCombos(){
super("Test frame");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(400,300));
setLocationRelativeTo(null);
getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
//create a panel
panel = new JPanel();
getContentPane().add(panel);
//add button to it
jButton1 = new JButton("Click Me");
//add action listener to the panel
jButton1.addActionListener((ActionEvent e)-> {
jButton1ActionPerformed();
});
panel.add(jButton1, BorderLayout.CENTER);
validate();
pack();
setVisible(true);
listOfComboBoxes = makeCombos();
}
/**
*#return
*/
private List<JComboBox> makeCombos() {
List combos = new ArrayList<JComboBox>();
for(int i = 0; i < Number_OF_COMBOS; i++) {
JComboBox<String> combo = new JComboBox<>(new String[] {});
combos.add(combo);
}
return combos;
}
private void jButton1ActionPerformed() {
if(counter >= listOfComboBoxes.size()) {
return;
}
listOfComboBoxes.get(counter);
listOfComboBoxes.get(counter).addItem("--Select the Teacher--");
getContentPane().add(listOfComboBoxes.get(counter)) ;//.setSize(a,b);
counter++;
pack();
}
public static void main(String[] args) {
new MakeCombos();
}
}
Run it, and if it is not clear, don't hesitate to ask.
Now let's take it one step further and do the layout as well.
Please see comments:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MakeCombos extends JFrame {
private static final int Number_OF_COMBOS = 4;
private List<JComboBox<String>> listOfComboBoxes;
private JPanel combosPanel;
private int xPosition = 28;
private int yPosition = 100;
private int width = 145;
private int height = 28;
private int counter = 0;
MakeCombos(){
//make width frame for testing
super("Test frame");
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(500,400));
setLocationRelativeTo(null);
//set layout manager to the frame
getContentPane().setLayout(new BorderLayout());
//add panel + button to the frame
JPanel buttonPanel = new JPanel();
getContentPane().add(buttonPanel, BorderLayout.NORTH); //add the panel to the frame
//add button to the button panel
JButton jButton1 = new JButton("Click Me");
//add action listener to the button
jButton1.addActionListener((ActionEvent e)-> {
jButton1ActionPerformed();
});
buttonPanel.add(jButton1, BorderLayout.CENTER);
//--add width panel for the combos
combosPanel = new JPanel();
//set layout manager to null so you can layout each combo
//consider using a layout manager instead
combosPanel.setLayout(null);
getContentPane().add(combosPanel, BorderLayout.CENTER); //add the panel to the frame
validate();
pack();
setVisible(true);
//make the combos and add them to width list
listOfComboBoxes = makeCombos();
}
/**
*
*/
private List<JComboBox<String>> makeCombos() {
List<JComboBox<String>> combos = new ArrayList<JComboBox<String>> ();
for(int i = 0; i < Number_OF_COMBOS; i++) {
JComboBox<String> combo = new JComboBox<>(new String[] {});
combos.add(combo);
}
return combos;
}
private void jButton1ActionPerformed() {
if(counter >= listOfComboBoxes.size()) {
return;
}
//////////////////////////////////////////////////////////////////////////////
//////////////// note : all this block could be moved to MakeCombos() ////////
// (adding content and setting bounds could have been done when creating ////
//the combo
//add content to the combo
listOfComboBoxes.get(counter).addItem("--Select the Teacher--");
//set layout bounds to each combo
listOfComboBoxes.get(counter).setBounds(xPosition, yPosition, width, height);
//increment position
xPosition=xPosition+30;
yPosition=yPosition+40;
////////////////////////////////////////////////////////////////////////////
/////////////////////// end of move-to-makeCombos() block //////////////////
////////////////////////////////////////////////////////////////////////////
//add the combo to the combos panel
combosPanel.add(listOfComboBoxes.get(counter)) ;
//increment position and counter
counter++;
repaint();
pack();
}
public static void main(String[] args) {
new MakeCombos();
}
}
I am new for Java. I need to have MDI in my project. When the user clicks ‘Open’ in menu bar, the internal frame is added and should be full screen on top.
I still cannot make it full screen on top when it is open. Also in my code, if I remove the following line from “AddNote” method, I cannot see the internal frame. In logic the JDesktop should add when the form is open.
JDesktopPane desktop = new JDesktopPane();
There is my code:
package MyPackage;
import java.awt.BorderLayout;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.*;
import java.io.*;
import java.awt.Dimension;
import java.awt.FlowLayout;
public class MainForm extends JFrame implements ActionListener {
private JMenuItem cascade = new JMenuItem("Cascade");
private int numInterFrame=0;
private JDesktopPane desktop=null;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run()
{
new MainForm();
}
});
}
public MainForm(){
super("Example");
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
// Name the JMenu & Add Items
JMenu menu = new JMenu("File");
menu.add(makeMenuItem("Open"));
menu.add(makeMenuItem("Save"));
menu.add(makeMenuItem("Quit"));
// Add JMenu bar
JMenuBar menuBar = new JMenuBar();
menuBar.add(menu);
//menuBar.add(menuWindow);
setJMenuBar(menuBar);
this.setMinimumSize(new Dimension(400, 500));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new BorderLayout());
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
JDesktopPane desktop = new JDesktopPane();
this.add(desktop, BorderLayout.CENTER);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// Menu item actions
String command = e.getActionCommand();
if (command.equals("Quit")) {
System.exit(0);
} else if (command.equals("Open")) {
// Open menu item action
JFileChooser fileChooser = new JFileChooser();
int returnVal = fileChooser.showOpenDialog(MainForm.this);
if (returnVal == fileChooser.APPROVE_OPTION) {
numInterFrame=numInterFrame+1;
File file = fileChooser.getSelectedFile();
AddNote(numInterFrame);
// Load file
} else if (returnVal == JFileChooser.CANCEL_OPTION ) {
// Do something else
}
}
else if (command.equals("Save")) {
// Save menu item action
System.out.println("Save menu item clicked");
}
}
private JMenuItem makeMenuItem(String name) {
JMenuItem m = new JMenuItem(name);
m.addActionListener(this);
return m;
}
private void AddNote(int index){
JDesktopPane desktop = new JDesktopPane();
JInternalFrame internalFrame = new JInternalFrame("PDFAnnotation" + index, true, true, true, true);
internalFrame.setBounds(0, 0, 600, 100);
desktop.add(internalFrame);
PDFPanel p=new PDFPanel();
JPanel e =p.getJPanel();
internalFrame.add(e, BorderLayout.CENTER);
internalFrame.setVisible(true);
this.add(desktop, BorderLayout.CENTER);
/* Dimension size = desktop.getSize();
int w = size.width ;
int h = size.height ;
int x=0;
int y=0;
desktop.getDesktopManager().resizeFrame(internalFrame, x, y, w, h);*/
}
}
There are a number problems, which are compounded based on the fact that you are shadowing the main desktop variable...
You declare an instance field....
private JDesktopPane desktop = null;
But in your constructor, you declare it again...
JDesktopPane desktop = new JDesktopPane();
This means that the instance field remains null. Instead, in you constructor, you should be using the instance field, for example...
desktop = new JDesktopPane();
This means that in your AddNote method, you can get rid of the creation of yet another JDesktopPane...
//JDesktopPane desktop = new JDesktopPane();
JInternalFrame internalFrame = new JInternalFrame("PDFAnnotation" + index, true, true, true, true);
internalFrame.setBounds(0, 0, 600, 100);
desktop.add(internalFrame);
PDFPanel p = new PDFPanel();
JPanel e = p.getJPanel();
internalFrame.add(e, BorderLayout.CENTER);
internalFrame.setVisible(true);
//this.add(desktop, BorderLayout.CENTER);
Also, because you're using...
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
You won't need
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
You should also have a read of Code Conventions for the Java Programming Language
I am displaying an image on the screen now I want to press Jbutton and display the next image in that directory. And other button(previous) should display the previous image. All of it in a loop. So that first image is displayed after the last image of the directory. This is my code so far:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import net.miginfocom.swing.MigLayout;
class ImageFilter extends FileFilter {
#Override
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
String name = f.getAbsolutePath();
if (name.matches(".*((.jpg)|(.gif)|(.png))"))
return true;
else
return false;
}
#Override
public String getDescription() {
return "Image Files(*.jpg, *.gif, *.png)";
}
}
#SuppressWarnings("serial")
class bottompanel extends JPanel {
JButton prev, next;
bottompanel() {
this.setLayout(new MigLayout("debug", "45%[center][center]", ""));
prev = new JButton("Previous");
next = new JButton("Next");
next.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
}
});
this.add(prev, " w 100!");
this.add(next, "w 100!");
}
}
#SuppressWarnings("serial")
class imgpanel extends JPanel {
imgpanel(JLabel image) {
this.setLayout(new MigLayout("debug", "", ""));
this.add(image, "push,align center");
}
}
#SuppressWarnings("serial")
class DispImg extends JFrame {
JMenuBar jmenubar;
JMenu jmenu;
JMenuItem jopen, jexit;
JLabel image;
BufferedImage img, dimg;
DispImg() {
// initializing the Frame
this.setTitle("Display Test");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setExtendedState(JFrame.MAXIMIZED_BOTH);
this.setLayout(new MigLayout("debug", "[fill,grow]", "[]push[]"));
this.setLocationByPlatform(true);
this.setMinimumSize(new Dimension(800, 600));
this.setVisible(true);
this.setResizable(false);
// create label
image = new JLabel(" ");
//add label to panel
this.add(new imgpanel(image), "wrap");
//add buttons to bottompanel
this.add(new bottompanel(), "gaptop 10");
// Making Menubar
jmenubar = new JMenuBar();
jmenu = new JMenu("File");
jopen = new JMenuItem("Open");
jopen.setMnemonic(KeyEvent.VK_O);
KeyStroke key1 = KeyStroke.getKeyStroke(KeyEvent.VK_O, Event.CTRL_MASK);
jopen.setAccelerator(key1);
jopen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser fc = new JFileChooser();
fc.setFileFilter(new ImageFilter());
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
img = ImageIO.read(file);
float width = img.getWidth();
float height = img.getHeight();
if (img.getHeight() > 500 && (width / height) > 1) {
Image thumb = img.getScaledInstance(-1, 620,
Image.SCALE_SMOOTH);
image.setIcon(new ImageIcon(thumb));
} else if (img.getHeight() > 500
&& (width / height) <= 1) {
Image thumb = img.getScaledInstance(460, -1,
Image.SCALE_SMOOTH);
image.setIcon(new ImageIcon(thumb));
} else {
image.setIcon(new ImageIcon(img));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
jexit = new JMenuItem("Exit");
jexit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
jmenu.add(jopen);
jmenu.addSeparator();
jmenu.add(jexit);
jmenubar.add(jmenu);
this.setJMenuBar(jmenubar);
}
public static void main(String s[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new DispImg();
}
});
}
}
when i added actionListener() on next button nothing happened and the new image is not displayed
You don't have any code in the actionListener, so I'm not sure what you expect to happen.
Don't know how to fetch the next image from the directory
You would probably use the JFileChooser to select the directory (and maybe initial image to display).
Once you have the directory then you could use the File.listFiles(...) method to get a list of all the image files in the directory. Then your Next/Previous button would add/subtract one to access the next/previous File in the array.
I am trying to implement a menu based graph - wherein i will represent a vertex by a circle and each circle will have an index provided by the user.The user has to go to File menu and click on Addvertex to create a new node with an index.The Problem though is - The circle is drawn only once - any subsequent clicks to addVertex does not result in drawing of a circle -Can't understand Why...
Here is my code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.*;
import java.util.*;
public class FileChoose extends JFrame {
public FileChoose() {
JMenuBar l=new JMenuBar();
JMenu file=new JMenu("File");
JMenuItem open=new JMenuItem("Addvertex");
open.addActionListener(new Drawer());
JMenuItem close=new JMenuItem("Exit");
close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
JMenu tools=new JMenu("Tools");
file.add(open);
file.add(close);
this.setJMenuBar(l);
l.add(tools);
l.add(file);
this.setSize(new Dimension(200, 200));
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
}
void HelloHere(String p) {
Draw d = new Draw(p);
this.add(d);
setExtendedState(MAXIMIZED_BOTH);
}
class Drawer extends JFrame implements ActionListener {
Integer index;
public void actionPerformed(ActionEvent e) {
JPanel pn = new JPanel();
JTextField jt = new JTextField(5);
JTextField jt1 = new JTextField(5);
pn.add(jt);
pn.add(jt1);
int result=JOptionPane.showConfirmDialog(null, pn, "Enter the values", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
index = Integer.parseInt(jt.getText());
System.out.println(jt1.getText());
}
this.setVisible(true);
this.setSize(500, 500);
this.setLocationRelativeTo(null);
HelloHere(index.toString());
}
}
public static void main(String [] args) {
FileChoose f = new FileChoose();
f.setVisible(true);
}
}
class Draw extends JPanel {
String inp;
public Draw(String gn) {
inp = gn;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Random r = new Random();
int x = r.nextInt(100);
g2.drawOval(x, x * 2, 100, 100);
g2.drawString(inp, x + (x / 2), x + (x / 2));
}
}
Some pointers:
Use EDT for creation and manipulation of Swing Components.
Dont extend JFrame class unnecessarily.
Use anonymous Listeners where possible/allowed
Make sure JFrame#setVisible(..) is the last call on JFrame instance specifically pointing here:
this.setVisible(true);
this.setSize(500, 500);
this.setLocationRelativeTo(null);
HelloHere(index.toString());
Call pack() on JFrame instance rather than setSize(..)
Do not use multiple JFrames see: The Use of Multiple JFrames: Good or Bad Practice?
The problem you are having is here:
Draw d = new Draw(p);
this.add(d);
You are creating a new instance of Draw JPanel each time and then overwriting the last JPanel added with the new one (this is default the behavior of BorderLayout). To solve this read below 2 points:
Call revalidate() and repaint() on instance after adding components to show newly added components.
Use an appropriate LayoutManager
As I am not sure of you expected results I have done as much fixing of the code as I could hope it helps:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
public class FileChoose {
JFrame frame;
public FileChoose() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar l = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem open = new JMenuItem("Addvertex");
open.addActionListener(new ActionListener() {
Integer index;
#Override
public void actionPerformed(ActionEvent e) {
JPanel pn = new JPanel();
JTextField jt = new JTextField(5);
JTextField jt1 = new JTextField(5);
pn.add(jt);
pn.add(jt1);
int result = JOptionPane.showConfirmDialog(null, pn, "Enter the values", JOptionPane.OK_CANCEL_OPTION);
if (result == JOptionPane.OK_OPTION) {
index = Integer.parseInt(jt.getText());
System.out.println(jt1.getText());
}
HelloHere(index.toString());
}
});
JMenuItem close = new JMenuItem("Exit");
close.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
JMenu tools = new JMenu("Tools");
file.add(open);
file.add(close);
frame.setJMenuBar(l);
l.add(tools);
l.add(file);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
void HelloHere(String p) {
Draw d = new Draw(p);
frame.add(d);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.revalidate();
frame.repaint();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
FileChoose f = new FileChoose();
}
});
}
}
class Draw extends JPanel {
String inp;
public Draw(String gn) {
inp = gn;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Random r = new Random();
int x = r.nextInt(100);
g2.drawOval(x, x * 2, 100, 100);
g2.drawString(inp, x + (x / 2), x + (x / 2));
}
}
UPDATE:
Declare this globally in your Draw class: Random r=new Random(); as if you iniate a new Random instance each time you call paintComponent() the distributions will not be significant/random enough
Every time the user creates a new node you create a new JPanel that is added to the JFrame of your application. In the absence of a specific layout it uses a BorderLayout. BorderLayout does not allow for more than one component to be added at each location. Your other calls to add are probably ignored.
Users of my software need to be able to click on different tabs to see different types of data representations. However, the code I am including below does not show the requested data panel when the user clicks on a tab.
You can re-create the problem easily by running the code below, and then following these steps in the GUI which the code will produce:
1.) Select "New" from the file menu
2.) Click on "AnotherTab" in the internal frame which will appear
Depending on which line of code you comment out below, the tab will either just show a blank panel or will show a tiny red square in the middle of the top of the panel.
The lines of code that you can toggle/comment-out to recreate this problem are:
GraphPanel myGP = new GraphPanel();
//GraphPanel myGP = new GraphPanel(width,height);
These lines of code are in GraphGUI.java below.
Can anyone show me how to fix the code below so that myGP gets displayed at the full size of the panel containing it?
Here are the three java files required to recreate this problem:
ParentFrame.java
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTabbedPane;
import javax.swing.KeyStroke;
public class ParentFrame extends JFrame implements ActionListener{
private static final long serialVersionUID = 1L;
JLayeredPane desktop;
JInternalFrame internalFrame;
public ParentFrame() {
super("Parent Frame");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setPreferredSize(new Dimension(800, 400));
Panel p = new Panel();
this.add(p, BorderLayout.SOUTH);
desktop = new JDesktopPane();
setJMenuBar(createMenuBar());
this.add(desktop, BorderLayout.CENTER);
this.pack();
this.setSize(new Dimension(800, 600));
this.setLocationRelativeTo(null);
}
protected JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
//Set up the File menu.
JMenu FileMenu = new JMenu("File");
FileMenu.setMnemonic(KeyEvent.VK_F);
menuBar.add(FileMenu);
//Set up the first menu item.
JMenuItem menuItem = new JMenuItem("New");
menuItem.setMnemonic(KeyEvent.VK_N);
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.ALT_MASK));
menuItem.setActionCommand("new");
menuItem.addActionListener(new OpenListener());
FileMenu.add(menuItem);
//Set up the second menu item.
menuItem = new JMenuItem("Quit");
menuItem.setMnemonic(KeyEvent.VK_Q);
menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.ALT_MASK));
menuItem.setActionCommand("quit");
menuItem.addActionListener(this);
FileMenu.add(menuItem);
return menuBar;
}
class OpenListener implements ActionListener {
private static final int DELTA = 40;
private int offset = DELTA;
public void actionPerformed(ActionEvent e) {
// create internal frame
int ifWidth = 600;
int ifHeight = 300;
internalFrame = new JInternalFrame("Internal Frame", true, true, true, true);
internalFrame.setLocation(offset, offset);
offset += DELTA;
// create jtabbed pane
JTabbedPane jtp = createTabbedPane();
internalFrame.add(jtp);
desktop.add(internalFrame);
internalFrame.pack();
internalFrame.setSize(new Dimension(ifWidth,ifHeight));
internalFrame.setVisible(true);
}
}
private JTabbedPane createTabbedPane() {
JTabbedPane jtp = new JTabbedPane();
jtp.setMinimumSize(new Dimension(600,300));
createTab(jtp, "One Tab");
createTab(jtp, "AnotherTab");
createTab(jtp, "Tab #3");
return jtp;
}
private void createTab(JTabbedPane jtp, String s) {
if(s=="AnotherTab"){
jtp.getHeight();
jtp.getWidth();
GraphGUI myGraphGUI = new GraphGUI(jtp.getHeight(),jtp.getWidth());
jtp.add(s, myGraphGUI);
}
else{jtp.add(s, new JLabel("TabbedPane " + s, JLabel.CENTER));}
}
public static void main(String args[]) {
ParentFrame myParentFrame = new ParentFrame();
myParentFrame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {if ("quit".equals(e.getActionCommand())){System.exit(0);}}
}
GraphGUI.java: This is the one where you can toggle comments to re-create the problem.
import javax.swing.*;
class GraphGUI extends JPanel{
GraphGUI(int height,int width) {
//REPRODUCE ERROR BY COMMENTING OUT EITHER ONE OF NEXT TWO LINES:
GraphPanel myGP = new GraphPanel();
// GraphPanel myGP = new GraphPanel(width,height);
this.add(myGP);
this.setVisible(true);// Display the panel.
}
}
GraphPanel.java:
import java.awt.*;
import javax.swing.*;
class GraphPanel extends JPanel {
Insets ins; // holds the panel's insets
double[] plotData;
double xScale;
GraphPanel(int w, int h) {
setOpaque(true);// Ensure that panel is opaque.
setPreferredSize(new Dimension(w, h));// Set preferred dimension as specfied.
setMinimumSize(new Dimension(w, h));// Set preferred dimension as specfied.
setMaximumSize(new Dimension(w, h));// Set preferred dimension as specfied.
}
GraphPanel() {
setOpaque(true);// Ensure that panel is opaque.
}
protected void paintComponent(Graphics g){// Override paintComponent() method.
super.paintComponent(g);// Always call superclass method first.
int height = getHeight();// Get height of component.
int width = getWidth();// Get width of component.
System.out.println("height, width are: "+height+" , "+width);
ins = getInsets();// Get the insets.
// Get dimensions of text
Graphics2D g2d = (Graphics2D)g;
FontMetrics fontMetrics = g2d.getFontMetrics();
String xString = ("x-axis label");
int xStrWidth = fontMetrics.stringWidth(xString);
int xStrHeight = fontMetrics.getHeight();
String yString = "y-axis label";
int yStrWidth = fontMetrics.stringWidth(yString);
int yStrHeight = fontMetrics.getHeight();
String titleString ="Title of Graphic";
int titleStrWidth = fontMetrics.stringWidth(titleString);
int titleStrHeight = fontMetrics.getHeight();
//get margins
int leftMargin = ins.left;
//set parameters for inner rectangle
int hPad=10;
int vPad = 6;
int numYticks = 10;
int testLeftStartPlotWindow = ins.left+5+(3*yStrHeight);
int testInnerWidth = width-testLeftStartPlotWindow-ins.right-hPad;
int remainder = testInnerWidth%numYticks;
int leftStartPlotWindow = testLeftStartPlotWindow-remainder;
System.out.println("remainder is: "+remainder);
int blueWidth = testInnerWidth-remainder;
int blueTop = ins.bottom+(vPad/2)+titleStrHeight;
int bottomPad = (3*xStrHeight)-vPad;
int blueHeight = height-bottomPad-blueTop;
g.setColor(Color.red);
int redWidth = width-leftMargin-1;
//plot outer rectangle
g.drawRect(leftMargin, ins.bottom, redWidth, height-ins.bottom-1);
System.out.println("blueWidth is: "+blueWidth);
// fill inner rectangle
g.setColor(Color.white);
g.fillRect(leftStartPlotWindow, blueTop, blueWidth, blueHeight);
//write top label
g.setColor(Color.black);
g.drawString(titleString, (width/2)-(titleStrWidth/2), titleStrHeight);
//write x-axis label
g.setColor(Color.red);
g.drawString(xString, (width/2)-(xStrWidth/2), height-ins.bottom-vPad);
g2d.rotate(Math.toRadians(-90), 0, 0);//rotate text 90 degrees counter-clockwise
//write y-axis label
g.drawString(yString, -(height/2)-(yStrWidth/2), yStrHeight);
g2d.rotate(Math.toRadians(+90), 0, 0);//rotate text 90 degrees clockwise
// plot inner rectangle
g.setColor(Color.blue);
g.drawRect(leftStartPlotWindow, blueTop, blueWidth, blueHeight);
}
}
class GraphGUI extends JPanel {
.
.
GraphGUI(int height,int width) {
// components in a GridLayout are stretched to fit space available
setLayout(new GridLayout());