I'm making a grapher that draws a graph from a mathematical expression given by user .additionally the program has a slider and play button that user can choose a variable for the slider and its range so upon clicking the play button the slider will start from minimum range to maximum and the graph will be drawn.
for the timer I'm using the answer from a previous question.
for the grapher I'm using This code. (I'm working specifically on Plotter.java file)
The edited Plotter.java file with the playable slider(timer) code :
import java.util.*;
public class Plotter extends JFrame implements ActionListener
{
private JMenuBar menuBar = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenuItem openMenuItem = new JMenuItem("Open");
private JMenuItem saveMenuItem = new JMenuItem("Save");
private JMenuItem exitMenuItem = new JMenuItem("Exit");
private int value;
private JComboBox eqCombo = new JComboBox();
private JButton addButton, removeButton, clearButton ;
private Graph graph;
private JPanel userPanel , sliderPanel;
private JSlider slider_1 = new JSlider();
private JButton playButton = new JButton();
private JTextField textField = new JTextField();
private Timer timer ;
private ImageIcon playIcon = new ImageIcon(getClass().getResource("/images/play.png"));
private ImageIcon pauseIcon = new ImageIcon(getClass().getResource("/images/pause.png"));
public Plotter(double lowX, double highX, double frequency, String file) throws GraphArgumentsException, IOException
{
super("Plotter");
textField.setBounds(266, 11, 134, 28);
textField.setColumns(10);
createNewGraph(lowX, highX, frequency, file);
createLayout();
//createsliderpanel();
}
private void createLayout() throws GraphArgumentsException
{
Container c = getContentPane();
setSize(850,600);
getContentPane().setLayout(null);
c.add(graph);
c.add(userPanel);
JPanel down = new JPanel();
down.setBounds(0, 437, 650, 119);
getContentPane().add(down);
down.setLayout(null);
slider_1.setValue(0);
slider_1.setMajorTickSpacing(5);
slider_1.setMinorTickSpacing(1);
slider_1.setPaintLabels(true);
slider_1.setPaintTicks(true);
slider_1.setBounds(145, 51, 467, 42);
down.add(slider_1);
playButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
playButton.setBounds(16, 51, 117, 29);
playButton.setIcon(playIcon);
down.add(playButton);
down.add(textField);
JPanel panel_1 = new JPanel();
panel_1.setBounds(649, 39, 201, 517);
getContentPane().add(panel_1);
panel_1.setLayout(new BorderLayout(0, 0));
// c.add(sliderPanel , BorderLayout.SOUTH);
createMenuBar();
}
/**
* Creates a new Graph instance and adds equations from file into Graph
* #param eqFile file where equations are stored
* #throws IOException
*/
private void createNewGraph(double minX, double maxX, double freq, String eqFile) throws GraphArgumentsException, IOException
{
Equation[] eq = null;
graph = new Graph(minX, maxX, freq);
graph.setBounds(0, 39, 650, 396);
eq = readEquationsFromFile(eqFile);
if (eq != null)
addEquation(eq);
graph.setBackground(Color.WHITE);
userPanel = createUserPanel(eq);
}
private void createMenuBar()
{
menuBar.add(fileMenu);
fileMenu.add(openMenuItem);
fileMenu.add(saveMenuItem);
fileMenu.addSeparator();
fileMenu.add(exitMenuItem);
openMenuItem.addActionListener(this);
saveMenuItem.addActionListener(this);
exitMenuItem.addActionListener(this);
setJMenuBar(menuBar);
}
/**
* Create user panel at top of the GUI for adding and editing functions
* #param eq equation list to add into the combo box
* #return panel containing buttons and an editable combo box
*/
private JPanel createUserPanel(Equation[] eq)
{
JPanel up = new JPanel(new FlowLayout(FlowLayout.LEFT));
up.setBounds(0, 0, 844, 39);
eqCombo.setEditable(true);
if (eq != null)
{
//Add all equations into the combo box
for (int i = 0; i < eq.length; i++)
eqCombo.addItem(eq[i].getPrefix());
}
addButton = new JButton("Add");
removeButton = new JButton("Remove");
clearButton = new JButton("Clear");
addButton.addActionListener(this);
removeButton.addActionListener(this);
clearButton.addActionListener(this);
up.add(eqCombo);
up.add(addButton);
up.add(removeButton);
up.add(clearButton);
return up;
}
// slider panel
/*private JPanel createsliderpanel()
{
JPanel down = new JPanel(new FlowLayout(FlowLayout.LEFT));
playbutton = new JButton("Play");
slider = new JSlider();
field = new JTextField();
down.add(playbutton);
down.add(slider);
down.add(field);
return down;
}*/
/**
* Check action lister for button and menu events
*/
public void actionPerformed(ActionEvent e)
{
timer = new Timer(500, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int value = slider_1.getValue() + 1;
if (value >= slider_1.getMaximum()) {
stopTheClock();
} else {
slider_1.setValue(value);
}
}
});
slider_1.addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
textField.setText(Integer.toString(slider_1.getValue()));
}
});
slider_1.setValue(0);
playButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (timer.isRunning()) {
stopTheClock();
} else {
startTheClock();
}
}
});
if (e.getSource() == addButton)
addEquation((String)eqCombo.getSelectedItem());
else if (e.getSource() == removeButton)
removeEquation(eqCombo.getSelectedIndex());
else if (e.getSource() == saveMenuItem)
saveEquationList();
else if (e.getSource() == openMenuItem)
loadEquations();
else if (e.getSource() == clearButton)
clearEquations();
else if (e.getSource() == exitMenuItem)
System.exit(0);
}
/**
* Save equations to file
*
*/
private void saveEquationList()
{
try
{
PrintWriter out = new PrintWriter(new FileWriter("myeq.txt"));
for (int i = 0; i < eqCombo.getItemCount(); i++)
out.println(eqCombo.getItemAt(i));
out.close();
}
catch (IOException e)
{
System.out.println(e);
}
}
private void clearEquations()
{
graph.removeAllEquations();
eqCombo.removeAllItems();
}
/**
* Load equations from file into graph
*
*/
private void loadEquations()
{
String file=null;
JFileChooser fc = new JFileChooser();
fc.showOpenDialog(null);
if (fc.getSelectedFile() != null)
{
file = fc.getSelectedFile().getPath();
try
{
Equation[] eq = readEquationsFromFile(file);
if (eq != null)
{
clearEquations();
addEquation(eq);
//Restock combo box with new equations
for (int i = 0; i < eq.length; i++)
eqCombo.addItem(eq[i].getPrefix());
}
}
catch (IOException e)
{
JOptionPane.showMessageDialog(null, "ERR4: Unable to read or access file", "alert", JOptionPane.ERROR_MESSAGE);
}
}
}
/**
* Add an equation to the Graph
* #param eq equation
*/
private void addEquation(String eq)
{
try
{
if (eq != null && !eq.equals(""))
{
Equation equation = new Equation(eq);
eqCombo.addItem(eq);
graph.addEquation(equation);
}
}
catch (EquationSyntaxException e)
{
JOptionPane.showMessageDialog(null, "ERR2: Equation is not well-formed", "alert", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Add multiple equations to Graph
* #param eq equation array
*/
private void addEquation(Equation[] eq)
{
for (int i = 0; i < eq.length; i++)
{
graph.addEquation(eq[i]);
}
}
/**
* Remove equation from Graph
* #param index index to remove
*/
private void removeEquation(int index)
{
if (index >= 0)
{
graph.removeEquation(index);
eqCombo.removeItem(eqCombo.getSelectedItem());
}
}
// Timer methods
protected void startTheClock() {
slider_1.setValue(0);
timer.start();
playButton.setIcon(pauseIcon);;
}
protected void stopTheClock() {
timer.stop();
playButton.setIcon(playIcon);
}
/**
* Read file and extract equations into an array. Any errors on an equation halt the loading of the entire file
* #param file name of file containing equations
* #return array of equations
* #throws IOException
*/
public Equation[] readEquationsFromFile(String file) throws IOException
{
ArrayList<Equation> eqList = new ArrayList<Equation>(20);
if (file == null)
return null;
String line;
int lineCount = 1;
try
{
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null)
{
Equation eq = new Equation(line);
eqList.add(eq);
lineCount++;
}
br.close();
return ((Equation[])(eqList.toArray(new Equation[0])));
}
catch (EquationSyntaxException e)
{
JOptionPane.showMessageDialog(null, "ERR2.1: Equation on line " + lineCount + " is not well-formed", "alert", JOptionPane.ERROR_MESSAGE);
return null;
}
}
/**
* Set up Plotter object and draw the graph.
* #param args command line arguments for Plotter
*/
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
String expr = JOptionPane.showInputDialog("Enter your expression");
String maxInput = JOptionPane.showInputDialog("Enter max value of x");
String minInput = JOptionPane.showInputDialog("Enter min value of x");
double frequency = 0.01;
double maxX = Double.parseDouble(maxInput);
double minX = Double.parseDouble(minInput);
String eqFile = null;
try
{
///double minX = Double.parseDouble(args[0]);
// double maxX = Double.parseDouble(args[1]);
// double frequency = Double.parseDouble(args[2]);
//double minX = -10;
//double maxX = 10;
//double frequency = 0.01;
if (args.length > 3)
eqFile = args[3];
Plotter plotterGUI = new Plotter(minX, maxX, frequency, eqFile);
plotterGUI.setVisible(true);
plotterGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
catch (NumberFormatException e)
{
System.out.println("ERR: Invalid arguments");
}
catch (GraphArgumentsException e)
{
System.out.println(e.getMessage());
}
catch (IOException e)
{
System.out.print("ERR4: Unable to read or access file");
}
}
}
general look of program :
now I want to change the code so the slider will affect the grapher .it means when user chooses the range of x from -10 to 10 , by clicking the play button the grapher starts to draw the graph as slider changes the x from -10 to 10
Gapminder chart is an example about slider and grapher should work.
The question is how can I do this ?
here is a small code which might help you get the insight of JSlider.
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
class demo extends JFrame
{
JFrame f=new JFrame("G");
JSlider slide=new JSlider();
JTextField field=new JTextField();
JTextField d=new JTextField();
final double value=0;
demo()
{
setSize(500,500);
f.setSize(600,600);
f.setVisible(true);
slide.setBounds(100,100,200,50);
field.setBounds(150,150,100,30);
d.setBounds(0,0,0,0);
add(slide);
add(field);
add(d);
}
public static void main(String args[])
{
demo m=new demo();
m.setVisible(true);
m.setLocationRelativeTo(null);
m.slidec();
}
public double slidec()
{
slide.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
double value=((JSlider)e.getSource()).getValue();
field.setText(Double.toString(value));
}
});
return value;
}
}
Related
I have a project that uses JFreeChart.
The chart that I am using is displaying correctly and works fine with the current code.
My problem is that I can only position the graph to the east, south, west, center or north of my JPanel.
My desire is to move this chart to any position inside my JPanel.
This is the short code snippet where I add my graph to the panSimulator JPanel. The problematic code is at the bottom of the ConfigurationFrame class:
public class ConfigurationFrame extends JFrame {
private KettlerBikeConnector bike1 = null;
private static final long serialVersionUID = 1L;
CrosshairDemo chd = new CrosshairDemo();
private JPanel panSimulator;
private PanelBikeSimulator panBSim;
private Timer timerBike;
private TimerListener listener;
private final int UPDATE_MS = 1000; // updates every second
private JTabbedPane tabPane;
private JPanel panConfiguration;
private JPanel panGame;
private JComboBox<String> cbxPort;
private JTextPane lblStatus;
// to have access to the textfield
public static JTextField txtEnergy;
public static JTextField txtDistance;
public static JTextField txtHeartRate;
public static JTextField txtTime;
public File path = null;
public int key = -1;
boolean run = true;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ConfigurationFrame frame = new ConfigurationFrame();
frame.setVisible(true);
// frame.pack(); // give a suitable size to window automatically
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
* #throws IOException
* #throws SAXException
* #throws ParserConfigurationException
*/
public ConfigurationFrame() throws ParserConfigurationException, SAXException, IOException {
setResizable(false);
setMinimumSize(new Dimension(1900, 1000));
setTitle("Bike Simulation ... I need a name ...");
setLocationRelativeTo(null);
addWindowListener(new WindowAdapter() {
#Override
public void windowClosed(WindowEvent arg0) {
try {
timerBike.stop();
bike1.close();
} catch (Exception e) {
log(e.getMessage());
}
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
getContentPane().setLayout(null);
// Panel
tabPane = new JTabbedPane(JTabbedPane.TOP);
tabPane.setFont(new Font("Tahoma", Font.PLAIN, 24));
tabPane.setBounds(0, 0, 1892, 994);
getContentPane().add(tabPane);
// Configuration-Panel
panConfiguration = new JPanel();
tabPane.addTab("Configuration", null, panConfiguration, null);
panConfiguration.setLayout(null);
// ComboBox for Kettler
cbxPort = new JComboBox<String>();
cbxPort.setFont(new Font("Tahoma", Font.PLAIN, 24));
cbxPort.setBounds(734, 5, 247, 49);
panConfiguration.add(cbxPort);
// Button-Connection
JButton btnConnect = new JButton("Connect");
btnConnect.setFont(new Font("Tahoma", Font.PLAIN, 24));
btnConnect.setBounds(157, 7, 137, 49);
btnConnect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
bike1 = new KettlerBikeConnector();
bike1.connect(cbxPort.getSelectedItem().toString(), new KettlerBikeListener() {
#Override
public void bikeAck() {
switch (listener.state) {
case hello:
listener.state = State.connected;
break;
case reset:
listener.state = State.hello;
break;
case connected:
log("connection successful");
break;
case notConnected:
log("not connected");
break;
}
}
#Override
public void bikeData(DataRecord data) {
//Sending the Ergometer velcoity every 1000ms to the
panBSim.setErgometerVelocity(data.getSpeed() / 10);
panBSim.setErgometerRPM(data.getPedalRpm());
panBSim.setTrueDataHere(true);
double power = panBSim.getTraveledDistance();
chd.setPower(power);
//getPower und dann set hier die Ergometer widerstand
try {
bike1.sendSetPower(panBSim.getErgometerPower());
} catch (IOException ignored) {
System.out.println("ignored");
}
}
#Override
public void bikeDestPowerChanged(int power) {
log("dest power: " + power);
}
#Override
public void bikeError() {
log("error1");
}
});
} catch (Exception e) {
log(e.getMessage());
}
}
});
panConfiguration.add(btnConnect);
// Button-Start
JButton btnStart = new JButton("Start");
btnStart.setFont(new Font("Tahoma", Font.PLAIN, 24));
btnStart.setBounds(304, 7, 137, 49);
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
listener = new TimerListener(bike1);
timerBike = new Timer(UPDATE_MS, listener);
timerBike.start();
tabPane.setSelectedComponent(panSimulator); // switch to GamePanel
panBSim.startSimulate();
} catch (Exception e) {
log(e.getMessage());
}
}
});
panConfiguration.add(btnStart);
// Button-Scan
JButton btnScan = new JButton("Scan");
btnScan.setFont(new Font("Tahoma", Font.PLAIN, 24));
btnScan.setBounds(10, 7, 137, 49);
btnScan.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Enumeration<CommPortIdentifier> portList = CommPortIdentifier.getPortIdentifiers(); // list of named
while (portList.hasMoreElements()) {
CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
cbxPort.addItem(portId.getName());
if (portId.isCurrentlyOwned()) {
log("Port " + portId.getName() + " is already open");
}
}
}
}
});
panConfiguration.add(btnScan);
// Status displays information regarding connection
lblStatus = new JTextPane();
lblStatus.setText(
"Anweisung:\r\n\t1) W\u00E4hle ein Lebensmittel aus der Food-Item Combobox aus\r\n\t2) Dr\u00FCcke den Scan-Button und w\u00E4hle den Port aus der Port Combobox aus\r\n\t3) Dr\u00FCcke den Connect-Button, um die Ger\u00E4te zu verbinden\r\n\t4) Dr\u00FCcke den Start-Button, um die Anwendung zu starten\r\n\t5) Warte auf das akustische Signal des Ergometer\r\n\t6) Beginne zu treten");
lblStatus.setFont(new Font("Tahoma", Font.PLAIN, 24));
lblStatus.setBounds(10, 125, 971, 229);
lblStatus.setDisabledTextColor(Color.BLACK);
lblStatus.setSelectionColor(new Color(51, 153, 255));
panConfiguration.add(lblStatus);
// FH Logo
JLabel lblLogo = new JLabel("");
lblLogo.setBounds(10, 365, 971, 430);
try {
File in = new File("FHLogo.png");
Image logo = ImageIO.read(in);
Image scaledLogo = logo.getScaledInstance(lblLogo.getWidth(), lblLogo.getHeight(), Image.SCALE_SMOOTH);
ImageIcon iconLogo = new ImageIcon(scaledLogo);
lblLogo.setIcon(iconLogo);
} catch (IOException e2) {
e2.printStackTrace();
}
panConfiguration.add(lblLogo);
// Labels
JLabel lblPort = new JLabel("Port:");
lblPort.setFont(new Font("Tahoma", Font.PLAIN, 24));
lblPort.setBounds(600, 5, 124, 49);
panConfiguration.add(lblPort);
//-----------------------------------------------------------------------------XXX
//Tab Bike Simulator
BorderLayout bdl = new BorderLayout();
panSimulator = new JPanel();
tabPane.addTab("Bike Simulator", null, panSimulator, null);
panSimulator.setLayout(bdl);
//Panel Bike Simulator
//panBSim = new PanelBikeSimulator();
//panBSim.setBorder(BorderFactory.createLineBorder(Color.black));
panSimulator.add(chd.getContentPane(), bdl.NORTH);
}
/**
* To log information
*
* #param str String that is shown
*/
private void log(String str) {
lblStatus.setText(lblStatus.getText() + str + "\n");
}
}
And this class belongs to my chart that I want to move to any location in my JPanel.
public class CrosshairDemo extends JFrame {
private static double POWER = 0.0;
public void setPower(double power) {
POWER = power;
}
public CrosshairDemo() {
super();
this.setContentPane(new CrosshairDemo.MyDemoPanel());
}
public static class MyDemoPanel extends JPanel implements Runnable {
/**
*
*/
private static final long serialVersionUID = 1L;
Thread t = new Thread((Runnable) this);
private TimeSeries series;
private final ChartPanel chartPanel;
private final JFreeChart chart = this.createChart();
public MyDemoPanel() {
super(new BorderLayout());
this.chartPanel = new ChartPanel(this.chart);
this.chartPanel.setPreferredSize(new Dimension(200, 550));
this.chartPanel.setLocation(getWidth() + 50, getHeight() + 30);
this.chartPanel.setDomainZoomable(true);
this.chartPanel.setRangeZoomable(true);
this.add(this.chartPanel);
t.start();
}
private JFreeChart createChart() {
XYDataset dataset1 = this.createDataset("Random 1", 100.0D, new Minute(), 200);
JFreeChart chart1 = ChartFactory.createTimeSeriesChart("Crosshair Demo 1", "Time of Day", "Value", dataset1);
XYPlot plot = (XYPlot)chart1.getPlot();
plot.setOrientation(PlotOrientation.VERTICAL);
plot.setDomainCrosshairVisible(true);
plot.setDomainCrosshairLockedOnData(false);
plot.setRangeCrosshairVisible(false);
return chart1;
}
private XYDataset createDataset(String name, double base, RegularTimePeriod start, int count) {
this.series = new TimeSeries(name);
RegularTimePeriod period = start;
double value = base;
for(int i = 0; i < count; ++i) {
this.series.add(period, value);
period = period.next();
value *= 1.0D + (Math.random() - 0.495D) / 10.0D;
}
TimeSeriesCollection dataset = new TimeSeriesCollection();
dataset.addSeries(this.series);
return dataset;
}
#Override
public void run() {
// TODO Auto-generated method stub
while(true) {
int value = (int) POWER; //this.slider.getValue();
XYPlot plot = (XYPlot)this.chart.getPlot();
ValueAxis domainAxis = plot.getDomainAxis();
Range range = domainAxis.getRange();
double c = domainAxis.getLowerBound() + (double)value / 100.0D * range.getLength();
plot.setDomainCrosshairValue(c);
}
}
}
Right now it's "attached" to the top (NORTH) of my JPanel:
Current chart position:
I would appreciate any help, because I have no more idea how to position this chart freely, therefore, I need your help guys.
I have a swing application which takes user input and goes to full screen and displays variations of input image, I want to stop this thread execution on particular key press (prig should not terminate) and program should ask for the another user input. don't know how to approach? plz help here's code:::
public class ImageProcessor extends JFrame implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 2916361361443483318L;
private JFileChooser fc = null;
private JMenuItem item1, item2;
private BufferedImage image = null;
private JFrame frame = null;
private JPanel panel = null;
private int width = 0;
private int height = 0;
private BorderLayout card;
private Container contentPane;
private int wcount = 0;
private int hcount = 0;
public ImageProcessor() {
frame = new JFrame("Image Processor");
contentPane = frame.getContentPane();
panel = new JPanel();
card = new BorderLayout();
panel.setLayout(card);
panel.setBackground(Color.white);
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Menu");
menu.setMnemonic(KeyEvent.VK_M);
menuBar.add(menu);
item1 = new JMenuItem("Browse an image");
item2 = new JMenuItem("Exit");
item1.addActionListener(this);
item2.addActionListener(this);
menu.add(item1);
menu.add(item2);
frame.setJMenuBar(menuBar);
contentPane.add(panel);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new ImageProcessor();
}
});
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == item1) {
if (fc == null)
fc = new JFileChooser();
int retVal = fc.showOpenDialog(null);
if (retVal == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
try {
image = ImageIO.read(file);
width = image.getWidth();
height = image.getHeight();
final GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
frame.getJMenuBar().setVisible(false);
gd.setFullScreenWindow(frame);
Timer timer = new Timer(0, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
panel.removeAll();
//System.out.println(wcount + " " + hcount);
if(wcount <= width-1 && hcount <= height-1){
Color c = new Color(image.getRGB(wcount, hcount));
panel.setBackground(c);
panel.revalidate();
panel.repaint();
}
((Timer)e.getSource()).setDelay(333);
if(wcount <= width-1){
if(hcount < height-1 )
hcount++;
else{
hcount = 0;
wcount++;
}
}else{
//((Timer)e.getSource()).stop();
//gd.setFullScreenWindow(null);
//frame.getJMenuBar().setVisible(true);
//JOptionPane.showMessageDialog(null, "Image Read Complete!");
wcount = 0;
hcount = 0;
}
}
});
timer.start();
} catch (IOException e1) {
System.out.println("IO::" + e1.getMessage());
} catch (Exception e1) {
System.out.println("Exception::" + e1.getMessage());
}
}
}
if (e.getSource() == item2) {
System.exit(0);
}
}
}
plz advice..
I am having trouble with one part of my code. I have been working for so long on this and I am exhausted and missing something easy. I need to have a text box to enter a new title for the JFrame, a button that says "Set New Name" and an "Exit Button.
Can someone look at this code and give me some info so I can go to bed.
Thank you
//Good One
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
public class Pool {
public static void main(String[] args) {
new poolCalc();
}
}
class poolCalc extends JFrame {
private static final long serialVersionUID = 1L;
public static final double MILLIMETER = 1;
public static final double METER = 1000 * MILLIMETER;
public static final double INCH = 25.4 * MILLIMETER;
public static final double FOOT = 304.8 * MILLIMETER;
public static final double YARD = 914.4 * MILLIMETER;
private static final DecimalFormat df = new DecimalFormat("#,##0.###");
private JTabbedPane tabs;
private JPanel generalPanel;
private JPanel optionsPanel;
private JPanel customerPanel;
private JPanel contractorPanel;
private JPanel poolPanel;
private JPanel hotTubPanel;
private JPanel tempCalPanel;
private JPanel lengthCalPanel;
public poolCalc() {
super("The Pool Calculator");
setSize(340, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(true);
initializeComponents();
setLocationRelativeTo(null);
setVisible(true);
}
private void initializeComponents() {
Container pane = getContentPane();
tabs = new JTabbedPane();
generalTab();
optionsTab();
customerTab();
contractorTab();
poolsTab();
hotTubsTab();
tempCalTab();
lengthCalTab();
tabs.add("General", generalPanel);
tabs.add("Options", optionsPanel);
tabs.add("Customers", customerPanel);
tabs.add("Contractors", contractorPanel);
tabs.add("Pools", poolPanel);
tabs.add("Hot Tubs", hotTubPanel);
tabs.add("Temp Calc", tempCalPanel);
tabs.add("Length Calc", lengthCalPanel);
pane.add(tabs);
}
private JButton createExitButton() {
JButton exitButton = new JButton("Exit");
exitButton.setMnemonic('x');
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
return exitButton;
}
private void generalTab() {
generalPanel = new JPanel(new FlowLayout());
String currentTime = SimpleDateFormat.getInstance().format(
Calendar.getInstance().getTime());
generalPanel.add(new JLabel("Today's Date: " + currentTime));
generalPanel.add(createExitButton());
}
private JTextField createTitleField(String text, int length) {
JTextField tf = new JTextField(length);
tf.setEditable(false);
tf.setFocusable(false);
tf.setText(text);
return tf;
}
// FIX
private void optionsTab() {
optionsPanel = new JPanel(new FlowLayout());
//optionsPanel.setLayout(null);
JLabel labelOptions = new JLabel("Change Company Name:");
labelOptions.setBounds(120, 10, 150, 20);
optionsPanel.add(labelOptions);
final JTextField newTitle = new JTextField("Some Title");
newTitle.setBounds(80, 40, 225, 20);
optionsPanel.add(newTitle);
final JTextField myTitle = new JTextField("My Title...");
myTitle.setBounds(80, 40, 225, 20);
myTitle.add(labelOptions);
JButton newName = new JButton("Set New Name");
newName.setBounds(60, 80, 150, 20);
//newName.addActionListener(this);
optionsPanel.add(newName);
optionsPanel.add(createExitButton());
}
private void customerTab() {
customerPanel = createContactPanel("Customer", "customer.txt");
}
private void contractorTab() {
contractorPanel = createContactPanel("Contractor", "contractor.txt");
}
private void poolsTab() {
poolPanel = new JPanel(new FlowLayout());
final JRadioButton roundPool = new JRadioButton("Round Pool");
final JRadioButton ovalPool = new JRadioButton("Oval Pool");
final JRadioButton rectangularPool = new JRadioButton("Rectangle Pool");
roundPool.setSelected(true);
ButtonGroup group = new ButtonGroup();
group.add(roundPool);
group.add(rectangularPool);
poolPanel.add(roundPool);
poolPanel.add(rectangularPool);
poolPanel.add(new JLabel("Enter the pool's length (ft): "));
final JTextField lengthField = new JTextField(10);
poolPanel.add(lengthField);
final JLabel widthLabel = new JLabel("Enter the pool's width (ft): ");
widthLabel.setEnabled(false);
poolPanel.add(widthLabel);
final JTextField widthField = new JTextField(10);
widthField.setEnabled(false);
poolPanel.add(widthField);
poolPanel.add(new JLabel("Enter the pool's depth (ft): "));
final JTextField depthField = new JTextField(10);
poolPanel.add(depthField);
JButton calculateVolume = new JButton("Calculate Volume");
calculateVolume.setMnemonic('C');
poolPanel.add(calculateVolume);
poolPanel.add(createExitButton());
poolPanel.add(new JLabel("The pool's volume is (ft^3): "));
final JTextField volumeField = new JTextField(10);
volumeField.setEditable(false);
poolPanel.add(volumeField);
final JTextArea messageArea = createMessageArea(2, 20, "");
poolPanel.add(messageArea);
calculateVolume.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (roundPool.isSelected()) {
widthField.setText(lengthField.getText());
}
ValidationResult result = validateFields(new JTextField[] {
lengthField, widthField, depthField });
String errors = "";
if (result.filled != 3) {
errors += "Please fill out all fields! ";
}
if (result.valid != 3 && result.filled != result.valid) {
errors += "Please enter valid numbers!";
}
if (errors != "") {
messageArea.setText(errors);
messageArea.setVisible(true);
}
else {
messageArea.setVisible(false);
double length = Double.parseDouble(lengthField.getText());
double width = Double.parseDouble(widthField.getText());
double depth = Double.parseDouble(depthField.getText());
double volume;
if (roundPool.isSelected()) {
volume = Math.PI * Math.pow(length / 2.0, 2) * depth;
}
if (rectangularPool.isSelected()) {
volume = length * width * depth * 5.9;
}
else {
volume = length * width * depth * 7.5;
}
volumeField.setText(df.format(volume));
}
}
});
ActionListener poolsListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == roundPool) {
widthLabel.setEnabled(false);
widthField.setEnabled(false);
widthField.setText(lengthField.getText());
}
else if (e.getSource() == rectangularPool) {
widthLabel.setEnabled(true);
widthField.setEnabled(true);
messageArea.setVisible(false);
}
}
};
roundPool.addActionListener(poolsListener);
ovalPool.addActionListener(poolsListener);
rectangularPool.addActionListener(poolsListener);
}
private void hotTubsTab() {
hotTubPanel = new JPanel(new FlowLayout());
final JRadioButton roundTub = new JRadioButton("Round Tub");
final JRadioButton ovalTub = new JRadioButton("Oval Tub");
roundTub.setSelected(true);
ButtonGroup group = new ButtonGroup();
group.add(roundTub);
group.add(ovalTub);
hotTubPanel.add(roundTub);
hotTubPanel.add(ovalTub);
hotTubPanel.add(new JLabel("Enter the tub's length (ft): "));
final JTextField lengthField = new JTextField(10);
hotTubPanel.add(lengthField);
final JLabel widthLabel = new JLabel("Enter the tub's width (ft): ");
widthLabel.setEnabled(false);
hotTubPanel.add(widthLabel);
final JTextField widthField = new JTextField(10);
widthField.setEnabled(false);
hotTubPanel.add(widthField);
hotTubPanel.add(new JLabel("Enter the tub's depth (ft): "));
final JTextField depthField = new JTextField(10);
hotTubPanel.add(depthField);
JButton calculateVolume = new JButton("Calculate Volume");
calculateVolume.setMnemonic('C');
hotTubPanel.add(calculateVolume);
hotTubPanel.add(createExitButton());
hotTubPanel.add(new JLabel("The tub's volume is (ft^3): "));
final JTextField volumeField = new JTextField(10);
volumeField.setEditable(false);
hotTubPanel.add(volumeField);
final JTextArea messageArea = createMessageArea(1, 25,
"Width will be set to the same value as length");
hotTubPanel.add(messageArea);
calculateVolume.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (roundTub.isSelected()) {
widthField.setText(lengthField.getText());
}
ValidationResult result = validateFields(new JTextField[] {
lengthField, widthField, depthField });
String errors = "";
if (result.filled != 3) {
errors += "Please fill out all fields! ";
}
if (result.valid != 3 && result.filled != result.valid) {
errors += "Please enter valid numbers!";
}
if (errors != "") {
messageArea.setText(errors);
messageArea.setVisible(true);
}
else {
messageArea.setVisible(false);
double length = Double.parseDouble(lengthField.getText());
double width = Double.parseDouble(widthField.getText());
double depth = Double.parseDouble(depthField.getText());
double volume;
if (roundTub.isSelected()) {
volume = Math.PI * Math.pow(length / 2.0,2) * depth;
}
if (ovalTub.isSelected()) {
volume = Math.PI * ((length * width)*2) * depth;
}
else {
volume = length * width * depth * 7.5;
}
volumeField.setText(df.format(volume));
}
}
});
ActionListener tubsListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == roundTub) {
widthLabel.setEnabled(false);
widthField.setEnabled(false);
widthField.setText(lengthField.getText());
}
else if (e.getSource() == ovalTub) {
widthLabel.setEnabled(true);
widthField.setEnabled(true);
messageArea.setVisible(false);}
}
};
roundTub.addActionListener(tubsListener);
ovalTub.addActionListener(tubsListener);}
private void tempCalTab() {
tempCalPanel = new JPanel(new FlowLayout());
tempCalPanel.add(new JLabel("Enter temperature: "));
final JTextField temperatureField = new JTextField(10);
tempCalPanel.add(temperatureField);
final JComboBox optionComboBox = new JComboBox(
new String[] { "C", "F" });
tempCalPanel.add(optionComboBox);
tempCalPanel.add(new JLabel("Result: "));
final JTextField resultField = new JTextField(18);
resultField.setEditable(false);
tempCalPanel.add(resultField);
final JLabel oppositeLabel = new JLabel("F");
tempCalPanel.add(oppositeLabel);
JButton convertButton = new JButton("Convert");
convertButton.setMnemonic('C');
tempCalPanel.add(convertButton);
tempCalPanel.add(createExitButton());
final JTextArea messageArea = createMessageArea(1, 20,
"System Messages");
tempCalPanel.add(messageArea);
optionComboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
if ("F".equals(e.getItem())) {
oppositeLabel.setText("C");}
else {
oppositeLabel.setText("F");}}}
});
convertButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ValidationResult result = validateFields(new JTextField[] { temperatureField });
String errors = "";
if (result.filled != 1 || result.valid != 1) {
errors += "Value set to zero";}
if (errors != "") {
messageArea.setText(errors);
messageArea.setVisible(true);
temperatureField.setText("0");}
else {
messageArea.setVisible(false);}
double temperature = Double.parseDouble(temperatureField
.getText());
double resultValue = 0;
if (oppositeLabel.getText().equals("C")) {
resultValue = (temperature - 32.0) / 9.0 * 5.0;}
else if (oppositeLabel.getText().equals("F")) {
resultValue = ((temperature * 9.0) / 5.0) + 32.0;}
resultField.setText(df.format(resultValue));}
});
}
private void lengthCalTab() {
lengthCalPanel = new JPanel(new FlowLayout());
lengthCalPanel.add(createTitleField("Millimeters", 6));
lengthCalPanel.add(createTitleField("Meters", 4));
lengthCalPanel.add(createTitleField("Yards", 4));
lengthCalPanel.add(createTitleField("Feet", 3));
lengthCalPanel.add(createTitleField("Inches", 6));
final JTextField millimetersField = new JTextField(6);
final JTextField metersField = new JTextField(4);
final JTextField yardsField = new JTextField(4);
final JTextField feetField = new JTextField(3);
final JTextField inchesField = new JTextField(6);
lengthCalPanel.add(millimetersField);
lengthCalPanel.add(metersField);
lengthCalPanel.add(yardsField);
lengthCalPanel.add(feetField);
lengthCalPanel.add(inchesField);
JButton convertButton = new JButton("Convert");
convertButton.setMnemonic('C');
convertButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double millimeters = convertToDouble(millimetersField.getText());
double meters = convertToDouble(metersField.getText());
double yards = convertToDouble(yardsField.getText());
double feet = convertToDouble(feetField.getText());
double inches = convertToDouble(inchesField.getText());
double value = 0;
if (millimeters != 0) {
value = millimeters * MILLIMETER;}
else if (meters != 0) {
value = meters * METER;}
else if (yards != 0) {
value = yards * YARD;}
else if (feet != 0) {
value = feet * FOOT;}
else if (inches != 0) {
value = inches * INCH;}
millimeters = value / MILLIMETER;
meters = value / METER;
yards = value / YARD;
feet = value / FOOT;
inches = value / INCH;
millimetersField.setText(df.format(millimeters));
metersField.setText(df.format(meters));
yardsField.setText(df.format(yards));
feetField.setText(df.format(feet));
inchesField.setText(df.format(inches));}
private double convertToDouble(String s) {
try {
return Double.parseDouble(s);}
catch (Exception e) {
return 0;}}
});
JButton clearButton = new JButton("Clear");
clearButton.setMnemonic('l');
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
millimetersField.setText(null);
metersField.setText(null);
yardsField.setText(null);
feetField.setText(null);
inchesField.setText(null);}
});
lengthCalPanel.add(convertButton);
lengthCalPanel.add(clearButton);
lengthCalPanel.add(createExitButton());}
private String loadDataFromFile(String fileName) {
String data = "";
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
while (reader.ready()) {
data += reader.readLine() + "\n";}
reader.close();}
catch (IOException e){
}
return data;}
private JPanel createContactPanel(final String contactName,
final String fileName) {
JPanel pane = new JPanel(new FlowLayout());
final JTextArea customerDisplay = new JTextArea(8, 25);
customerDisplay.setLineWrap(true);
customerDisplay.setEditable(false);
pane.add(new JScrollPane(customerDisplay));
pane.add(createExitButton());
JButton addCustomerButton = new JButton("Add " + contactName);
addCustomerButton.setMnemonic('A');
pane.add(addCustomerButton);
JButton refreshButton = new JButton("Refresh");
refreshButton.setMnemonic('R');
pane.add(refreshButton);
final JTextArea messageArea = createMessageArea(2, 25, "");
messageArea.setBackground(Color.white);
pane.add(messageArea);
addCustomerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new EditContact(contactName, fileName);}
});
refreshButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = loadDataFromFile(fileName);
if (data != "") {
customerDisplay.setText(data);
customerDisplay.setEnabled(true);
messageArea.setText("File " + fileName
+ " can be read from!");
}
else {
customerDisplay.setText("Click Add "
+ contactName
+ " button to add "
+ contactName.toLowerCase()
+ ". And click Refresh button to update this pane.");
customerDisplay.setEnabled(false);
messageArea.setText("File " + fileName + " is not "
+ "there yet! It will be created "
+ "when you add " + contactName.toLowerCase()
+ "s!");
}
}
});
refreshButton.doClick();
return pane;
}
private JTextArea createMessageArea(int rows, int cols, String text) {
final JTextArea messageArea = new JTextArea(rows, cols);
messageArea.setBorder(BorderFactory.createEmptyBorder());
messageArea.setLineWrap(true);
messageArea.setWrapStyleWord(true);
messageArea.setFont(new Font("System", Font.PLAIN, 12));
messageArea.setText(text);
messageArea.setBackground(null);
messageArea.setForeground(Color.GRAY);
messageArea.setEnabled(true);
messageArea.setFocusable(false);
return messageArea;
}
private class ValidationResult {
int filled;
int valid;
}
private ValidationResult validateFields(JTextField[] fields) {
ValidationResult result = new ValidationResult();
for (int i = 0; i < fields.length; i++) {
JTextField field = fields[i];
if ((field.getText() != null) && (field.getText().length() > 0)) {
result.filled++;
}
try {
Double.parseDouble(field.getText());
field.setBackground(Color.white);
result.valid++;
}
catch (Exception e) {
field.setBackground(Color.orange);
}
}
return result;
}
private class EditContact extends JDialog {
private static final long serialVersionUID = 1L;
private final String contactName;
private final String fileName;
private File file;
private JTextField nameField;
private JTextField addressField;
private JTextField cityField;
private JComboBox stateComboBox;
private JTextField zipField;
private JTextField phoneField;
private JTextArea messageArea;
public EditContact(String contactName, String fileName) {
super(poolCalc.this, contactName + "s");
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
setModalityType(ModalityType.APPLICATION_MODAL);
setSize(418, 300);
this.contactName = contactName;
this.fileName = fileName;
initializeComponents();
if (openFile()) {
displayMessage(null);
}
else {
displayMessage("File " + fileName + " does not exist yet! "
+ "Will be created when you add a "
+ contactName.toLowerCase() + "!");
}
setLocationRelativeTo(null);
setVisible(true);
}
private void displayMessage(String message) {
if (message != null) {
messageArea.setVisible(true);
messageArea.setText(message);
}
else {
messageArea.setVisible(false);
}
}
private boolean openFile() {
file = new File(fileName);
return file.exists();
}
private boolean deleteFile() {
return file.exists() && file.delete();
}
private boolean saveToFile() {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(file,
true));
writer.write("Name: " + nameField.getText() + "\n");
writer.write("Address: " + addressField.getText() + "\n");
writer.write("City: " + cityField.getText() + "\n");
writer.write("State: "
+ stateComboBox.getSelectedItem().toString() + "\n");
writer.write("ZIP: " + zipField.getText() + "\n");
writer.write("Phone: " + phoneField.getText() + "\n");
writer.write("\n");
writer.close();
return true;
}
catch (IOException e) {
return false;
}
}
private void initializeComponents() {
Container pane = getContentPane();
pane.setLayout(new FlowLayout());
pane.add(new JLabel(contactName + " Name "));
nameField = new JTextField(25);
pane.add(nameField);
pane.add(new JLabel("Address "));
addressField = new JTextField(28);
pane.add(addressField);
pane.add(new JLabel("City "));
cityField = new JTextField(32);
pane.add(cityField);
pane.add(new JLabel("State "));
stateComboBox = new JComboBox(new String[] { "AL", "AK", "AZ",
"AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI", "ID", "IL",
"IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN",
"MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC",
"ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX",
"UT", "VT", "VA", "WA", "WV", "WI", "WY" });
pane.add(stateComboBox);
pane.add(new JLabel("ZIP "));
zipField = new JTextField(5);
pane.add(zipField);
pane.add(new JLabel("Phone "));
phoneField = new JTextField(10);
pane.add(phoneField);
JButton addContactButton = new JButton("Add " + this.contactName);
addContactButton.setMnemonic('A');
addContactButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (saveToFile()) {
displayMessage(contactName + " added");
}
else {
displayMessage("File saving error!");
}
}
});
pane.add(addContactButton);
JButton closeButton = new JButton("Close");
closeButton.setMnemonic('C');
closeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setVisible(false);
}
});
pane.add(closeButton);
JButton deleteFileButton = new JButton("Delete File");
deleteFileButton.setMnemonic('D');
deleteFileButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (deleteFile()) {
displayMessage("File " + fileName + " deleted!");
}
}
});
pane.add(deleteFileButton);
messageArea = createMessageArea(2, 30, "");
messageArea.setBackground(Color.white);
pane.add(messageArea);
}
}
}
Let's start with this (which I assume is where you create the details)...
private void optionsTab() {
optionsPanel = new JPanel(new FlowLayout());
//optionsPanel.setLayout(null);
JLabel labelOptions = new JLabel("Change Company Name:");
labelOptions.setBounds(120, 10, 150, 20);
optionsPanel.add(labelOptions);
final JTextField newTitle = new JTextField("Some Title");
newTitle.setBounds(80, 40, 225, 20);
optionsPanel.add(newTitle);
final JTextField myTitle = new JTextField("My Title...");
myTitle.setBounds(80, 40, 225, 20);
myTitle.add(labelOptions);
JButton newName = new JButton("Set New Name");
newName.setBounds(60, 80, 150, 20);
//newName.addActionListener(this);
optionsPanel.add(newName);
optionsPanel.add(createExitButton());
}
The newTitle field is a local variable, so once the method exists, you will not be able to access the field (easily)...
You seem to have tried adding a actionListener to the newName button, which isn't a bad idea, but because you can't actually access the newTitle field, isn't going to help...
The use of setBounds is not only ill advised, but probably won't result in the results you are expecting, because the optionsPane is under the control a layout manager...
And while I was digging around, I noticed this if (errors != "") {...This is not how String comparison is done in Java. This is comparing the memory references of both Strings which will never be true, instead you should if (!"".equals(errors)) {...
But back to the problem at hand...
You are really close to having a solution. You could make the newTitle field a class instance variable, which would allow you to access the field within other parts of your program, but because you've made it final, there's something else you can try...
You can use an anonymous inner class instead...
newName.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
setTitle(newTitle.getText());
}
});
Which should get a good nights sleep :D
It is a little unclear what you want, but if I understand you right you want the JButton newName to set the title of the JFrame to the text in some textbox?
In that case you would write
setTitle(someTextbox.getText());
inside the function of the button.
First, you need to create a JTextField that has public access. Then, create a JButton that implements ActionListener. After that you must implement the abstract method actionPerformed() in the JButton Subclass. Then in the run method say JFrame.setTitle(JTextfield.getText()).
Subclass Method:
public class main extends JFrame{
// Construct and setVisible()
}
class textfield extends JTextField{
// create field then add to JFrame
}
class button extends JButton implements ActionListener{
// create button
public void actionPerformed(ActionEvent e){
main.setTitle(textfield.getText());
}
Instance Method:
public class main implements ActionListener{
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JTextField field = new JTextField();
JButton button = new JButtone();
button.addActionListener(this);
panel.add(field);
panel.add(button);
frame.add(panel);
public void actionPerformed(ActionEvent e){
frame.setTitle(field.getText);
}
}
Try This
private void optionsTab() {
optionsPanel = new JPanel(new FlowLayout());
// optionsPanel.setLayout(null);
JLabel labelOptions = new JLabel("Change Company Name:");
labelOptions.setBounds(120, 10, 150, 20);
optionsPanel.add(labelOptions);
final JTextField newTitle = new JTextField("Some Title");
newTitle.setBounds(80, 40, 225, 20);
optionsPanel.add(newTitle);
final JTextField myTitle = new JTextField("My Title...");
myTitle.setBounds(80, 40, 225, 20);
myTitle.add(labelOptions);
JButton newName = new JButton("Set New Name");
newName.setBounds(60, 80, 150, 20);
newName.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setTitle(newTitle.getText());
}
});
// newName.addActionListener(this);
optionsPanel.add(newName);
optionsPanel.add(createExitButton());
}
I have a jframe with page navigation buttons,print,search buttons.When i clicked on the print button it is perfectly opening the window and i am able to print the page also.But when i clicked on search button i am not able to get the window.My requirement is clicking on the Search button should open a window(same as print window) with text field and when i enter the search data then it should display the matches and unmatches.
I have tried the below code but i am not succeed.
import com.google.common.base.CharMatcher;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
import com.sun.pdfview.PDFRenderer;
import com.sun.pdfview.PagePanel;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.standard.PageRanges;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import static com.google.common.base.Strings.isNullOrEmpty;
public class PdfViewer extends JPanel {
private static enum Navigation {
GO_FIRST_PAGE, FORWARD, BACKWARD, GO_LAST_PAGE, GO_N_PAGE
}
private static final CharMatcher POSITIVE_DIGITAL = CharMatcher.anyOf("0123456789");
private static final String GO_PAGE_TEMPLATE = "%s of %s";
private static final int FIRST_PAGE = 1;
private int currentPage = FIRST_PAGE;
private JButton btnFirstPage;
private JButton btnPreviousPage;
private JTextField txtGoPage;
private JButton btnNextPage;
private JButton btnLastPage;
private JButton print;
private JButton search;
private PagePanel pagePanel;
private PDFFile pdfFile;
public PdfViewer() {
initial();
}
private void initial() {
setLayout(new BorderLayout(0, 0));
JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
add(topPanel, BorderLayout.NORTH);
btnFirstPage = createButton("|<<");
topPanel.add(btnFirstPage);
btnPreviousPage = createButton("<<");
topPanel.add(btnPreviousPage);
txtGoPage = new JTextField(10);
txtGoPage.setHorizontalAlignment(JTextField.CENTER);
topPanel.add(txtGoPage);
btnNextPage = createButton(">>");
topPanel.add(btnNextPage);
btnLastPage = createButton(">>|");
topPanel.add(btnLastPage);
print = new JButton("print");
topPanel.add(print);
search = new JButton("search");
topPanel.add(search);
JScrollPane scrollPane = new JScrollPane();
add(scrollPane, BorderLayout.CENTER);
JPanel viewPanel = new JPanel(new BorderLayout(0, 0));
scrollPane.setViewportView(viewPanel);
pagePanel = new PagePanel();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
pagePanel.setPreferredSize(screenSize);
viewPanel.add(pagePanel, BorderLayout.CENTER);
disableAllNavigationButton();
btnFirstPage.addActionListener(new PageNavigationListener(Navigation.GO_FIRST_PAGE));
btnPreviousPage.addActionListener(new PageNavigationListener(Navigation.BACKWARD));
btnNextPage.addActionListener(new PageNavigationListener(Navigation.FORWARD));
btnLastPage.addActionListener(new PageNavigationListener(Navigation.GO_LAST_PAGE));
txtGoPage.addActionListener(new PageNavigationListener(Navigation.GO_N_PAGE));
print.addActionListener(new PrintUIWindow());
search.addActionListener(new Action1());
}
static class Action1 implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame parent = new JFrame();
JDialog jDialog = new JDialog();
Label label = new Label("Enter Word: ");
final JTextField jTextField = new JTextField(100);
JPanel panel = new JPanel();
parent.add(panel);
panel.add(label);
panel.add(jTextField);
parent.setLocationRelativeTo(null);
}
}
private JButton createButton(String text) {
JButton button = new JButton(text);
button.setPreferredSize(new Dimension(55, 20));
return button;
}
private void disableAllNavigationButton() {
btnFirstPage.setEnabled(false);
btnPreviousPage.setEnabled(false);
btnNextPage.setEnabled(false);
btnLastPage.setEnabled(false);
}
private boolean isMoreThanOnePage(PDFFile pdfFile) {
return pdfFile.getNumPages() > 1;
}
private class PageNavigationListener implements ActionListener {
private final Navigation navigation;
private PageNavigationListener(Navigation navigation) {
this.navigation = navigation;
}
public void actionPerformed(ActionEvent e) {
if (pdfFile == null) {
return;
}
int numPages = pdfFile.getNumPages();
if (numPages <= 1) {
disableAllNavigationButton();
} else {
if (navigation == Navigation.FORWARD && hasNextPage(numPages)) {
goPage(currentPage, numPages);
}
if (navigation == Navigation.GO_LAST_PAGE) {
goPage(numPages, numPages);
}
if (navigation == Navigation.BACKWARD && hasPreviousPage()) {
goPage(currentPage, numPages);
}
if (navigation == Navigation.GO_FIRST_PAGE) {
goPage(FIRST_PAGE, numPages);
}
if (navigation == Navigation.GO_N_PAGE) {
String text = txtGoPage.getText();
boolean isValid = false;
if (!isNullOrEmpty(text)) {
boolean isNumber = POSITIVE_DIGITAL.matchesAllOf(text);
if (isNumber) {
int pageNumber = Integer.valueOf(text);
if (pageNumber >= 1 && pageNumber <= numPages) {
goPage(Integer.valueOf(text), numPages);
isValid = true;
}
}
}
if (!isValid) {
JOptionPane.showMessageDialog(PdfViewer.this,
format("Invalid page number '%s' in this document", text));
txtGoPage.setText(format(GO_PAGE_TEMPLATE, currentPage, numPages));
}
}
}
}
private void goPage(int pageNumber, int numPages) {
currentPage = pageNumber;
PDFPage page = pdfFile.getPage(currentPage);
pagePanel.showPage(page);
boolean notFirstPage = isNotFirstPage();
btnFirstPage.setEnabled(notFirstPage);
btnPreviousPage.setEnabled(notFirstPage);
txtGoPage.setText(format(GO_PAGE_TEMPLATE, currentPage, numPages));
boolean notLastPage = isNotLastPage(numPages);
btnNextPage.setEnabled(notLastPage);
btnLastPage.setEnabled(notLastPage);
}
private boolean hasNextPage(int numPages) {
return (++currentPage) <= numPages;
}
private boolean hasPreviousPage() {
return (--currentPage) >= FIRST_PAGE;
}
private boolean isNotLastPage(int numPages) {
return currentPage != numPages;
}
private boolean isNotFirstPage() {
return currentPage != FIRST_PAGE;
}
}
private class PrintUIWindow implements Printable, ActionListener {
/*
* (non-Javadoc)
*
* #see java.awt.print.Printable#print(java.awt.Graphics,
* java.awt.print.PageFormat, int)
*/
#Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
int pagenum = pageIndex+1;
if (pagenum < 1 || pagenum > pdfFile.getNumPages ())
return NO_SUCH_PAGE;
Graphics2D g2d = (Graphics2D) graphics;
AffineTransform at = g2d.getTransform ();
PDFPage pdfPage = pdfFile.getPage (pagenum);
Dimension dim;
dim = pdfPage.getUnstretchedSize ((int) pageFormat.getImageableWidth (),
(int) pageFormat.getImageableHeight (),
pdfPage.getBBox ());
Rectangle bounds = new Rectangle ((int) pageFormat.getImageableX (),
(int) pageFormat.getImageableY (),
dim.width,
dim.height);
PDFRenderer rend = new PDFRenderer (pdfPage, (Graphics2D) graphics, bounds,
null, null);
try
{
pdfPage.waitForFinish ();
rend.run ();
}
catch (InterruptedException ie)
{
//JOptionPane.showMessageDialog (this, ie.getMessage ());
}
g2d.setTransform (at);
g2d.draw (new Rectangle2D.Double (pageFormat.getImageableX (),
pageFormat.getImageableY (),
pageFormat.getImageableWidth (),
pageFormat.getImageableHeight ()));
return PAGE_EXISTS;
}
/*
* (non-Javadoc)
*
* #see
* java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent
* )
*/
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Inside action performed");
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
try
{
HashPrintRequestAttributeSet attset;
attset = new HashPrintRequestAttributeSet ();
//attset.add (new PageRanges (1, pdfFile.getNumPages ()));
if (printJob.printDialog (attset))
printJob.print (attset);
}
catch (PrinterException pe)
{
//JOptionPane.showMessageDialog (this, pe.getMessage ());
}
}
}
public PagePanel getPagePanel() {
return pagePanel;
}
public void setPDFFile(PDFFile pdfFile) {
this.pdfFile = pdfFile;
currentPage = FIRST_PAGE;
disableAllNavigationButton();
txtGoPage.setText(format(GO_PAGE_TEMPLATE, FIRST_PAGE, pdfFile.getNumPages()));
boolean moreThanOnePage = isMoreThanOnePage(pdfFile);
btnNextPage.setEnabled(moreThanOnePage);
btnLastPage.setEnabled(moreThanOnePage);
}
public static String format(String template, Object... args) {
template = String.valueOf(template); // null -> "null"
// start substituting the arguments into the '%s' placeholders
StringBuilder builder = new StringBuilder(template.length() + 16 * args.length);
int templateStart = 0;
int i = 0;
while (i < args.length) {
int placeholderStart = template.indexOf("%s", templateStart);
if (placeholderStart == -1) {
break;
}
builder.append(template.substring(templateStart, placeholderStart));
builder.append(args[i++]);
templateStart = placeholderStart + 2;
}
builder.append(template.substring(templateStart));
// if we run out of placeholders, append the extra args in square braces
if (i < args.length) {
builder.append(" [");
builder.append(args[i++]);
while (i < args.length) {
builder.append(", ");
builder.append(args[i++]);
}
builder.append(']');
}
return builder.toString();
}
public static void main(String[] args) {
try {
long heapSize = Runtime.getRuntime().totalMemory();
System.out.println("Heap Size = " + heapSize);
JFrame frame = new JFrame("PDF Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// load a pdf from a byte buffer
File file = new File("/home/swarupa/Downloads/2626OS-Chapter-5-Advanced-Theme.pdf");
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
final PDFFile pdffile = new PDFFile(buf);
PdfViewer pdfViewer = new PdfViewer();
pdfViewer.setPDFFile(pdffile);
frame.add(pdfViewer);
frame.pack();
frame.setVisible(true);
PDFPage page = pdffile.getPage(0);
pdfViewer.getPagePanel().showPage(page);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Where i am doing wrong.Can any one point me.
I think, that this should solve your problem ;) You've forgotten to set the window to be visible :)
static class Action1 implements ActionListener {
public void actionPerformed (ActionEvent e) {
JFrame parent = new JFrame();
JDialog jDialog = new JDialog();
Label label = new Label("Enter Word: ");
final JTextField jTextField = new JTextField(100);
JPanel panel = new JPanel();
parent.add(panel);
panel.add(label);
panel.add(jTextField);
parent.setLocationRelativeTo(null);
parent.setVisible(true);
}
}
Btw-why do you create that JDialog?
You create JDialog and JFrame, why? You never call setVisible(true), why?
What you expect from the Action1?
Sorry for posting this answer to your comment as a new post, but it was too long to post it as a comment. You just can't remove close and minimize buttons from JFrame. If you want some window without those buttons, you have to create and customize your own JDialog. Nevertheless there will still be a close button (X). You can make your JDialog undecorated and make it to behave more like JFrame when you implement something like this:
class CustomizedDialog extends JDialog {
public CustomizedDialog(JFrame frame, String str) {
super(frame, str);
super.setUndecorated(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
});
}
}
And then you can call it in your code with this:
CustomizedDialog myCustomizedDialog = new CustomizedDialog(new JFrame(), "My title");
JPanel panel = new JPanel();
panel.setSize(256, 256);
myCustomizedDialog.add(panel);
myCustomizedDialog.setSize(256, 256);
myCustomizedDialog.setLocationRelativeTo(null);
myCustomizedDialog.setVisible(true);
I hope, this helps :)
Im making a contact list, and my code compiles and runs, when you add the contact, type or email or phone its supposed to read them to you, the problem I have here is when I add the contacts and press next or previous, first or last it doesnt read the Name Contact, but it reads everything else...does it have to do something with spacing ? here is what I have...thanks
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
public class ContactSystem extends JFrame{
//Specify the size of five string fields in the record
final static int NAME_SIZE = 32;
final static int TYPE_SIZE = 32;
final static int CITY_SIZE = 20;
final static int PHONE_SIZE = 15;
final static int EMAIL_SIZE = 15;
final static int RECORD_SIZE =
(NAME_SIZE + TYPE_SIZE + CITY_SIZE + PHONE_SIZE + EMAIL_SIZE);
//access contact.dat using RandomAccessFile
private RandomAccessFile raf;
//Text Fields
private JTextField jbtName = new JTextField(NAME_SIZE);
private JTextField jbtType = new JTextField(TYPE_SIZE);
private JTextField jbtCity = new JTextField(CITY_SIZE);
private JTextField jbtPhone = new JTextField(PHONE_SIZE);
private JTextField jbtEmail = new JTextField(EMAIL_SIZE);
//Buttons
private JButton jbtAdd = new JButton("Add");
private JButton jbtFirst = new JButton("First");
private JButton jbtNext = new JButton("Next");
private JButton jbtPrevious = new JButton("Previous");
private JButton jbtLast = new JButton("Last");
public ContactSystem(){
//open or create a random access file
try {
raf = new RandomAccessFile("contact.txt", "rw");
}
catch(IOException ex) {
System.out.print("Error: " + ex);
System.exit(0);
}
//Panel p1 for holding labels Name , Type, Email or phone
JPanel p1 = new JPanel();
p1.setLayout(new GridLayout(3,1));
p1.add(new JLabel("Name Contact"));
p1.add(new JLabel("Email Address"));
p1.add(new JLabel("Type of Contact"));
//Panel jpPhone for holding Phone
JPanel jpPhone = new JPanel();
jpPhone.setLayout(new BorderLayout());
jpPhone.add(new JLabel("Phone"), BorderLayout.WEST);
jpPhone.add(jbtPhone, BorderLayout.CENTER);
//Panel jpEmail for holding Phone
JPanel jpEmail = new JPanel();
jpEmail.setLayout(new BorderLayout());
jpEmail.add(new JLabel("Phone"), BorderLayout.WEST);
jpEmail.add(jbtEmail, BorderLayout.CENTER);
// Panel p2 for holding jpPhone and jpEmail
JPanel p2 = new JPanel();
p2.setLayout(new BorderLayout());
p2.add(jpPhone, BorderLayout.WEST);
p2.add(jpPhone, BorderLayout.CENTER);
JPanel p3 = new JPanel();
p3.setLayout(new BorderLayout());
p3.add(jbtCity, BorderLayout.CENTER);
p3.add(p2, BorderLayout.EAST);
//panel p4 for holding jtfName, jtfType, and p3
JPanel p4 = new JPanel();
p4.setLayout(new GridLayout(3,1));
p4.add(jbtName);
p4.add(jbtType);
p4.add(p3);
//place p1 and p4 into jpContact
JPanel jpContact = new JPanel(new BorderLayout());
jpContact.add(p1, BorderLayout.WEST);
jpContact.add(p4, BorderLayout.CENTER);
//set panel with line border
jpContact.setBorder(new BevelBorder(BevelBorder.RAISED));
//add buttons to a panel
JPanel jpButton = new JPanel();
jpButton.add(jbtAdd);
jpButton.add(jbtFirst);
jpButton.add(jbtNext);
jpButton.add(jbtPrevious);
jpButton.add(jbtLast);
//add jpContact and jpButton to the frame
add(jpContact, BorderLayout.CENTER);
add(jpButton, BorderLayout.SOUTH);
jbtAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
writeContact();
}
});
jbtFirst.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
if (raf.length() > 0) readContact(0);
}
catch(IOException ex){
ex.printStackTrace();
}
}
});
jbtNext.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
try {
long currentPosition = raf.getFilePointer();
if (currentPosition < raf.length())
readContact(currentPosition);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
});
jbtPrevious.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
long currentPosition = raf.getFilePointer();
if(currentPosition - 2 * RECORD_SIZE > 0)
//why 2 * 2 * RECORD_SIZE? see the the follow-up remarks
readContact(currentPosition - 2 * 2 * RECORD_SIZE);
else
readContact(0);
}
catch(IOException ex){
ex.printStackTrace();
}
}
});
jbtLast.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
long lastPosition = raf.length();
if(lastPosition > 0)
//why 2 * RECORD_SIZE? see the follow up remarks
readContact(lastPosition - 2 * RECORD_SIZE);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
});
try {
if (raf.length() > 0) readContact(0);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
//write a record at the end of file
public void writeContact() {
try {
raf.seek(raf.length());
FixedLengthStringIO.writeFixedLengthString(
jbtName.getText(), NAME_SIZE, raf);
FixedLengthStringIO.writeFixedLengthString(
jbtType.getText(), TYPE_SIZE, raf);
FixedLengthStringIO.writeFixedLengthString(
jbtCity.getText(), CITY_SIZE, raf);
FixedLengthStringIO.writeFixedLengthString(
jbtPhone.getText(), PHONE_SIZE, raf);
FixedLengthStringIO.writeFixedLengthString(
jbtEmail.getText(), EMAIL_SIZE, raf);
}
catch (IOException ex) {
ex.printStackTrace();
}
}
//read a contact at the specific position
public void readContact(long position) throws IOException{
raf.seek(position);
String name = FixedLengthStringIO.readFixedLengthString(
NAME_SIZE, raf);
String type = FixedLengthStringIO.readFixedLengthString(
TYPE_SIZE, raf);
String city = FixedLengthStringIO.readFixedLengthString(
CITY_SIZE, raf);
String phone = FixedLengthStringIO.readFixedLengthString(
PHONE_SIZE, raf);
String email = FixedLengthStringIO.readFixedLengthString(
EMAIL_SIZE, raf);
jbtName.setText(name);
jbtType.setText(type);
jbtCity.setText(city);
jbtName.setText(phone);
jbtName.setText(email);
}
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ContactSystem frame = new ContactSystem();
frame.pack();
frame.setTitle("Contact System");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
fixedlengthstringIO class
import java.io.*;
public class FixedLengthStringIO {
//read fixed number of characters from datainput stream
public static String readFixedLengthString(int size,
DataInput in) throws IOException {
//declare an array of characters
char[] chars = new char[size];
//read fixed number of characters to the array
for(int i = 0; i < size; i++)
chars[i] = in.readChar();
return new String (chars);
}
//write fixed number of characters to a dataoutput stream
public static void writeFixedLengthString(String s, int size,
DataOutput out) throws IOException {
char[] chars = new char[size];
//fill an array of characters from the string
s.getChars(0, Math.min(s.length(), size), chars, 0);
//fill in blank characters in the rest of the array
for (int i = Math.min(s.length(), size); i < chars.length; i++)
chars[i] = ' ';
//create and write a new string padded with blank characters
out.writeChars(new String(chars));
}
}
here is when I type in contact name, type, email etc into the list
and when I press next or previous, or first or last, it doesnt read the name..
Glitch is in your readContact method, change this
public void readContact(long position) throws IOException {
raf.seek(position);
String name = FixedLengthStringIO.readFixedLengthString(
NAME_SIZE, raf);
String type = FixedLengthStringIO.readFixedLengthString(
TYPE_SIZE, raf);
String city = FixedLengthStringIO.readFixedLengthString(
CITY_SIZE, raf);
String phone = FixedLengthStringIO.readFixedLengthString(
PHONE_SIZE, raf);
String email = FixedLengthStringIO.readFixedLengthString(
EMAIL_SIZE, raf);
jbtName.setText(name);
jbtType.setText(type);
jbtCity.setText(city);
jbtPhone.setText(phone);
jbtEmail.setText(email);
}
Also instead of adding separate ActionListner command button you can implement like
public class ContactSystem extends JFrame implements ActionListener
{
.....
jbtAdd.addActionListener(this);
jbtFirst.addActionListener(this);
.....
#Override
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
if(actionCommand.equals("Add")) {
//do add stuff
} else if (actionCommand.equals("First")) {
// move first
}
}
}