我正在尝试创建一个新的按钮创建类,它将维度以及文本和图标作为参数。要做到这一点,我使用JButton类作为参考并添加我自己的东西。问题是在writeObject方法中,似乎需要添加按钮,.setWriteObjCounter表示只能从同一个包中访问它。有谁知道如何访问它? (除了把它放在包装中,因为我不能这样做)
import javax.accessibility.Accessible;
import javax.accessibility.AccessibleContext;
import javax.accessibility.AccessibleRole;
import javax.swing.*;
import javax.swing.plaf.ButtonUI;
import java.awt.*;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class JMButton extends AbstractButton implements Accessible {
private static final String uiClassID = "JMButtonUI";
//constructors for different inputs
public JMButton() {
this(null, null, 0, 0);
}
public JMButton(String text) {
this(text, null, 0, 0);
}
public JMButton(Icon icon) {
this(null, icon, 0, 0);
}
public JMButton(String text, Icon icon) {
this(text, icon, 0, 0);
}
public JMButton(String text, int width, int height) {
this(text, null, width, height);
}
public JMButton(Icon icon, int width, int height) {
this(null, icon, width, height);
}
public JMButton(int width, int heigth) {
this(null, null, width, heigth);
}
public JMButton(Action a) {
this();
setAction(a);
}
public JMButton(String text, Icon icon, int width, int height) {
setModel(new DefaultButtonModel());
init(text, icon);
if (width == 0) {
FontMetrics fontMetrics = getFontMetrics(getFont());
int buttonWidth = fontMetrics.stringWidth(text);
setSize(buttonWidth + 40, 40);
} else {
setSize(width, height);
}
}
//pulled from other button classes for functionality
public void updateUI() {
setUI((ButtonUI) UIManager.getUI(this));
}
public String getUIClassID() {
return uiClassID;
}
//PROBLEM!!
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
}
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJButton();
}
return accessibleContext;
}
protected class AccessibleJButton extends AccessibleAbstractButton {
public AccessibleRole getAccessibleRole() {
return AccessibleRole.PUSH_BUTTON;
}
}
答案 0 :(得分:0)
解决方法:
创建您在项目中扩展的类的相同包结构,并将类添加到其中。 因此,您的项目中将包含 javax.swing
package javax.swing;
import java.io.IOException;
import java.io.ObjectOutputStream;
import javax.accessibility.Accessible;
public class JMButton extends AbstractButton implements Accessible {
private static final String uiClassID = "JMButtonUI";
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
}
}