Related
I have been killing my brain trying to figure out the problem, i am pretty sure the server connection is established neatly. i have even put some system prints to make sure the object is sent and received. let me post my code first.
RemoteService.java (interface):
package testrmi;
import java.rmi.*;
import javax.swing.JPanel;
public interface RemoteService extends Remote {
public Object[] getServiceList() throws RemoteException;
public Service getService(Object SvcKey) throws RemoteException;
}
Service.java (interface) used by Services offered by server:
package testrmi;
import javax.swing.*;
import java.io.*;
import java.rmi.Remote;
public interface Service extends Serializable {
public JPanel getGuiPanel();
}
RSimpl.java (RemoteService interface implementer)
package testrmi;
import java.rmi.*;
import java.rmi.server.*;
import java.util.*;
public class RSimpl implements RemoteService {
HashMap<String, Service> map;
public RSimpl() throws RemoteException
{
//super();
setUpServices();
}
public void setUpServices()
{
map = new HashMap<String, Service>();
map.put("Dice Roll Service", new DiceRoll());
map.put("Calculator Service", new Calculator());
map.put("Clock Service", new DigitalClock1());
// Keep Adding Services On The Go!
}
public Object[] getServiceList()
{
return map.keySet().toArray();
}
public Service getService(Object SvcKey)
{
System.out.println(SvcKey + " request has been recieved");
Service theService = map.get(SvcKey);
return theService;
}
}
Client.java (The client, this looks dirty :p )
package testrmi;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Client {
JFrame frame;
JPanel mainPanel;
JComboBox<Object> comboBox;
RemoteService server;
int i = 0;
Object[] error = {"Cannot Load Services"};
public void buildGUI()
{
frame = new JFrame("Service Browser");
mainPanel = new JPanel();
attemptConnect();
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
frame.getContentPane().add(BorderLayout.NORTH, comboBox);
frame.setVisible(true);
frame.setSize(300, 150);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
//centerFrame();
}
public void attemptConnect()
{
if(i==0)
{
i++;
Object[] services = getServiceList();
try {
comboBox = new JComboBox<Object>(services);
if (!services.toString().equalsIgnoreCase("Cannot Load Services"))
comboBox.addActionListener(new MyListListener());
}
catch(Exception ex) {
System.out.println("Cannot Establish Connection");
}
}
}
public void centerFrame()
{
Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) (d.getWidth()-frame.getWidth() / 2);
int y = (int) (d.getHeight()-frame.getHeight() / 2);
frame.setLocation(x, y);
}
public Object[] getServiceList()
{
boolean connectionsuccess = false;
Object[] objList = null;
try {
Registry rs = LocateRegistry.getRegistry("127.0.0.1", 9797); //CHANGE TO 192.168.1.97
server = (RemoteService) rs.lookup("RService");
connectionsuccess = true;
}
catch(Exception ex) {
Object[] options = {"Retry","Cancel"};
int o = JOptionPane.showOptionDialog(frame, "Cannot Establish Connection To The Server. \n Do You Want To Retry?", "Connection Error", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[0]);
if(o==0)
{
i=0;
attemptConnect();
}
else
{
i=1;
return error;
}
}
if(connectionsuccess) {
try {
objList = server.getServiceList();
}
catch(Exception ex) {
Object[] options = {"Retry","Cancel"};
int o = JOptionPane.showOptionDialog(frame, "Cannot Fetch Services List From The Server. \n Do You Want To Retry?", "Fetch Error", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[0]);
if(o==0)
{
i=0;
attemptConnect();
}
else
{
i=1;
return error;
}
}
}
return objList;
}
public void loadService(Object SvcKey)
{
try {
System.out.println(" I am going to send key: " + SvcKey);
Service svc = (Service) server.getService(SvcKey); //THIS IS CAUSING THE ERROR!
System.out.println("i am yet working"); //THIS LINE IS NOT WORKING
mainPanel.removeAll();
//frame.setContentPane(svc.getGuiPanel());
mainPanel.add(svc.getGuiPanel());
mainPanel.validate();
mainPanel.repaint();
frame.pack();
frame.setMinimumSize(new Dimension(300,150));
}
catch(Exception ex) {
Object[] options = {"Retry","Cancel"};
int o = JOptionPane.showOptionDialog(frame, "Cannot Load The Service From The Server. \n Do You Want To Retry?", "Connection Error", JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, options, options[0]);
if(o==0)
{
new MyListListener();
}
else
{
i=1;
frame.repaint();
}
}
}
public class MyListListener implements ActionListener
{
public void actionPerformed(ActionEvent ev)
{
Object selection = comboBox.getSelectedItem();
System.out.println(comboBox.getSelectedItem()); //DO NOT FORGET TO TEST THIS!
loadService(selection);
}
}
public static void main(String[] args)
{
Client cl = new Client();
cl.buildGUI();
}
}
StartServer.java (instantiates RSimpl object and starts server)
package testrmi;
import java.net.InetAddress;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class StartServer {
public static void main(String[] args)
{
try {
RSimpl obj = new RSimpl();
RemoteService stub = (RemoteService) UnicastRemoteObject.exportObject(obj, 0);
System.setProperty("java.rmi.server.hostname","192.168.1.97");
//RemoteService rs = new RSimpl();
Registry r = LocateRegistry.getRegistry(9797);
r.rebind("RService", stub);
System.out.println("Remote Service Is Running");
System.out.println(""+ InetAddress.getLocalHost().getHostAddress());
}
catch (Exception ex) {
ex.printStackTrace();
System.out.println("Sorry, Cannot Start Remote Service");
}
}
}
Calculator.java (Calculator Service, no need to check this)
package testrmi;
import javax.script.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.Serializable;
public class Calculator implements Service, Serializable {
JPanel mainPanel;
public JPanel getGuiPanel()
{
mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
//JPanel p1 = new JPanel();
//p1.setLayout(new GridLayout(4,4));
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
JPanel p4 = new JPanel();
final JTextField t = new JTextField(10);
t.setEditable(false);
t.setBackground(Color.green);
t.setBorder(BorderFactory.createLineBorder(Color.BLACK, 2));
Font myFont = new Font("MS Sans Serif", Font.BOLD, 24);
t.setFont(myFont);
mainPanel.add(t,BorderLayout.NORTH);
final JButton n1 = new JButton("1");
n1.setFocusable(false);
n1.setFont(myFont);
n1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String num1 = n1.getText();
String global = t.getText();
global = global.concat(num1);
t.setText(global);
}
});
final JButton n2 = new JButton("2");
n2.setFocusable(false);
n2.setFont(myFont);
n2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String num1 = n2.getText();
String global = t.getText();
global = global.concat(num1);
t.setText(global);
}
});
final JButton n3 = new JButton("3");
n3.setFocusable(false);
n3.setFont(myFont);
n3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String num1 = n3.getText();
String global = t.getText();
global = global.concat(num1);
t.setText(global);
}
});
final JButton n4 = new JButton("4");
n4.setFocusable(false);
n4.setFont(myFont);
n4.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String num1 = n4.getText();
String global = t.getText();
global = global.concat(num1);
t.setText(global);
}
});
final JButton n5 = new JButton("5");
n5.setFocusable(false);
n5.setFont(myFont);
n5.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String num1 = n5.getText();
String global = t.getText();
global = global.concat(num1);
t.setText(global);
}
});
final JButton n6 = new JButton("6");
n6.setFocusable(false);
n6.setFont(myFont);
n6.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String num1 = n6.getText();
String global = t.getText();
global = global.concat(num1);
t.setText(global);
}
});
final JButton n7 = new JButton("7");
n7.setFocusable(false);
n7.setFont(myFont);
n7.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String num1 = n7.getText();
String global = t.getText();
global = global.concat(num1);
t.setText(global);
}
});
final JButton n8 = new JButton("8");
n8.setFocusable(false);
n8.setFont(myFont);
n8.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String num1 = n8.getText();
String global = t.getText();
global = global.concat(num1);
t.setText(global);
}
});
final JButton n9 = new JButton("9");
n9.setFocusable(false);
n9.setFont(myFont);
n9.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String num1 = n9.getText();
String global = t.getText();
global = global.concat(num1);
t.setText(global);
}
});
final JButton n10 = new JButton("0");
n10.setFocusable(false);
n10.setFont(myFont);
n10.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String num1 = n10.getText();
String global = t.getText();
global = global.concat(num1);
t.setText(global);
}
});
final JButton n11 = new JButton("+");
n11.setFocusable(false);
n11.setFont(myFont);
n11.setForeground(Color.MAGENTA);
n11.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String num1 = n11.getText();
String global = t.getText();
global = global.concat(num1);
t.setText(global);
}
});
final JButton n12 = new JButton("-");
n12.setFocusable(false);
n12.setFont(myFont);
n12.setForeground(Color.MAGENTA);
n12.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String num1 = n12.getText();
String global = t.getText();
global = global.concat(num1);
t.setText(global);
}
});
final JButton n13 = new JButton("*");
n13.setFocusable(false);
n13.setFont(myFont);
n13.setForeground(Color.MAGENTA);
n13.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String num1 = n13.getText();
String global = t.getText();
global = global.concat(num1);
t.setText(global);
}
});
final JButton n14 = new JButton("/");
n14.setFocusable(false);
n14.setFont(myFont);
n14.setForeground(Color.MAGENTA);
n14.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
String num1 = n14.getText();
String global = t.getText();
global = global.concat(num1);
t.setText(global);
}
});
final JButton n15 = new JButton("=");
n15.setFocusable(false);
n15.setFont(myFont);
n15.setForeground(Color.BLUE);
n15.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
//String num1 = n15.getText();
String global = t.getText();
//global = global.concat(num1);
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
try {
String s = engine.eval(global).toString();
t.setText(s);
}
catch (ScriptException e1) {
e1.printStackTrace();
}
}
});
final JButton n16 = new JButton("C");
n16.setFocusable(false);
n16.setFont(myFont);
n16.setForeground(Color.RED);
n16.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
//String num1 = n16.getText();
String global = t.getText();
global = null;
t.setText(global);
}
});
p1.add(n1);
p1.add(n2);
p1.add(n3);
p1.add(n4);
p2.add(n5);
p2.add(n6);
p2.add(n7);
p2.add(n8);
p3.add(n9);
p3.add(n10);
p3.add(n11);
p3.add(n12);
p4.add(n13);
p4.add(n14);
p4.add(n15);
p4.add(n16);
JPanel pPanel = new JPanel();
pPanel.setLayout(new BoxLayout(pPanel, BoxLayout.Y_AXIS));
pPanel.add(p1);
pPanel.add(p2);
pPanel.add(p3);
pPanel.add(p4);
mainPanel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
mainPanel.add(pPanel);
return mainPanel;
}
}
DiceRoll.java (DiceRoll Service, no need to check this)
package testrmi;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DiceRoll implements Service {
int i = 0;
int h = 0;
JPanel mainPanel;
JButton roll;
MyDrawPanel drawPanel;
public JPanel getGuiPanel()
{
mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
roll = new JButton("Roll The Dice!");
roll.setFont(new Font("Comic Sans Ms", Font.BOLD, 16));
roll.setFocusable(false);
roll.setAlignmentX(Component.CENTER_ALIGNMENT);
roll.addActionListener(new rollListener());
drawPanel = new MyDrawPanel();
drawPanel.setPreferredSize(new Dimension(150,150));
mainPanel.add(roll);
mainPanel.add(Box.createRigidArea(new Dimension(0,10)));
mainPanel.add(drawPanel);
mainPanel.setBorder(BorderFactory.createEmptyBorder(5,0,5,0));
return mainPanel;
}
public int roll()
{
while (i==0 || i==h)
{
i = (int) (Math.random()*7);
}
h = i;
return i;
}
public class rollListener implements ActionListener
{
public void actionPerformed(ActionEvent ev)
{
int x = roll();
drawPanel.sendNum(x);
drawPanel.repaint();
}
}
public class MyDrawPanel extends JPanel
{
Graphics g;
int least = 0, x;
int fx=0, fy=0, fw=150, fh=150;
int dw=100, dh=100;
int dx=((fw-dw)/2), dy=((fh-dh)/2);
int dxc,dyc,dx1,dy1,dx2,dy2,dx3,dy3,dx4,dy4,dx5,dy5,dx6,dy6;
public void paintComponent(Graphics gn)
{
g = gn;
super.paintComponent(g);
g.setColor(Color.LIGHT_GRAY);
g.fillRect(fx, fy, fw, fh);
g.setColor(Color.WHITE);
g.fillRoundRect(dx, dy, dw, dh, 30, 30);
g.setColor(Color.BLACK); // set black for dots and border
g.drawRoundRect(dx, dy, dw, dh, 30, 30);
if(least>=1)
{
if(x==1)
{
g.fillOval(dxc, dyc, 20, 20);
}
else if(x==2)
{
g.fillOval(dx1, dy1, 20, 20);
g.fillOval(dx6, dy6, 20, 20);
}
else if(x==3)
{
g.fillOval(dx1, dy1, 20, 20);
g.fillOval(dxc, dyc, 20, 20);
g.fillOval(dx6, dy6, 20, 20);
}
else if(x==4)
{
g.fillOval(dx1, dy1, 20, 20);
g.fillOval(dx2, dy2, 20, 20);
g.fillOval(dx5, dy5, 20, 20);
g.fillOval(dx6, dy6, 20, 20);
}
else if(x==5)
{
g.fillOval(dx1, dy1, 20, 20);
g.fillOval(dx2, dy2, 20, 20);
g.fillOval(dxc, dyc, 20, 20);
g.fillOval(dx5, dy5, 20, 20);
g.fillOval(dx6, dy6, 20, 20);
}
else if(x==6)
{
g.fillOval(dx1, dy1, 20, 20);
g.fillOval(dx2, dy2, 20, 20);
g.fillOval(dx3, dy3, 20, 20);
g.fillOval(dx4, dy4, 20, 20);
g.fillOval(dx5, dy5, 20, 20);
g.fillOval(dx6, dy6, 20, 20);
}
}
}
public void sendNum(int xx)
{
least = 1;
x = xx;
// REMEMBER: dx+40=CENTER_X and dy+40=CENTER_Y because dice size 100, dot size 20
dxc=dx+40;
dyc=dy+40;
dx1=dx+10;
dy1=dy+10;
dx2=dx+70;
dy2=dy+10;
dx3=dx+10;
dy3=dy+40;
dx4=dx+70;
dy4=dy+40;
dx5=dx+10;
dy5=dy+70;
dx6=dx+70;
dy6=dy+70;
}
} // close class MyDrawPanel
}
DigitalClock1.java (no need to check -- these are only for compilation purposes)
package testrmi;
import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import java.awt.event.ActionEvent;
public class DigitalClock1 implements Service
{
public JPanel getGuiPanel()
{
SimpleDigitalClock clock1 = new SimpleDigitalClock();
return clock1;
}
static class SimpleDigitalClock extends JPanel
{
String stringTime;
int hour, minute, second;
String aHour = "";
String bMinute = "";
String cSecond = "";
public void setStringTime(String abc)
{
this.stringTime = abc;
}
public int Number(int a, int b)
{
return (a <= b) ? a : b;
}
SimpleDigitalClock()
{
Timer t = new Timer(1000, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
repaint();
}
});
t.start();
}
#Override
public void paintComponent(Graphics v)
{
super.paintComponent(v);
Calendar rite = Calendar.getInstance();
hour = rite.get(Calendar.HOUR_OF_DAY);
minute = rite.get(Calendar.MINUTE);
second = rite.get(Calendar.SECOND);
if (hour < 10)
{
this.aHour = "0";
}
if (hour >= 10)
{
this.aHour = "";
}
if (minute < 10)
{
this.bMinute = "0";
}
if (minute >= 10)
{
this.bMinute = "";
}
if (second < 10)
{
this.cSecond = "0";
}
if (second >= 10)
{
this.cSecond = "";
}
setStringTime(aHour + hour + ":" + bMinute+ minute + ":" + cSecond + second);
v.setColor(Color.BLACK);
int length = Number(this.getWidth(),this.getHeight());
Font Font1 = new Font("Comic Sans MS", Font.PLAIN, length / 5);
v.setFont(Font1);
v.drawString(stringTime, (int) length/6, length/2);
}
#Override
public Dimension getPreferredSize()
{
return new Dimension(200, 200);
}
}
}
I am running start rmiregistry 9797 from the directory in which the testrmi directory(package) is also placed. Then I run java testrmi.StartServer from the same directory. I get the server is running message, then I run the client from another directory but with same package name, which only contains Client.class, RemoteService.class and Service.class; the client starts fine, displays all three services, but when I select from the list, I get the exception error 'Cannot load service, retry?'.
NOTE: The client loads the services properly if I copy the services (calculator.class, diceroll.class and digitalclock1.class) in the client package directory. I don't want the services to be accessible to the clients directly without connecting to server.
If you want to be able to return serializable objects to the client that aren't in the client's classpath, you need to use the RMI codebase feature, which among other things requires you to deploy a codebase server, and use a SecurityManager at the client.
I have a swing application where the user inputs a number into two of the three fields, and my application does Pythagoras Theorem on those two numbers, and sets the answer field with the answer. However, the three fields (hypotenuse, short side 1, short side 2) are all returning 0 (shorter side 1 and shorter side 2 are different fields, forgot to add the : there), and 0 is the default value. This is not the case for other windows, this is only the case for the Maths tab. My question is, what is the problem?
Here is a screenshot of the error:
And here is the code:
Entry.java
package Entry;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JMenuBar;
import Settings.SettingsLoader;
import Window.ErrorWindow;
import Window.SmallLinkWindow;
import Window.Window;
import Window.WindowEntry;
public class Entry {
public static JFrame frame;
public static File file;
public static JInternalFrame currentframe;
public static void main(String[] args){
file = new File("settings.txt");
frame = new JFrame("GUI_Base");
JMenuBar menu = new JMenuBar();
JMenuBar bottom = new JMenuBar();
SmallLinkWindow[] smallwindows = WindowEntry.getSmallWindows();
for(int i = 0; i < smallwindows.length; i++){
SmallLinkWindow window = smallwindows[i];
JButton button = window.getButton(); //ActionListener already added at this point.
button.addActionListener(getActionListener(window));
bottom.add(button);
}
List<String> data = readAllData();
SettingsLoader loader = new SettingsLoader(data);
loader.obtainSettings();
Window[] windows = WindowEntry.getAllWindows();
for(int i = 0; i < windows.length; i++){
Window window = windows[i];
JButton item = new JButton(window.getName());
item.addActionListener(getActionListener(window));
menu.add(item);
}
currentframe = windows[0].getInsideFrame();
menu.add(getRefresh(), BorderLayout.EAST);
frame.setSize(2000, 1000);
frame.add(menu, BorderLayout.NORTH);
frame.add(bottom, BorderLayout.SOUTH);
frame.getRootPane().setBorder(BorderFactory.createLineBorder(Color.BLACK, 5));
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
System.out.println("Loaded!");
}
private static JButton getRefresh() {
try {
BufferedImage image = ImageIO.read(new File("refresh.png"));
int type = image.getType() == 0? BufferedImage.TYPE_INT_ARGB : image.getType();
image = resizeImage(image, type, 25, 25);
ImageIcon icon = new ImageIcon(image);
JButton label = new JButton(icon);
label.addActionListener(getActionListener());
return label;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private static ActionListener getActionListener() {
return new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
frame.repaint();
}
};
}
//Copied from http://www.mkyong.com/java/how-to-resize-an-image-in-java/
public static BufferedImage resizeImage(BufferedImage originalImage, int type, int width, int height){
BufferedImage resizedImage = new BufferedImage(width, height, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, width, height, null);
g.dispose();
return resizedImage;
}
private static ActionListener getActionListener(SmallLinkWindow window) {
ActionListener listener = new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
Entry.frame.remove(currentframe);
JInternalFrame frame = window.getInsideFrame();
frame.setSize(1400, 925);
Entry.frame.add(frame);
currentframe = frame;
frame.setVisible(true);
}
};
return listener;
}
private static ActionListener getActionListener(Window window) {
ActionListener listener = new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
Entry.frame.remove(currentframe);
JInternalFrame frame = window.getInsideFrame();
frame.setSize(1400, 925);
Entry.frame.add(frame);
currentframe = frame;
frame.setVisible(true);
}
};
return listener;
}
private static List<String> readAllData() {
try {
return Files.readAllLines(file.toPath());
} catch (IOException e) {
ErrorWindow.forException(e);
}
ErrorWindow.forException(new RuntimeException("Unable to read file!"));
System.exit(1);
return null;
}
}
MathWindow.java
package Window;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import Math.Pythagoras;
import Math.Trig;
import Math.TrigValue;
import Math.TrigonometryException;
import Settings.GUISetting;
public class MathWindow implements Window {
private Color colour;
private JSplitPane splitPane;
#Override
public String getName() {
return "Maths";
}
#Override
public JInternalFrame getInsideFrame() {
JInternalFrame frame = new JInternalFrame();
JSplitPane pane = new JSplitPane();
pane.setDividerLocation(300);
JPanel panel = new JPanel();
panel.setSize(300, 925);
JButton pyth = new JButton();
JButton trig = new JButton();
pyth.setText("Pythagoars theorem");
trig.setText("Trigonometry");
pyth.setSize(300, 200);
trig.setSize(300, 200);
pyth.addActionListener(getActionListenerForPythagoras());
trig.addActionListener(getActionListenerForTrignomotry());
panel.setLayout(new GridLayout(0,1));
panel.add(pyth);
panel.add(trig);
pane.setLeftComponent(panel);
splitPane = pane;
frame.getContentPane().add(pane);
return frame;
}
private ActionListener getActionListenerForPythagoras() {
return new ActionListener(){
#Override
public void actionPerformed(ActionEvent event) {
JPanel overseePanel = new JPanel();
JTextField hypField = new JTextField();
JTextField aField = new JTextField();
JTextField bField = new JTextField();
JLabel hypLabel = new JLabel();
JLabel aLabel = new JLabel();
JLabel bLabel = new JLabel();
JButton button = new JButton();
JTextField field = new JTextField();
hypLabel.setText("Hypotenuse");
aLabel.setText("Small side 1");
bLabel.setText("Small side 2");
hypLabel.setSize(400, hypLabel.getHeight());
aLabel.setSize(400, aLabel.getHeight());
bLabel.setSize(400, bLabel.getHeight());
hypField.setText("0");
aField.setText("0");
bField.setText("0");
hypField.setSize(400, hypLabel.getHeight());
aField.setSize(400, aLabel.getHeight());
bField.setSize(400, bLabel.getHeight());
button.setText("Work it out!");
button.addActionListener(getActionListenerForPythagorasFinal(hypField.getText(), aField.getText(), bField.getText(), field));
overseePanel.setLayout(new GridLayout(0,1));
overseePanel.add(hypLabel, BorderLayout.CENTER);
overseePanel.add(hypField, BorderLayout.CENTER);
overseePanel.add(aLabel, BorderLayout.CENTER);
overseePanel.add(aField, BorderLayout.CENTER);
overseePanel.add(bLabel, BorderLayout.CENTER);
overseePanel.add(bField, BorderLayout.CENTER);
overseePanel.add(button);
overseePanel.add(field);
splitPane.setRightComponent(overseePanel);
}
};
}
protected ActionListener getActionListenerForPythagorasFinal(String hyp, String s1, String s2, JTextField field) {
return new ActionListener(){
private Pythagoras p = new Pythagoras();
#Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("Hypotenuse: " + hyp);
System.out.println("Shorter side 1" + s1);
System.out.println("Shorter side 2" + s2);
if(hyp.equals("0")){
double a = Double.parseDouble(s1);
double b = Double.parseDouble(s2);
if(a == 3 && b == 4 || a == 4 && b == 3) System.out.println("The result should be 5!");
field.setText(String.valueOf(p.getHypotenuse(a, b)));
}else if(s1.equals("0")){
double c = Double.parseDouble(hyp);
double b = Double.parseDouble(s2);
field.setText(String.valueOf(p.getShorterSide(b, c)));
}else if(s2.equals("0")){
double c = Double.parseDouble(hyp);
double a = Double.parseDouble(s1);
field.setText(String.valueOf(p.getShorterSide(a, c)));
}else throw new IllegalArgumentException("All of the fields have stuff in them!");
}
};
}
private ActionListener getActionListenerForTrignomotry(){
return new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
JPanel overseePanel = new JPanel();
JTextField hypField = new JTextField();
JTextField aField = new JTextField();
JTextField bField = new JTextField();
JTextField anField = new JTextField();
JLabel hypLabel = new JLabel();
JLabel aLabel = new JLabel();
JLabel bLabel = new JLabel();
JLabel anLabel = new JLabel();
JButton button = new JButton();
JTextField field = new JTextField();
hypLabel.setText("Hypotenuse");
aLabel.setText("Opposite");
bLabel.setText("Adjacent");
anLabel.setText("Angle size");
hypLabel.setSize(400, hypLabel.getHeight());
aLabel.setSize(400, aLabel.getHeight());
bLabel.setSize(400, bLabel.getHeight());
anLabel.setSize(400, anLabel.getHeight());
hypField.setText("0");
aField.setText("0");
bField.setText("0");
anField.setText("0");
hypField.setSize(400, hypLabel.getHeight());
aField.setSize(400, aLabel.getHeight());
bField.setSize(400, bLabel.getHeight());
anField.setSize(400, anLabel.getHeight());
button.setText("Work it out!");
button.addActionListener(getActionListenerForTrigonomotryFinal(hypField.getText(), aField.getText(), bField.getText(), anField.getText(), field));
overseePanel.setLayout(new GridLayout(0,1));
overseePanel.add(hypLabel, BorderLayout.CENTER);
overseePanel.add(hypField, BorderLayout.CENTER);
overseePanel.add(aLabel, BorderLayout.CENTER);
overseePanel.add(aField, BorderLayout.CENTER);
overseePanel.add(bLabel, BorderLayout.CENTER);
overseePanel.add(bField, BorderLayout.CENTER);
overseePanel.add(anLabel, BorderLayout.CENTER);
overseePanel.add(anField, BorderLayout.CENTER);
overseePanel.add(button);
overseePanel.add(field);
splitPane.setRightComponent(overseePanel);
}
};
}
//a == opposite, b == adjacent
protected ActionListener getActionListenerForTrigonomotryFinal(String hyp,
String a, String b, String an, JTextField field) {
return new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
Trig trigonometry = new Trig();
double value = 0.000;
if(an == "0"){
if(hyp == "0"){
int shorta = Integer.parseInt(a);
int shortb = Integer.parseInt(b);
try {
TrigValue tA = new TrigValue(TrigValue.OPPOSITE, shorta);
TrigValue tB = new TrigValue(TrigValue.ADJACENT, shortb);
value = trigonometry.getAngleSize(tA, tB);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}else if(a == "0"){
int hypotenuse = Integer.parseInt(hyp);
int shortb = Integer.parseInt(b);
try {
TrigValue tH = new TrigValue(TrigValue.HYPOTENUSE, hypotenuse);
TrigValue tB = new TrigValue(TrigValue.ADJACENT, shortb);
value = trigonometry.getAngleSize(tH, tB);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}else if(b == "0"){
int hypotenuse = Integer.parseInt(hyp);
int shorta = Integer.parseInt(a);
try {
TrigValue tA = new TrigValue(TrigValue.OPPOSITE, shorta);
TrigValue tH = new TrigValue(TrigValue.HYPOTENUSE, hypotenuse);
value = trigonometry.getAngleSize(tA, tH);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}
}else{
int angle = Integer.parseInt(an);
if(angle >= 90) throw new IllegalArgumentException("Angle is bigger than 90");
if(hyp.equals("0")){
if(a.equals("?")){
int shortb = Integer.parseInt(b);
try {
TrigValue tB = new TrigValue(TrigValue.ADJACENT, shortb);
TrigValue tA = new TrigValue(TrigValue.OPPOSITE);
value = trigonometry.getSideLength(tB, angle, tA);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}else if(b.equals("?")){
int shorta = Integer.parseInt(a);
try {
TrigValue tB = new TrigValue(TrigValue.ADJACENT);
TrigValue tA = new TrigValue(TrigValue.OPPOSITE, shorta);
value = trigonometry.getSideLength(tA, angle, tB);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}else throw new IllegalArgumentException("We already know what we want to know.");
}else if(a.equals("0")){
if(hyp.equals("?")){
int shortb = Integer.parseInt(b);
try {
TrigValue tB = new TrigValue(TrigValue.ADJACENT, shortb);
TrigValue tH = new TrigValue(TrigValue.HYPOTENUSE);
value = trigonometry.getSideLength(tB, angle, tH);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}else if(b.equals("?")){
int h = Integer.parseInt(hyp);
try {
TrigValue tB = new TrigValue(TrigValue.ADJACENT);
TrigValue tH = new TrigValue(TrigValue.HYPOTENUSE, h);
value = trigonometry.getSideLength(tH, angle, tB);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}else throw new IllegalArgumentException("We already know what we want to know.");
}else if(b.equals("0")){
if(hyp.equals("?")){
int shorta = Integer.parseInt(a);
try {
TrigValue tA = new TrigValue(TrigValue.OPPOSITE, shorta);
TrigValue tH = new TrigValue(TrigValue.HYPOTENUSE);
value = trigonometry.getSideLength(tA, angle, tH);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}else if(a.equals("?")){
int h = Integer.parseInt(hyp);
try {
TrigValue tA = new TrigValue(TrigValue.OPPOSITE);
TrigValue tH = new TrigValue(TrigValue.HYPOTENUSE, h);
value = trigonometry.getSideLength(tH, angle, tA);
} catch (TrigonometryException e1) {
e1.printStackTrace();
}
}
}
}
field.setText(String.valueOf(value));
}
};
}
#Override
public GUISetting[] getSettings() {
GUISetting setting = new GUISetting("Show working", "Maths");
GUISetting setting2 = new GUISetting("Round", "Maths");
return new GUISetting[]{setting, setting2};
}
#Override
public void setColour(Color c) {
colour = c;
}
#Override
public Color getCurrentColour() {
return colour;
}
}
If I need to add anything else please add a comment.
You create a new instance of JTextField, you then pass it's text property to the getActionListenerForPythagorasFinal method, so it no longer has what "will" be entered into the fields, only what it's initial value is (""), thus it's completely unable to perform the calculation on the fields in question
You could try passing the fields themselves to the method instead, but as a general piece of advice, I would create a custom class which contains the fields and associated actions which you can create whenever you need it, making significantly easier to manage and maintain
So here is my GUI as you can see.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Frame1 {
private JFrame frame;
private JTextField textFieldnum1;
private JTextField textFieldnum2;
private JTextField textFieldAns;
private Termostat thermo;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Frame1 window = new Frame1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Frame1() {
initialize();
}
private void initialize() {
thermo = new Termostat();
frame = new JFrame();
frame.setBounds(100, 100, 696, 250);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textFieldnum1 = new JTextField();
textFieldnum1.setBounds(176, 11, 147, 46);
frame.getContentPane().add(textFieldnum1);
textFieldnum1.setColumns(10);
textFieldnum2 = new JTextField();
textFieldnum2.setBounds(176, 154, 147, 46);
frame.getContentPane().add(textFieldnum2);
textFieldnum2.setColumns(10);
JButton btnNewButton = new JButton("Convert to celcius");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
double myf = thermo.convertToCelcius(Double.parseDouble(textFieldnum1.getText()));
textFieldAns.setText(String.valueOf(myf));
}
});
btnNewButton.setBounds(0, 0, 171, 68);
frame.getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("Convert to fahrenheit");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double myf = thermo.convertToFahrenheit(Double.parseDouble(textFieldnum2.getText()));
textFieldAns.setText(String.valueOf(myf));
}
});
btnNewButton_1.setBounds(0, 143, 171, 68);
frame.getContentPane().add(btnNewButton_1);
textFieldAns = new JTextField();
textFieldAns.setBounds(354, 90, 147, 46);
frame.getContentPane().add(textFieldAns);
textFieldAns.setColumns(10);
JLabel lblNewLabel = new JLabel("Converted");
lblNewLabel.setBounds(285, 94, 112, 38);
frame.getContentPane().add(lblNewLabel);
}
}
And here comes my problem. When i made my class that i wanna run the input in to calculate celcius to fahrenheit, i dont want it to crash when i type anything else than numbers. but i cant get it to work so i need you guys help to get the try catch to work.
Im very thankful for all help i get.
import javax.swing.JOptionPane;
public class Termostat {
public double convertToCelcius(double input) {
double far = 0;
try {
far = (input - 32) * 5 / 9;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Wrong input");
return far;
}
return far;
}
public double convertToFahrenheit(double input) {
double cel = 1;
try {
cel = (input * 9 / 5) + 32;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Wrong input");
return cel;
}
return cel;
}
}
This is the line where you get probably an Exception:
double myf = thermo.convertToFahrenheit(Double.parseDouble(textFieldnum2.getText()));
So guard it with a NumberFormatException (parseDouble).
You can use the NumberUtil.isNumber(str) to check if the input is a number. Here is more information
you must use try catch when you want to parse text field texts to Double using this method Double.parseDouble(text)
write them them like this and remove your try catches inside your convertToFahrenheit and convertToCelcius methods
JButton btnNewButton_1 = new JButton("Convert to fahrenheit");
btnNewButton_1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
try { // start trying to parse input string to double
double myf = thermo.convertToFahrenheit(Double.parseDouble(textFieldnum2.getText()));
textFieldAns.setText(String.valueOf(myf));
} catch (NumberFormatException ex) { // catch the exception that you mentioned
JOptionPane.showMessageDialog(null, "Wrong input");
textFieldAns.setText("");
}
}
});
my question is i want to add full background image if JDialog, this JDialog is created by JOptionPane. This image does not cover full Dialog.
If you have any solution please let me know.
public class BrowseFilePath {
public static final String DIALOG_NAME = "what-dialog";
public static final String PANE_NAME = "what-pane";
private static JDialog loginRegister;
private static String path;
private static JPanel Browse_panel = new JPanel(new BorderLayout());
private static JLabel pathLbl = new JLabel("Please Choose Folder / File");
private static JTextField regtxt_file = new JTextField(30);
private static JButton browse_btn = new JButton("Browse");
private static JButton ok_btn = new JButton("Ok");
private static JButton close_btn = new JButton("Cancel");
/*public static void main(String [] arg){
showFileDialog();
}*/
public static void showFileDialog() {
JOptionPane.setDefaultLocale(null);
JOptionPane pane = new JOptionPane(createRegInputComponent());
pane.setName(PANE_NAME);
loginRegister = pane.createDialog("ShareBLU");
/* try {
loginRegister.setContentPane(new JLabel(new ImageIcon(ImageIO.read(AlertWindow.getBgImgFilePath()))));
} catch (IOException e) {
e.printStackTrace();
}*/
loginRegister.setName(DIALOG_NAME);
loginRegister.setSize(380,150);
loginRegister.setVisible(true);
if(pane.getInputValue().equals("Ok")){
String getTxt = regtxt_file.getText();
BrowseFilePath.setPath(getTxt);
}
else if(pane.getInputValue().equals("Cancel")){
regtxt_file.setText("");
System.out.println("Pressed Cancel Button =======********=");
System.exit(0);
}
}
public static String getPath() {
return path;
}
public static void setPath(String path) {
BrowseFilePath.path = path;
}
private static JComponent createRegInputComponent() {
Browse_panel = new JBackgroundPanel();
Browse_panel.setLayout(new BorderLayout());
Box rows = Box.createVerticalBox();
Browse_panel.setBounds(0,0,380,150);
Browse_panel.add(pathLbl);
pathLbl.setForeground(Color.white);
pathLbl.setBounds(20, 20, 200, 20);
Browse_panel.add(regtxt_file);
regtxt_file.setToolTipText("Select File/Folder..");
regtxt_file.setBounds(20, 40, 220, 20);
Browse_panel.add(browse_btn);
browse_btn.setToolTipText("Browse");
browse_btn.setBounds(250, 40, 90, 20);
Browse_panel.add(ok_btn);
ok_btn.setToolTipText("Ok");
ok_btn.setBounds(40, 75, 80, 20);
Browse_panel.add(close_btn);
close_btn.setToolTipText("Cancel");
close_btn.setBounds(130, 75, 80, 20);
ActionListener chooseMe = createChoiceAction();
ok_btn.addActionListener(chooseMe);
close_btn.addActionListener(chooseMe);
browse_btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser();
int selection = JFileChooser.FILES_AND_DIRECTORIES;
fileChooser.setFileSelectionMode(selection);
fileChooser.setAcceptAllFileFilterUsed(false);
int rVal = fileChooser.showOpenDialog(null);
if (rVal == JFileChooser.APPROVE_OPTION) {
path = fileChooser.getSelectedFile().toString();
regtxt_file.setText(path);
}
}
});
rows.add(Box.createVerticalStrut(105));
Browse_panel.add(rows,BorderLayout.CENTER);
return Browse_panel;
}
public static ActionListener createChoiceAction() {
ActionListener chooseMe = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JButton choice = (JButton) e.getSource();
// find the pane so we can set the choice.
Container parent = choice.getParent();
while (!PANE_NAME.equals(parent.getName())) {
parent = parent.getParent();
}
JOptionPane pane = (JOptionPane) parent;
pane.setInputValue(choice.getText());
// find the dialog so we can close it.
while ((parent != null) && !DIALOG_NAME.equals(parent.getName()))
{
parent = parent.getParent();
//parent.setBounds(0, 0, 350, 150);
}
if (parent != null) {
parent.setVisible(false);
}
}
};
return chooseMe;
}
}
Don't use JOptionPane but use a full-blown JDialog. Set the content pane to a JComponent that overrides paintComponent() and returns an appropriate getPreferredSize().
Example code below:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestBackgroundImage {
private static final String BACKHGROUND_IMAGE_URL = "http://cache2.allpostersimages.com/p/LRG/27/2740/AEPND00Z/affiches/blue-fiber-optic-wires-against-black-background.jpg";
protected void initUI() throws MalformedURLException {
JDialog dialog = new JDialog((Frame) null, TestBackgroundImage.class.getSimpleName());
dialog.setModal(true);
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
final ImageIcon backgroundImage = new ImageIcon(new URL(BACKHGROUND_IMAGE_URL));
JPanel mainPanel = new JPanel(new BorderLayout()) {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(backgroundImage.getImage(), 0, 0, getWidth(), getHeight(), this);
}
#Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
size.width = Math.max(backgroundImage.getIconWidth(), size.width);
size.height = Math.max(backgroundImage.getIconHeight(), size.height);
return size;
}
};
mainPanel.add(new JButton("A button"), BorderLayout.WEST);
dialog.add(mainPanel);
dialog.setSize(400, 300);
dialog.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new TestBackgroundImage().initUI();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Don't forget to provide an appropriate parent Frame
I am making an application similar to a chat. For that purpose I have two JTextPanes, one where I'm writing and one that displays messages. This is the code that handles the transferring of text from input to display :
String input = textPane.getText();
if(!input.endsWith("\n")){
input+="\n";
}
StyledDocument doc = displayPane.getStyledDocument();
int offset = displayPane.getCaretPosition();
textPane.setText("");
try {
doc.insertString(offset, input, set);
} catch (BadLocationException ex) {
Logger.getLogger(ChatComponent.class.getName()).log(Level.SEVERE, null, ex);
}
The problem is that if i have colour on some words of the input text , the output is all coloured . So the colour is applied to all of the text when moved to display(while displayed correctly on input). Any suggestions on how i can move text properly?
Notice that same happens with other format as bold , italic etc
The text is already formatted on the input JTextPane . What i need to do
is transfer it as it is on a different JTextPane without having to check
the different style options
example
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
public class Fonts implements Runnable {
private String[] fnt;
private JFrame frm;
private JScrollPane jsp;
private JTextPane jta;
private int width = 450;
private int height = 300;
private GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
private StyledDocument doc;
private MutableAttributeSet mas;
private int cp = 0;
private Highlighter.HighlightPainter cyanPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.cyan);
private Highlighter.HighlightPainter redPainter = new DefaultHighlighter.DefaultHighlightPainter(Color.red);
private Highlighter.HighlightPainter whitePainter = new DefaultHighlighter.DefaultHighlightPainter(Color.white);
private int _count = 0;
private int _lenght = 0;
public Fonts() {
jta = new JTextPane();
doc = jta.getStyledDocument();
jsp = new JScrollPane(jta);
jsp.setPreferredSize(new Dimension(height, width));
frm = new JFrame("awesome");
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setLayout(new BorderLayout());
frm.add(jsp, BorderLayout.CENTER);
frm.setLocation(100, 100);
frm.pack();
frm.setVisible(true);
jta.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
fnt = ge.getAvailableFontFamilyNames();
mas = jta.getInputAttributes();
new Thread(this).start();
}
#Override
public void run() {
for (int i = 0; i < fnt.length; i++) {
StyleConstants.setBold(mas, false);
StyleConstants.setItalic(mas, false);
StyleConstants.setFontFamily(mas, fnt[i]);
StyleConstants.setFontSize(mas, 16);
dis(fnt[i]);
try {
Thread.sleep(75);
} catch (Exception e) {
e.printStackTrace();
}
StyleConstants.setBold(mas, true);
dis(fnt[i] + " Bold");
try {
Thread.sleep(75);
} catch (Exception e) {
e.printStackTrace();
}
StyleConstants.setItalic(mas, true);
dis(fnt[i] + " Bold & Italic");
try {
Thread.sleep(75);
} catch (Exception e) {
e.printStackTrace();
}
StyleConstants.setBold(mas, false);
dis(fnt[i] + " Italic");
try {
Thread.sleep(75);
} catch (Exception e) {
e.printStackTrace();
}
}
jta.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
public void dis(String s) {
_count++;
_lenght = jta.getText().length();
try {
doc.insertString(cp, s, mas);
doc.insertString(cp, "\n", mas);
} catch (Exception bla_bla_bla_bla) {
bla_bla_bla_bla.printStackTrace();
}
if (_count % 2 == 0) {
try {
jta.getHighlighter().addHighlight(1, _lenght - 1, cyanPainter);
} catch (BadLocationException bla_bla_bla_bla) {
}
} else if (_count % 3 == 0) {
try {
jta.getHighlighter().addHighlight(1, _lenght - 1, redPainter);
} catch (BadLocationException bla_bla_bla_bla) {
}
} else {
try {
jta.getHighlighter().addHighlight(1, _lenght - 1, whitePainter);
} catch (BadLocationException bla_bla_bla_bla) {
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Fonts fs = new Fonts();
}
});
}
}
In the absence of a good SSCCE, I really don't know how you adding colour to the text on your JTextPane, but hopefully this method might sort things out for you :
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
private void appendToTextPane(String name, Color c, String f)
{
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c);
aset = sc.addAttribute(aset, StyleConstants.FontFamily, f);
int len = Client.nPane.getDocument().getLength();
textPane.setCaretPosition(len);
textPane.setCharacterAttributes(aset, true);
textPane.replaceSelection(name);
}
With this you can give a different Color and Font to each String literal that will be added to your JTextPane.
Hope this new Code might help you in some way :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.AttributeSet;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyleContext;
public class TextPaneTest extends JFrame
{
private JPanel topPanel;
private JPanel bottomPanel;
private JTextPane tPane1;
private JTextPane tPane2;
private JButton button;
public TextPaneTest()
{
topPanel = new JPanel();
topPanel.setLayout(new GridLayout(1, 2));
bottomPanel = new JPanel();
bottomPanel.setBackground(Color.BLACK);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
StyleContext sc = StyleContext.getDefaultStyleContext();
AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, Color.BLUE);
aset = sc.addAttribute(aset, StyleConstants.FontFamily, "Lucida Console");
tPane1 = new JTextPane();
tPane1.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
tPane1.setCharacterAttributes(aset, false); // Add these settings to the other JTextPane also
tPane2 = new JTextPane();
tPane2.setCharacterAttributes(aset, false); // Mimic what the other JTextPane has
button = new JButton("ADD TO THE TOP JTEXTPANE");
button.setBackground(Color.DARK_GRAY);
button.setForeground(Color.WHITE);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
tPane1.setText(tPane2.getText());
}
});
add(topPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
topPanel.add(tPane1);
topPanel.add(tPane2);
bottomPanel.add(button);
pack();
tPane2.requestFocusInWindow();
setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new TextPaneTest();
}
});
}
}
Regards
This has been solved by merging the document models of the two panes. The solution is in this question: Keeping the format on text retrieval